Search is not available for this dataset
qid
int64 1
74.7M
| question
stringlengths 16
65.1k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
117k
| response_k
stringlengths 3
61.5k
|
---|---|---|---|---|---|
5,203,338 | I am new to C#
What is the difference between
```
public string MyValue;
```
and
```
public string MyValue { get; set; }
```
I always assumed that both were same. Something was not working in my code. Using the latter form made it work. But don't know what is the difference. Can you help?
Thanks | 2011/03/05 | [
"https://Stackoverflow.com/questions/5203338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15065/"
] | If the "latter made it work", you are probably using data-binding; data-binding *usually* works only against properties (not fields). These can be explicit properties, or automatically implemented properties like in your example.
Note that changing from a field to a property can break serialization if you are using `BinaryFormatter` (which IMO is deeply flawed anyway), but properties are **very much** preferred over fields. Absolutely make this change ;p | Please check this...
[What's the difference between encapsulating a private member as a property and defining a property without a private member?](https://stackoverflow.com/questions/4267144/whats-the-difference-between-encapsulating-a-private-member-as-a-property-and-de)
it might help... |
5,203,338 | I am new to C#
What is the difference between
```
public string MyValue;
```
and
```
public string MyValue { get; set; }
```
I always assumed that both were same. Something was not working in my code. Using the latter form made it work. But don't know what is the difference. Can you help?
Thanks | 2011/03/05 | [
"https://Stackoverflow.com/questions/5203338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15065/"
] | If the "latter made it work", you are probably using data-binding; data-binding *usually* works only against properties (not fields). These can be explicit properties, or automatically implemented properties like in your example.
Note that changing from a field to a property can break serialization if you are using `BinaryFormatter` (which IMO is deeply flawed anyway), but properties are **very much** preferred over fields. Absolutely make this change ;p | **Needed for Data Annotations**
For ASP.NET 3.1, use automatically implemented public property for models that use Data Annotations like `[Required]`.
I learned the hard way that a public field won't work. `ModelState.IsValid` will always return `true`. |
56,208,694 | I am using SQLite.
Let's say I have a table like this one:
```
CREATE TABLE dates (
date1 DATE NOT NULL PRIMARY KEY,
date2 DATE NOT NULL
);
```
Now, I want date1 to be a certain date and date2 to be date1 + 10 days.
How can I insert values to the table by using only date1 to produce both of them?
only thing i could find on the internet was something like that, but it's obviously not working, except for the case that I replace date('date1',+10days)) with date('now',+10days), but this is not what I want:
```
insert into dates values('2012-01-01', date('date1','+10 days'))
```
Any ideas? | 2019/05/19 | [
"https://Stackoverflow.com/questions/56208694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11375958/"
] | Raise a trigger to automatically insert date2 every time you insert a date1 into the table.
```
CREATE TRIGGER date2_trigger AFTER INSERT ON dates
BEGIN
UPDATE dates SET date2 = DATE(NEW.date1, '+10 days') WHERE date1 = NEW.date1;
END;
-- insert date1 like so; date2 will be set automatically.
INSERT INTO dates(date1) VALUES('2012-01-01');
``` | Instead of INSERT...VALUES use INSERT...SELECT like this:
```
insert into dates (date1, date2)
select t.date1, date(t.date1, '+10 days')
from (
select '2012-01-01' as date1
union all
select '2012-01-02'
union all
....................
) t
```
See the [demo](https://www.db-fiddle.com/f/iYcCmrheqgMAQBf1X5kYUT/0).
Results:
```
| date1 | date2 |
| ---------- | ---------- |
| 2012-01-01 | 2012-01-11 |
| 2012-01-02 | 2012-01-12 |
``` |
127,573 | Is there a way to let the users edit their usernames? Today, I googled for such a code for a while and had no luck finding a solution except a few plugins. I didn't find any tutorial for doing so.
These are the plugins I found- [Username changer](http://wordpress.org/plugins/username-changer/) and [BuddyPress user name changer](http://buddydev.com/plugins/bp-username-changer/). The first plugin's interface is no good and I want to offer the users a native interface to edit user names. Brajesh's BuddyPress user name changer is similar to what I expected. But that works only if BuddyPress is setup. Could any suggest me a nice way to let the users edit their user names?
Plugins would help me. But I can also manage to code if someone guide me through.
**Update:**
I am looking for a solution to edit the default **usernames** because sometimes, there would be a problem with the default user name appearing for the public. When you use Social Networks via OAuth(Twitter and Google etc.) for your member login , the user accounts will created with prefixes like *Yourfullname-Google* or sometimes *Yourfullemailaddress-Google*.
The author URLs appear like this- *site.com/author/twitter-random-name* or *site.com/author/google-profile-address-uglyurl*. Here the user's profile URL appears ugly or lengthy and doesn't look in a normal way like-site.com/the-author-name
Also I use a plugin named [Quick Subscribe](http://wordpress.org/plugins/ajax-quick-subscribe/) which helps us to get users subscribe and register account just using their email addresses creating random passwords. Here the problem is that the the user names will be created based on the email address(ex: userfullemailaddressgmail.com). The plugin is not popular as it has to be, but that helps people like me to let the users subscribe with single email address.
The author URLs appear like this- *<http://site.com/author/author-full-email-addressgmailcom>*. The user's email address is blown out to the spammers. I can't resist using this subscribe plugin because of it's usability.
In such cases I want to let users edit their user names to save themselves being their email addresses revealed to the public. | 2013/12/25 | [
"https://wordpress.stackexchange.com/questions/127573",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/2078/"
] | You define priority. It's not a hack.
Maybe it's that you're looking for is `PHP_INT_MAX` which is a PHP constant. So you can put it as priority number. | If you want your CSS rule to apply, you must make it more specific. Of course if you add it the last one, it'll work, but if other person adds the same on the same priority, it fails. The best approach is to make something like:
`body .custom-class`
Or make it more deep specific, adding more IDs or classes to your selector. |
66,580,797 | I'm new to Python3 and I am working with large JSON objects. I have a large JSON object which has extra chars coming in between two JSON objects, in between the braces.
For example:
```
{"id":"121324343", "name":"foobar"}3$£_$£rvcfddkgga£($(>..bu&^783 { "id":"343554353", "name":"ABCXYZ"}'
```
These extra chars could be anything alphanumeric, special chars or ASCII. They appear in this large JSON multiple times and can be of any length. I'm trying to use regex to identify that pattern to remove them, but regex doesn't seem to work. Here is the regex I used:
```
(^}\n[a-zA-Z0-9]+{$)
```
Is there a way of identifying such patter using regex in python? | 2021/03/11 | [
"https://Stackoverflow.com/questions/66580797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15374451/"
] | You need to spearate multiple commands with semicolon (";"):
```
counter = 5
while counter > 0: print ("Counter =", counter); counter = counter - 1
```
However, as kabooya stated, this is not the pythonic way.
As you see, the correctly formatted source (in his answer) is much more readable. | Python syntax is white-space sensitive.
Don't write things on one line.
Do it like this:
```
counter = 5
while counter > 0:
print ("Counter =", counter)
counter = counter - 1
``` |
40,183,239 | Google released new support library v25 with BottomNavigationView
[![enter image description here](https://i.stack.imgur.com/R572H.gif)](https://i.stack.imgur.com/R572H.gif)
is there any way to remove items labels ? | 2016/10/21 | [
"https://Stackoverflow.com/questions/40183239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5033303/"
] | I hope I am not too late to the party here.
But as of Design Support Library 28.0.0-alpha1
you can use the property
```
app:labelVisibilityMode="unlabeled"
```
[![BottomNavigationView without labels](https://i.stack.imgur.com/QL6fW.png)](https://i.stack.imgur.com/QL6fW.png)
you can use other values "auto", "labeled" and "selected" as well. | I'd recommend to implement it by yourself as [sanf0rd gave in his answer](https://stackoverflow.com/a/40188794/1104612). But `AppCompatImageView` is not working for me. I've changed it to `ImageView`. And changed `getChildAt` to `findViewById`.
Also I hide all labels of unselected items.
```
private void centerMenuIcon() {
BottomNavigationMenuView menuView = getBottomMenuView();
if (menuView != null) {
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView menuItemView = (BottomNavigationItemView) menuView.getChildAt(i);
TextView smallText = (TextView) menuItemView.findViewById(R.id.smallLabel);
smallText.setVisibility(View.INVISIBLE);
//TextView largeText = (TextView) menuItemView.findViewById(R.id.largeLabel);
ImageView icon = (ImageView) menuItemView.findViewById(R.id.icon);
FrameLayout.LayoutParams params = (LayoutParams) icon.getLayoutParams();
params.gravity = Gravity.CENTER;
menuItemView.setShiftingMode(true);
}
}
}
``` |
40,183,239 | Google released new support library v25 with BottomNavigationView
[![enter image description here](https://i.stack.imgur.com/R572H.gif)](https://i.stack.imgur.com/R572H.gif)
is there any way to remove items labels ? | 2016/10/21 | [
"https://Stackoverflow.com/questions/40183239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5033303/"
] | Unfortunately this first version of BottomNavigationView came with a lot of limitations. And for now you can't remove the titles just using the support design API. So to solve this limitation while google doesn't implement it, you can do (using reflection):
**1. Set the titles empty in from bottom\_navigation\_menu.xml file.**
**2. Extends the BottomNavigationView:**
```
public class MyBottomNavigationView extends BottomNavigationView {
public MyBottomNavigationView(Context context, AttributeSet attrs) {
super(context, attrs);
centerMenuIcon();
}
private void centerMenuIcon() {
BottomNavigationMenuView menuView = getBottomMenuView();
if (menuView != null) {
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView menuItemView = (BottomNavigationItemView) menuView.getChildAt(i);
AppCompatImageView icon = (AppCompatImageView) menuItemView.getChildAt(0);
FrameLayout.LayoutParams params = (LayoutParams) icon.getLayoutParams();
params.gravity = Gravity.CENTER;
menuItemView.setShiftingMode(true);
}
}
}
private BottomNavigationMenuView getBottomMenuView() {
Object menuView = null;
try {
Field field = BottomNavigationView.class.getDeclaredField("mMenuView");
field.setAccessible(true);
menuView = field.get(this);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
return (BottomNavigationMenuView) menuView;
}
}
```
**3. Add to the layout.xml this customView**
For more details I have implemented this on [Github](https://github.com/DavidSanf0rd/BottomNavigationViewSample) | I'd recommend to implement it by yourself as [sanf0rd gave in his answer](https://stackoverflow.com/a/40188794/1104612). But `AppCompatImageView` is not working for me. I've changed it to `ImageView`. And changed `getChildAt` to `findViewById`.
Also I hide all labels of unselected items.
```
private void centerMenuIcon() {
BottomNavigationMenuView menuView = getBottomMenuView();
if (menuView != null) {
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView menuItemView = (BottomNavigationItemView) menuView.getChildAt(i);
TextView smallText = (TextView) menuItemView.findViewById(R.id.smallLabel);
smallText.setVisibility(View.INVISIBLE);
//TextView largeText = (TextView) menuItemView.findViewById(R.id.largeLabel);
ImageView icon = (ImageView) menuItemView.findViewById(R.id.icon);
FrameLayout.LayoutParams params = (LayoutParams) icon.getLayoutParams();
params.gravity = Gravity.CENTER;
menuItemView.setShiftingMode(true);
}
}
}
``` |
40,183,239 | Google released new support library v25 with BottomNavigationView
[![enter image description here](https://i.stack.imgur.com/R572H.gif)](https://i.stack.imgur.com/R572H.gif)
is there any way to remove items labels ? | 2016/10/21 | [
"https://Stackoverflow.com/questions/40183239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5033303/"
] | **1.** Set `android:title="";` in **menu/abc.xml**
**2.** Create the below helper class which is using reflection
```
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.widget.AppCompatImageView;
import android.util.Log;
import android.view.Gravity;
import android.widget.FrameLayout;
import java.lang.reflect.Field;
public class BottomNavigationViewHelper {
public static void disableShiftMode(BottomNavigationView view) {
BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
try {
Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
shiftingMode.setAccessible(true);
shiftingMode.setBoolean(menuView, false);
shiftingMode.setAccessible(false);
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
//noinspection RestrictedApi
item.setShiftingMode(false);
item.setPadding(0, 15, 0, 0);
// set once again checked value, so view will be updated
//noinspection RestrictedApi
item.setChecked(item.getItemData().isChecked());
}
} catch (NoSuchFieldException e) {
Log.e("BNVHelper", "Unable to get shift mode field", e);
} catch (IllegalAccessException e) {
Log.e("BNVHelper", "Unable to change value of shift mode", e);
}
}
}
```
**3.** In your main activity, add these lines:
```
mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
BottomNavigationViewHelper.disableShiftMode(mBottomNav);
``` | I wanted to remove both the [shift animation](https://stackoverflow.com/questions/40176244/how-to-disable-bottomnavigationview-shift-mode) and the labels and none of the solutions here worked well for me, so here's the one I built based on everything I learned here:
```
public void removeLabels(@IdRes int... menuItemIds) {
getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override public boolean onPreDraw() {
getViewTreeObserver().removeOnPreDrawListener(this);
// this only needs to be calculated once for an unchecked item, it'll be the same value for all items
ViewGroup uncheckedItem = findFirstUncheckedItem(menuItemIds);
View icon = uncheckedItem.getChildAt(0);
int iconTopMargin = ((LayoutParams) uncheckedItem.getChildAt(0).getLayoutParams()).topMargin;
int desiredTopMargin = (uncheckedItem.getHeight() - uncheckedItem.getChildAt(0).getHeight()) / 2;
int itemTopPadding = desiredTopMargin - iconTopMargin;
for (int id : menuItemIds) {
ViewGroup item = findViewById(id);
// remove the label
item.removeViewAt(1);
// and then center the icon
item.setPadding(item.getPaddingLeft(), itemTopPadding, item.getPaddingRight(),
item.getPaddingBottom());
}
return true;
}
});
}
@SuppressLint("RestrictedApi")
private ViewGroup findFirstUncheckedItem(@IdRes int... menuItemIds) {
BottomNavigationItemView item = findViewById(menuItemIds[0]);
int i = 1;
while (item.getItemData().isChecked()) {
item = findViewById(menuItemIds[i++]);
}
return item;
}
```
Just add this method to your custom `BottomNavigationView` and call it passing the ids of the menu items. |
40,183,239 | Google released new support library v25 with BottomNavigationView
[![enter image description here](https://i.stack.imgur.com/R572H.gif)](https://i.stack.imgur.com/R572H.gif)
is there any way to remove items labels ? | 2016/10/21 | [
"https://Stackoverflow.com/questions/40183239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5033303/"
] | Would you want to this style ?
![](https://github.com/ittianyu/BottomNavigationViewEx/raw/master/read_me_images/no_animation_shifting_mode_item_shifting_mode_text.gif)
![](https://github.com/ittianyu/BottomNavigationViewEx/raw/master/read_me_images/no_text.gif)
If so, I recommend you try [BottomNavigationViewEx](https://github.com/ittianyu/BottomNavigationViewEx). | I wanted to remove both the [shift animation](https://stackoverflow.com/questions/40176244/how-to-disable-bottomnavigationview-shift-mode) and the labels and none of the solutions here worked well for me, so here's the one I built based on everything I learned here:
```
public void removeLabels(@IdRes int... menuItemIds) {
getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override public boolean onPreDraw() {
getViewTreeObserver().removeOnPreDrawListener(this);
// this only needs to be calculated once for an unchecked item, it'll be the same value for all items
ViewGroup uncheckedItem = findFirstUncheckedItem(menuItemIds);
View icon = uncheckedItem.getChildAt(0);
int iconTopMargin = ((LayoutParams) uncheckedItem.getChildAt(0).getLayoutParams()).topMargin;
int desiredTopMargin = (uncheckedItem.getHeight() - uncheckedItem.getChildAt(0).getHeight()) / 2;
int itemTopPadding = desiredTopMargin - iconTopMargin;
for (int id : menuItemIds) {
ViewGroup item = findViewById(id);
// remove the label
item.removeViewAt(1);
// and then center the icon
item.setPadding(item.getPaddingLeft(), itemTopPadding, item.getPaddingRight(),
item.getPaddingBottom());
}
return true;
}
});
}
@SuppressLint("RestrictedApi")
private ViewGroup findFirstUncheckedItem(@IdRes int... menuItemIds) {
BottomNavigationItemView item = findViewById(menuItemIds[0]);
int i = 1;
while (item.getItemData().isChecked()) {
item = findViewById(menuItemIds[i++]);
}
return item;
}
```
Just add this method to your custom `BottomNavigationView` and call it passing the ids of the menu items. |
40,183,239 | Google released new support library v25 with BottomNavigationView
[![enter image description here](https://i.stack.imgur.com/R572H.gif)](https://i.stack.imgur.com/R572H.gif)
is there any way to remove items labels ? | 2016/10/21 | [
"https://Stackoverflow.com/questions/40183239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5033303/"
] | This is a temporary fix. Just add: `app:itemTextColor="@android:color/transparent"` That'll make it whatever the background color is, appearing disabled. It does make the icon look elevated. | I'd recommend to implement it by yourself as [sanf0rd gave in his answer](https://stackoverflow.com/a/40188794/1104612). But `AppCompatImageView` is not working for me. I've changed it to `ImageView`. And changed `getChildAt` to `findViewById`.
Also I hide all labels of unselected items.
```
private void centerMenuIcon() {
BottomNavigationMenuView menuView = getBottomMenuView();
if (menuView != null) {
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView menuItemView = (BottomNavigationItemView) menuView.getChildAt(i);
TextView smallText = (TextView) menuItemView.findViewById(R.id.smallLabel);
smallText.setVisibility(View.INVISIBLE);
//TextView largeText = (TextView) menuItemView.findViewById(R.id.largeLabel);
ImageView icon = (ImageView) menuItemView.findViewById(R.id.icon);
FrameLayout.LayoutParams params = (LayoutParams) icon.getLayoutParams();
params.gravity = Gravity.CENTER;
menuItemView.setShiftingMode(true);
}
}
}
``` |
40,183,239 | Google released new support library v25 with BottomNavigationView
[![enter image description here](https://i.stack.imgur.com/R572H.gif)](https://i.stack.imgur.com/R572H.gif)
is there any way to remove items labels ? | 2016/10/21 | [
"https://Stackoverflow.com/questions/40183239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5033303/"
] | This is a temporary fix. Just add: `app:itemTextColor="@android:color/transparent"` That'll make it whatever the background color is, appearing disabled. It does make the icon look elevated. | I wanted to remove both the [shift animation](https://stackoverflow.com/questions/40176244/how-to-disable-bottomnavigationview-shift-mode) and the labels and none of the solutions here worked well for me, so here's the one I built based on everything I learned here:
```
public void removeLabels(@IdRes int... menuItemIds) {
getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override public boolean onPreDraw() {
getViewTreeObserver().removeOnPreDrawListener(this);
// this only needs to be calculated once for an unchecked item, it'll be the same value for all items
ViewGroup uncheckedItem = findFirstUncheckedItem(menuItemIds);
View icon = uncheckedItem.getChildAt(0);
int iconTopMargin = ((LayoutParams) uncheckedItem.getChildAt(0).getLayoutParams()).topMargin;
int desiredTopMargin = (uncheckedItem.getHeight() - uncheckedItem.getChildAt(0).getHeight()) / 2;
int itemTopPadding = desiredTopMargin - iconTopMargin;
for (int id : menuItemIds) {
ViewGroup item = findViewById(id);
// remove the label
item.removeViewAt(1);
// and then center the icon
item.setPadding(item.getPaddingLeft(), itemTopPadding, item.getPaddingRight(),
item.getPaddingBottom());
}
return true;
}
});
}
@SuppressLint("RestrictedApi")
private ViewGroup findFirstUncheckedItem(@IdRes int... menuItemIds) {
BottomNavigationItemView item = findViewById(menuItemIds[0]);
int i = 1;
while (item.getItemData().isChecked()) {
item = findViewById(menuItemIds[i++]);
}
return item;
}
```
Just add this method to your custom `BottomNavigationView` and call it passing the ids of the menu items. |
40,183,239 | Google released new support library v25 with BottomNavigationView
[![enter image description here](https://i.stack.imgur.com/R572H.gif)](https://i.stack.imgur.com/R572H.gif)
is there any way to remove items labels ? | 2016/10/21 | [
"https://Stackoverflow.com/questions/40183239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5033303/"
] | Unfortunately this first version of BottomNavigationView came with a lot of limitations. And for now you can't remove the titles just using the support design API. So to solve this limitation while google doesn't implement it, you can do (using reflection):
**1. Set the titles empty in from bottom\_navigation\_menu.xml file.**
**2. Extends the BottomNavigationView:**
```
public class MyBottomNavigationView extends BottomNavigationView {
public MyBottomNavigationView(Context context, AttributeSet attrs) {
super(context, attrs);
centerMenuIcon();
}
private void centerMenuIcon() {
BottomNavigationMenuView menuView = getBottomMenuView();
if (menuView != null) {
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView menuItemView = (BottomNavigationItemView) menuView.getChildAt(i);
AppCompatImageView icon = (AppCompatImageView) menuItemView.getChildAt(0);
FrameLayout.LayoutParams params = (LayoutParams) icon.getLayoutParams();
params.gravity = Gravity.CENTER;
menuItemView.setShiftingMode(true);
}
}
}
private BottomNavigationMenuView getBottomMenuView() {
Object menuView = null;
try {
Field field = BottomNavigationView.class.getDeclaredField("mMenuView");
field.setAccessible(true);
menuView = field.get(this);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
return (BottomNavigationMenuView) menuView;
}
}
```
**3. Add to the layout.xml this customView**
For more details I have implemented this on [Github](https://github.com/DavidSanf0rd/BottomNavigationViewSample) | I wanted to remove both the [shift animation](https://stackoverflow.com/questions/40176244/how-to-disable-bottomnavigationview-shift-mode) and the labels and none of the solutions here worked well for me, so here's the one I built based on everything I learned here:
```
public void removeLabels(@IdRes int... menuItemIds) {
getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override public boolean onPreDraw() {
getViewTreeObserver().removeOnPreDrawListener(this);
// this only needs to be calculated once for an unchecked item, it'll be the same value for all items
ViewGroup uncheckedItem = findFirstUncheckedItem(menuItemIds);
View icon = uncheckedItem.getChildAt(0);
int iconTopMargin = ((LayoutParams) uncheckedItem.getChildAt(0).getLayoutParams()).topMargin;
int desiredTopMargin = (uncheckedItem.getHeight() - uncheckedItem.getChildAt(0).getHeight()) / 2;
int itemTopPadding = desiredTopMargin - iconTopMargin;
for (int id : menuItemIds) {
ViewGroup item = findViewById(id);
// remove the label
item.removeViewAt(1);
// and then center the icon
item.setPadding(item.getPaddingLeft(), itemTopPadding, item.getPaddingRight(),
item.getPaddingBottom());
}
return true;
}
});
}
@SuppressLint("RestrictedApi")
private ViewGroup findFirstUncheckedItem(@IdRes int... menuItemIds) {
BottomNavigationItemView item = findViewById(menuItemIds[0]);
int i = 1;
while (item.getItemData().isChecked()) {
item = findViewById(menuItemIds[i++]);
}
return item;
}
```
Just add this method to your custom `BottomNavigationView` and call it passing the ids of the menu items. |
40,183,239 | Google released new support library v25 with BottomNavigationView
[![enter image description here](https://i.stack.imgur.com/R572H.gif)](https://i.stack.imgur.com/R572H.gif)
is there any way to remove items labels ? | 2016/10/21 | [
"https://Stackoverflow.com/questions/40183239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5033303/"
] | I hope I am not too late to the party here.
But as of Design Support Library 28.0.0-alpha1
you can use the property
```
app:labelVisibilityMode="unlabeled"
```
[![BottomNavigationView without labels](https://i.stack.imgur.com/QL6fW.png)](https://i.stack.imgur.com/QL6fW.png)
you can use other values "auto", "labeled" and "selected" as well. | I wanted to remove both the [shift animation](https://stackoverflow.com/questions/40176244/how-to-disable-bottomnavigationview-shift-mode) and the labels and none of the solutions here worked well for me, so here's the one I built based on everything I learned here:
```
public void removeLabels(@IdRes int... menuItemIds) {
getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override public boolean onPreDraw() {
getViewTreeObserver().removeOnPreDrawListener(this);
// this only needs to be calculated once for an unchecked item, it'll be the same value for all items
ViewGroup uncheckedItem = findFirstUncheckedItem(menuItemIds);
View icon = uncheckedItem.getChildAt(0);
int iconTopMargin = ((LayoutParams) uncheckedItem.getChildAt(0).getLayoutParams()).topMargin;
int desiredTopMargin = (uncheckedItem.getHeight() - uncheckedItem.getChildAt(0).getHeight()) / 2;
int itemTopPadding = desiredTopMargin - iconTopMargin;
for (int id : menuItemIds) {
ViewGroup item = findViewById(id);
// remove the label
item.removeViewAt(1);
// and then center the icon
item.setPadding(item.getPaddingLeft(), itemTopPadding, item.getPaddingRight(),
item.getPaddingBottom());
}
return true;
}
});
}
@SuppressLint("RestrictedApi")
private ViewGroup findFirstUncheckedItem(@IdRes int... menuItemIds) {
BottomNavigationItemView item = findViewById(menuItemIds[0]);
int i = 1;
while (item.getItemData().isChecked()) {
item = findViewById(menuItemIds[i++]);
}
return item;
}
```
Just add this method to your custom `BottomNavigationView` and call it passing the ids of the menu items. |
40,183,239 | Google released new support library v25 with BottomNavigationView
[![enter image description here](https://i.stack.imgur.com/R572H.gif)](https://i.stack.imgur.com/R572H.gif)
is there any way to remove items labels ? | 2016/10/21 | [
"https://Stackoverflow.com/questions/40183239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5033303/"
] | I hope I am not too late to the party here.
But as of Design Support Library 28.0.0-alpha1
you can use the property
```
app:labelVisibilityMode="unlabeled"
```
[![BottomNavigationView without labels](https://i.stack.imgur.com/QL6fW.png)](https://i.stack.imgur.com/QL6fW.png)
you can use other values "auto", "labeled" and "selected" as well. | This is a temporary fix. Just add: `app:itemTextColor="@android:color/transparent"` That'll make it whatever the background color is, appearing disabled. It does make the icon look elevated. |
40,183,239 | Google released new support library v25 with BottomNavigationView
[![enter image description here](https://i.stack.imgur.com/R572H.gif)](https://i.stack.imgur.com/R572H.gif)
is there any way to remove items labels ? | 2016/10/21 | [
"https://Stackoverflow.com/questions/40183239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5033303/"
] | Unfortunately this first version of BottomNavigationView came with a lot of limitations. And for now you can't remove the titles just using the support design API. So to solve this limitation while google doesn't implement it, you can do (using reflection):
**1. Set the titles empty in from bottom\_navigation\_menu.xml file.**
**2. Extends the BottomNavigationView:**
```
public class MyBottomNavigationView extends BottomNavigationView {
public MyBottomNavigationView(Context context, AttributeSet attrs) {
super(context, attrs);
centerMenuIcon();
}
private void centerMenuIcon() {
BottomNavigationMenuView menuView = getBottomMenuView();
if (menuView != null) {
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView menuItemView = (BottomNavigationItemView) menuView.getChildAt(i);
AppCompatImageView icon = (AppCompatImageView) menuItemView.getChildAt(0);
FrameLayout.LayoutParams params = (LayoutParams) icon.getLayoutParams();
params.gravity = Gravity.CENTER;
menuItemView.setShiftingMode(true);
}
}
}
private BottomNavigationMenuView getBottomMenuView() {
Object menuView = null;
try {
Field field = BottomNavigationView.class.getDeclaredField("mMenuView");
field.setAccessible(true);
menuView = field.get(this);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
return (BottomNavigationMenuView) menuView;
}
}
```
**3. Add to the layout.xml this customView**
For more details I have implemented this on [Github](https://github.com/DavidSanf0rd/BottomNavigationViewSample) | This is a temporary fix. Just add: `app:itemTextColor="@android:color/transparent"` That'll make it whatever the background color is, appearing disabled. It does make the icon look elevated. |
45,563,661 | I am a new Xamarin developer and i am now working on simple application that needs a database to store the application data.
**My needs:**
Simple application, MVVM design pattern, One development.
The application need to work in IOS and Android
**My Solution structure:**
1. Xamarin.Forms PCL project (Contains Views, ViewModels, Models, Services)
2. Xamarin.Droid - A default Xamarin Android project.
3. Xamarin.IOS - A default Xamarin IOS project.
I want to use **NoSQL database**.
I know about MongoDB, that is a nice one.
BUT after searching in Google, there are no any tutorial to use MongoDB with Xamarin.Forms PCL project.
**So, my Questions:**
1. It is possible to use MongoDB with Xamarin.forms?
2. (If the answer for (1) is "Yes") - MongoDB are really recommended to use with Xamarin.Forms PCL project?
3. (If the answer for (2) is "No") - What the best NoSQL database option in my case?
Attention:
I am already tried to use this article:
<http://www.c-sharpcorner.com/UploadFile/093731/xamarin-with-mongodb/>
But not working.
I am using: **Visual Studio 2017**, Xamarin.Forms (2.3.4.247).
Thank a lot! | 2017/08/08 | [
"https://Stackoverflow.com/questions/45563661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5635569/"
] | Xamarin Forms PCL has nothing to do with MongoDB.You need a service to access the MongoDB or any other db .Ideally you could use a RESTful service to access a database
The article you have referred explains how to access MongoDB through a Web API(It is a RESTful web service). Only thing you have to worry about Xamarin is , how to call a web api in pcl. Again based on your article they use HttpWebRequest to access the web api(You can use different clients such as httpclient,restsharp etc to do this).
By the way you need to add Mongodb driver using nuget(<https://www.nuget.org/packages/MongoDB.Driver/>) to your web api project.
Seems you didn't properly install the driver to web api project.Also i wonder MongoCollection is a custom model class which they created for keeping the db instances. | If your looking for a NoSQL **Offline** Database that works with Xamarin PCL that you can access through Models and Query using LINQ.
[Realm](https://realm.io/docs/xamarin/latest) might be what your looking for:
```
public class Dog : RealmObject {
public string name {get;set;}
public Human Owner {get;set}
}
public class Human : RealmObject {
public IList<Dog> dogs {get;}
public string FirstName {get;set;}
}
Realm realm = Realm.GetInstance();
Human man = new Human();
man.Firstname = "Matan";
Dog dog = new Dog();
dog.name = "Jimmy";
man.dogs.Add(dog);
using (var trans = realm.BeginWrite()){
realm.Add(man):
trans.Commit();
}
var people = realm.All<Human>();
foreach(var person : people){
Debug.WriteLine(person.FirstName);
Debug.WriteLine(person.dogs[0].name);
}
// [Output]
// Matan
//
```
To use MongoDB directly you'll need to create an API that you post data to with REST |
45,563,661 | I am a new Xamarin developer and i am now working on simple application that needs a database to store the application data.
**My needs:**
Simple application, MVVM design pattern, One development.
The application need to work in IOS and Android
**My Solution structure:**
1. Xamarin.Forms PCL project (Contains Views, ViewModels, Models, Services)
2. Xamarin.Droid - A default Xamarin Android project.
3. Xamarin.IOS - A default Xamarin IOS project.
I want to use **NoSQL database**.
I know about MongoDB, that is a nice one.
BUT after searching in Google, there are no any tutorial to use MongoDB with Xamarin.Forms PCL project.
**So, my Questions:**
1. It is possible to use MongoDB with Xamarin.forms?
2. (If the answer for (1) is "Yes") - MongoDB are really recommended to use with Xamarin.Forms PCL project?
3. (If the answer for (2) is "No") - What the best NoSQL database option in my case?
Attention:
I am already tried to use this article:
<http://www.c-sharpcorner.com/UploadFile/093731/xamarin-with-mongodb/>
But not working.
I am using: **Visual Studio 2017**, Xamarin.Forms (2.3.4.247).
Thank a lot! | 2017/08/08 | [
"https://Stackoverflow.com/questions/45563661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5635569/"
] | Xamarin Forms PCL has nothing to do with MongoDB.You need a service to access the MongoDB or any other db .Ideally you could use a RESTful service to access a database
The article you have referred explains how to access MongoDB through a Web API(It is a RESTful web service). Only thing you have to worry about Xamarin is , how to call a web api in pcl. Again based on your article they use HttpWebRequest to access the web api(You can use different clients such as httpclient,restsharp etc to do this).
By the way you need to add Mongodb driver using nuget(<https://www.nuget.org/packages/MongoDB.Driver/>) to your web api project.
Seems you didn't properly install the driver to web api project.Also i wonder MongoCollection is a custom model class which they created for keeping the db instances. | You need to create REST server and use restful service using Nodejs or Asp.Net core application.
>
> 1. Asp.net : <https://www.c-sharpcorner.com/UploadFile/093731/xamarin-with-mongodb/>
> 2. Nodejs : <https://www.npmjs.com/package/mongodb>
>
>
> |
45,563,661 | I am a new Xamarin developer and i am now working on simple application that needs a database to store the application data.
**My needs:**
Simple application, MVVM design pattern, One development.
The application need to work in IOS and Android
**My Solution structure:**
1. Xamarin.Forms PCL project (Contains Views, ViewModels, Models, Services)
2. Xamarin.Droid - A default Xamarin Android project.
3. Xamarin.IOS - A default Xamarin IOS project.
I want to use **NoSQL database**.
I know about MongoDB, that is a nice one.
BUT after searching in Google, there are no any tutorial to use MongoDB with Xamarin.Forms PCL project.
**So, my Questions:**
1. It is possible to use MongoDB with Xamarin.forms?
2. (If the answer for (1) is "Yes") - MongoDB are really recommended to use with Xamarin.Forms PCL project?
3. (If the answer for (2) is "No") - What the best NoSQL database option in my case?
Attention:
I am already tried to use this article:
<http://www.c-sharpcorner.com/UploadFile/093731/xamarin-with-mongodb/>
But not working.
I am using: **Visual Studio 2017**, Xamarin.Forms (2.3.4.247).
Thank a lot! | 2017/08/08 | [
"https://Stackoverflow.com/questions/45563661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5635569/"
] | If your looking for a NoSQL **Offline** Database that works with Xamarin PCL that you can access through Models and Query using LINQ.
[Realm](https://realm.io/docs/xamarin/latest) might be what your looking for:
```
public class Dog : RealmObject {
public string name {get;set;}
public Human Owner {get;set}
}
public class Human : RealmObject {
public IList<Dog> dogs {get;}
public string FirstName {get;set;}
}
Realm realm = Realm.GetInstance();
Human man = new Human();
man.Firstname = "Matan";
Dog dog = new Dog();
dog.name = "Jimmy";
man.dogs.Add(dog);
using (var trans = realm.BeginWrite()){
realm.Add(man):
trans.Commit();
}
var people = realm.All<Human>();
foreach(var person : people){
Debug.WriteLine(person.FirstName);
Debug.WriteLine(person.dogs[0].name);
}
// [Output]
// Matan
//
```
To use MongoDB directly you'll need to create an API that you post data to with REST | You need to create REST server and use restful service using Nodejs or Asp.Net core application.
>
> 1. Asp.net : <https://www.c-sharpcorner.com/UploadFile/093731/xamarin-with-mongodb/>
> 2. Nodejs : <https://www.npmjs.com/package/mongodb>
>
>
> |
7,623,215 | I haven't been doing Java long. In this script where it says Thread.sleep(10000); you can still type (I use eclipse) I really don't know why it enables you to type in the output when I have no uno.nextLine(); before or after the 10 second waiting. Please help! Thanks
```
import java.util.Scanner;
class Tutoiral{
public static void main (String args[])throws InterruptedException {
Scanner uno = new Scanner(System.in);
Scanner uno1 = new Scanner(System.in);
System.out.println("What's your name?");
String name = uno.nextLine();
System.out.println("Hi, " + name + ". Feel free to type whatever you want :) BUT DON'T SPAM!!!!!");
String typed = (": ") + uno1.nextLine();
System.out.println(name + typed + " (5 types remaining)");
uno.nextLine();
System.out.println(name + typed + " (4 types remaining)");
uno.nextLine();
System.out.println(name + typed + " (3 types remaining)");
uno.nextLine();
System.out.println(name + typed + " (2 types remaining)");
uno.nextLine();
System.out.println(name + typed + " (1 type remaining)");
uno.nextLine();
System.out.println(name + typed + " (If you type one more time, then I'll... I'll block you! Ha!)");
uno.nextLine();
System.out.println(name + typed + " (tut tut tut. You have been blocked for a while for spam. Don't type EVER again ok?)");
Thread.sleep(10000);
System.out.println("Ok, you can type again. But I wouldn't If I were you.");
``` | 2011/10/01 | [
"https://Stackoverflow.com/questions/7623215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/974906/"
] | >
> ***I really don't know why it enables you to type in the output when I have no uno.nextLine();***
>
>
>
The call to `nextLine` will read (and return) characters from standard input. The console will print the characters entered by the user, **regardless if you read them or not**.
Unfortunately (for you) it's not possible to *prevent* the user from entering data on standard input.
---
One workaround would perhaps be to disable "local echo", i.e. avoid printing the characters entered by the user. I'm not sure how to do this. A nasty approach would be to do `System.console().readPassword()`.
Playing around with it, I came up with the following super-nasty hack workaround (Beware that `Thread.stop()` for instance, is deprecated for good reasons.):
```
public static void turnOffLocalEcho(long ms) {
Thread t = new Thread() {
public void run() {
while (true) { System.console().readPassword(); }
}
};
t.start();
try {
Thread.sleep(ms);
} catch (InterruptedException ie) {
}
t.stop();
}
```
Just replace your call to `Thread.sleep(10000)` with a call to this method:
```
turnOffLocalEcho(10000);
``` | uno will process the input typed whenever (while sleeping, working, or waiting for input) when one of its `nextSomething()` methods is called. you need not call `nextSomething()` and parse the input, but the user can enter it either way. |
7,623,215 | I haven't been doing Java long. In this script where it says Thread.sleep(10000); you can still type (I use eclipse) I really don't know why it enables you to type in the output when I have no uno.nextLine(); before or after the 10 second waiting. Please help! Thanks
```
import java.util.Scanner;
class Tutoiral{
public static void main (String args[])throws InterruptedException {
Scanner uno = new Scanner(System.in);
Scanner uno1 = new Scanner(System.in);
System.out.println("What's your name?");
String name = uno.nextLine();
System.out.println("Hi, " + name + ". Feel free to type whatever you want :) BUT DON'T SPAM!!!!!");
String typed = (": ") + uno1.nextLine();
System.out.println(name + typed + " (5 types remaining)");
uno.nextLine();
System.out.println(name + typed + " (4 types remaining)");
uno.nextLine();
System.out.println(name + typed + " (3 types remaining)");
uno.nextLine();
System.out.println(name + typed + " (2 types remaining)");
uno.nextLine();
System.out.println(name + typed + " (1 type remaining)");
uno.nextLine();
System.out.println(name + typed + " (If you type one more time, then I'll... I'll block you! Ha!)");
uno.nextLine();
System.out.println(name + typed + " (tut tut tut. You have been blocked for a while for spam. Don't type EVER again ok?)");
Thread.sleep(10000);
System.out.println("Ok, you can type again. But I wouldn't If I were you.");
``` | 2011/10/01 | [
"https://Stackoverflow.com/questions/7623215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/974906/"
] | >
> ***I really don't know why it enables you to type in the output when I have no uno.nextLine();***
>
>
>
The call to `nextLine` will read (and return) characters from standard input. The console will print the characters entered by the user, **regardless if you read them or not**.
Unfortunately (for you) it's not possible to *prevent* the user from entering data on standard input.
---
One workaround would perhaps be to disable "local echo", i.e. avoid printing the characters entered by the user. I'm not sure how to do this. A nasty approach would be to do `System.console().readPassword()`.
Playing around with it, I came up with the following super-nasty hack workaround (Beware that `Thread.stop()` for instance, is deprecated for good reasons.):
```
public static void turnOffLocalEcho(long ms) {
Thread t = new Thread() {
public void run() {
while (true) { System.console().readPassword(); }
}
};
t.start();
try {
Thread.sleep(ms);
} catch (InterruptedException ie) {
}
t.stop();
}
```
Just replace your call to `Thread.sleep(10000)` with a call to this method:
```
turnOffLocalEcho(10000);
``` | Console input (and hence `Scanner`) does not work the way one might think.
A console program has an input stream called [*standard input*, or *stdin*](https://en.wikipedia.org/wiki/Stdin). You can think of this as a queue of characters for the program to read.
When you type a character into a console program, it normally has 2 effects:
1. The terminal immediately prints the character to the screen.
2. The character is appended to the program's standard input. (Technically this only happens each time you type a newline (`Enter`).)
These actions are performed by the OS, so they work regardless of whether your program is currently reading data from stdin. If the program is waiting for data, it will immediately process it (ignoring input stream buffering). But if not (e.g. it is processing something else, or in your case sleeping for 10 seconds), the character just sits in the queue until the program reads it.
`Scanner` does not actually prompt the user for a line of text. How it works: *When a program tries to read from stdin, if there is no data available the program blocks until the OS feeds it enough data*. `Scanner.nextLine()` reads characters from stdin until a newline has been read, at which point it returns the characters entered since the last newline. This means that typically, `Scanner.nextLine()` will cause the program to wait until the user presses Enter.
However, note that if you input more than one line of text at once, e.g. by pasting several lines into the terminal, or by shell pipes or redirection (such as with `java MyProgram < file.txt`), the program will keep running until it has eaten all of the input.
While your program is sleeping, the user can still type and append to your program's stdin! (Try adding a few copies of `System.out.println(name + typed + uno.nextLine());` at the end of your program, and see what happens when you type while your program is sleeping.)
Therefore, to prevent the user from typing stuff that your main program will read, you need to do 2 things while your main thread sleeps:
1. Tell the console to stop echoing characters typed to the console.
2. Read any characters fed to stdin, and discard them.
You can do both of these by calling `System.console().readPassword()` in another thread (and discarding its output). That way, after 10 seconds your main thread will wake up and kill the password-reading thread. But by then, anything the user typed while the main thread was sleeping will already have been read (removed from stdin) and discarded by the other thread, so in effect the user has been unable to type on the console. (See aioobe's answer for code of this.) |
34,999,124 | I'm using Google Calendar API v3 to work a one-way sync from another calendar system to a Google calendar, and wondering - how should I be treating deleted Google calendar events that are not deleted in the other calendar system?
The 'cancelled'/deleted Google calendar event I attempted to update contains the ICalUID value from an event in the other calendar system (where the event is not deleted). When I try to update/revive the 'cancelled' event I get a "403: Forbidden" response, and when I try to insert a new event using that ICalUID I receive a "duplicate" event error response.
Is there any way to revive the 'cancelled' event or clear its ICalUID? Or maybe a known gotchya hidden somewhere within this scenario that I missed?
I can re-create them using a different ICalUID, but I'm hoping someone else can offer some insight from their experience before I abandon the ICalUID. Thanks! | 2016/01/25 | [
"https://Stackoverflow.com/questions/34999124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5834871/"
] | Try this:
```
$('#first, #third').click(function () {
var firstChecked = $('#first).prop("checked") == true);
var thirdChecked = $('#third).prop("checked") == true);
if (firstChecked && thirdChecked ) {
alert("I'm checked!");
}
})
``` | In order to target a specific elements, try using a `css` class as a selector. Also, include the input `type` so that you don't have any conflict with other elements having the same class.
In order to check if all the required checkboxes are checked or not, you can use `.each()` loop and determine if they are all checked and based on that display the `alert()`. The following approach avoids any hardcoding and `multiple if` checks.
```
$("input:checkbox.test").click(function()
{
var allchecked = true;
$("input:checkbox.test").each(function(){
if(!$(this).is(":checked"))
allchecked = false;
});
if(allchecked)
alert("Im checked");
});
```
Working example : <https://jsfiddle.net/DinoMyte/fy1asfws/34/> |
34,999,124 | I'm using Google Calendar API v3 to work a one-way sync from another calendar system to a Google calendar, and wondering - how should I be treating deleted Google calendar events that are not deleted in the other calendar system?
The 'cancelled'/deleted Google calendar event I attempted to update contains the ICalUID value from an event in the other calendar system (where the event is not deleted). When I try to update/revive the 'cancelled' event I get a "403: Forbidden" response, and when I try to insert a new event using that ICalUID I receive a "duplicate" event error response.
Is there any way to revive the 'cancelled' event or clear its ICalUID? Or maybe a known gotchya hidden somewhere within this scenario that I missed?
I can re-create them using a different ICalUID, but I'm hoping someone else can offer some insight from their experience before I abandon the ICalUID. Thanks! | 2016/01/25 | [
"https://Stackoverflow.com/questions/34999124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5834871/"
] | <https://jsfiddle.net/p1zjaw46/>
```
var $toCheck = $('#first').add('#third');
$(function () {
$('input[type="checkbox"]').on('change', function () {
if ( $toCheck.filter(':checked').length === $toCheck.length )
alert('good');
else
alert('bad');
})
});
```
Basically:
1. cache the items you want to check into a var. `$toCheck` in this case.
2. When any are **[changed](https://api.jquery.com/change/)**, do a quick check. You [filter](http://api.jquery.com/filter/) by [`":checked"`](http://api.jquery.com/checked-selector/), and compare the length of the results of the `filter` to the length of the original set of checkboxes.
If they aren't equal, at least one of the expected boxes aren't checked!
Why is this answer better than others?
======================================
It's scalable
-------------
All you need to do is add new elements to `$toCheck` and the rest is automatic | In order to target a specific elements, try using a `css` class as a selector. Also, include the input `type` so that you don't have any conflict with other elements having the same class.
In order to check if all the required checkboxes are checked or not, you can use `.each()` loop and determine if they are all checked and based on that display the `alert()`. The following approach avoids any hardcoding and `multiple if` checks.
```
$("input:checkbox.test").click(function()
{
var allchecked = true;
$("input:checkbox.test").each(function(){
if(!$(this).is(":checked"))
allchecked = false;
});
if(allchecked)
alert("Im checked");
});
```
Working example : <https://jsfiddle.net/DinoMyte/fy1asfws/34/> |
34,999,124 | I'm using Google Calendar API v3 to work a one-way sync from another calendar system to a Google calendar, and wondering - how should I be treating deleted Google calendar events that are not deleted in the other calendar system?
The 'cancelled'/deleted Google calendar event I attempted to update contains the ICalUID value from an event in the other calendar system (where the event is not deleted). When I try to update/revive the 'cancelled' event I get a "403: Forbidden" response, and when I try to insert a new event using that ICalUID I receive a "duplicate" event error response.
Is there any way to revive the 'cancelled' event or clear its ICalUID? Or maybe a known gotchya hidden somewhere within this scenario that I missed?
I can re-create them using a different ICalUID, but I'm hoping someone else can offer some insight from their experience before I abandon the ICalUID. Thanks! | 2016/01/25 | [
"https://Stackoverflow.com/questions/34999124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5834871/"
] | You can check if the checkbox is checked using `is(':checked')`, you can check the if the both are checked using `&&` sign check example bellow.
Hope this helps.
---
```js
$("#first, #third").click(function () {
if ($('#first').is(':checked') && $('#third').is(':checked'))
{
alert("Message!");
}
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="checkbox" id="first" />
<input type="checkbox" id="second" />
<input type="checkbox" id="third" />
</form>
``` | Try this:
```
$('#first, #third').click(function () {
var firstChecked = $('#first).prop("checked") == true);
var thirdChecked = $('#third).prop("checked") == true);
if (firstChecked && thirdChecked ) {
alert("I'm checked!");
}
})
``` |
34,999,124 | I'm using Google Calendar API v3 to work a one-way sync from another calendar system to a Google calendar, and wondering - how should I be treating deleted Google calendar events that are not deleted in the other calendar system?
The 'cancelled'/deleted Google calendar event I attempted to update contains the ICalUID value from an event in the other calendar system (where the event is not deleted). When I try to update/revive the 'cancelled' event I get a "403: Forbidden" response, and when I try to insert a new event using that ICalUID I receive a "duplicate" event error response.
Is there any way to revive the 'cancelled' event or clear its ICalUID? Or maybe a known gotchya hidden somewhere within this scenario that I missed?
I can re-create them using a different ICalUID, but I'm hoping someone else can offer some insight from their experience before I abandon the ICalUID. Thanks! | 2016/01/25 | [
"https://Stackoverflow.com/questions/34999124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5834871/"
] | You can check if the checkbox is checked using `is(':checked')`, you can check the if the both are checked using `&&` sign check example bellow.
Hope this helps.
---
```js
$("#first, #third").click(function () {
if ($('#first').is(':checked') && $('#third').is(':checked'))
{
alert("Message!");
}
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="checkbox" id="first" />
<input type="checkbox" id="second" />
<input type="checkbox" id="third" />
</form>
``` | In order to target a specific elements, try using a `css` class as a selector. Also, include the input `type` so that you don't have any conflict with other elements having the same class.
In order to check if all the required checkboxes are checked or not, you can use `.each()` loop and determine if they are all checked and based on that display the `alert()`. The following approach avoids any hardcoding and `multiple if` checks.
```
$("input:checkbox.test").click(function()
{
var allchecked = true;
$("input:checkbox.test").each(function(){
if(!$(this).is(":checked"))
allchecked = false;
});
if(allchecked)
alert("Im checked");
});
```
Working example : <https://jsfiddle.net/DinoMyte/fy1asfws/34/> |
34,999,124 | I'm using Google Calendar API v3 to work a one-way sync from another calendar system to a Google calendar, and wondering - how should I be treating deleted Google calendar events that are not deleted in the other calendar system?
The 'cancelled'/deleted Google calendar event I attempted to update contains the ICalUID value from an event in the other calendar system (where the event is not deleted). When I try to update/revive the 'cancelled' event I get a "403: Forbidden" response, and when I try to insert a new event using that ICalUID I receive a "duplicate" event error response.
Is there any way to revive the 'cancelled' event or clear its ICalUID? Or maybe a known gotchya hidden somewhere within this scenario that I missed?
I can re-create them using a different ICalUID, but I'm hoping someone else can offer some insight from their experience before I abandon the ICalUID. Thanks! | 2016/01/25 | [
"https://Stackoverflow.com/questions/34999124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5834871/"
] | This answer works on the premise that you want to when *either* of the specified check-boxes are checked, rather than when they're *both* checked, this can be done with either comma separated selectors:
```
$('#first, #third')
```
Or through the use of a class-name to identify the relevant elements:
```
$('.alertIfSelectedClassName')
```
With the HTML of:
```
<form id="myForm">
<input type="checkbox" class="alertIfSelectedClassName" id="first" />
<input type="checkbox" id="second" />
<input type="checkbox" class="alertIfSelectedClassName" id="third" />
</form>
```
The use of CSS attribute selection,nbased on a shared attribute, such as the name of the `<input>`:
```
$('input[name=alertIfSelectedElementName')
```
HTML:
```
<form id="myForm">
<input type="checkbox" name="alertIfSelectedElementName" id="first" />
<input type="checkbox" id="second" />
<input type="checkbox" name="alertIfSelectedElementName" id="third" />
</form>
``` | <https://jsfiddle.net/p1zjaw46/>
```
var $toCheck = $('#first').add('#third');
$(function () {
$('input[type="checkbox"]').on('change', function () {
if ( $toCheck.filter(':checked').length === $toCheck.length )
alert('good');
else
alert('bad');
})
});
```
Basically:
1. cache the items you want to check into a var. `$toCheck` in this case.
2. When any are **[changed](https://api.jquery.com/change/)**, do a quick check. You [filter](http://api.jquery.com/filter/) by [`":checked"`](http://api.jquery.com/checked-selector/), and compare the length of the results of the `filter` to the length of the original set of checkboxes.
If they aren't equal, at least one of the expected boxes aren't checked!
Why is this answer better than others?
======================================
It's scalable
-------------
All you need to do is add new elements to `$toCheck` and the rest is automatic |
34,999,124 | I'm using Google Calendar API v3 to work a one-way sync from another calendar system to a Google calendar, and wondering - how should I be treating deleted Google calendar events that are not deleted in the other calendar system?
The 'cancelled'/deleted Google calendar event I attempted to update contains the ICalUID value from an event in the other calendar system (where the event is not deleted). When I try to update/revive the 'cancelled' event I get a "403: Forbidden" response, and when I try to insert a new event using that ICalUID I receive a "duplicate" event error response.
Is there any way to revive the 'cancelled' event or clear its ICalUID? Or maybe a known gotchya hidden somewhere within this scenario that I missed?
I can re-create them using a different ICalUID, but I'm hoping someone else can offer some insight from their experience before I abandon the ICalUID. Thanks! | 2016/01/25 | [
"https://Stackoverflow.com/questions/34999124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5834871/"
] | You can check if the checkbox is checked using `is(':checked')`, you can check the if the both are checked using `&&` sign check example bellow.
Hope this helps.
---
```js
$("#first, #third").click(function () {
if ($('#first').is(':checked') && $('#third').is(':checked'))
{
alert("Message!");
}
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="checkbox" id="first" />
<input type="checkbox" id="second" />
<input type="checkbox" id="third" />
</form>
``` | <https://jsfiddle.net/p1zjaw46/>
```
var $toCheck = $('#first').add('#third');
$(function () {
$('input[type="checkbox"]').on('change', function () {
if ( $toCheck.filter(':checked').length === $toCheck.length )
alert('good');
else
alert('bad');
})
});
```
Basically:
1. cache the items you want to check into a var. `$toCheck` in this case.
2. When any are **[changed](https://api.jquery.com/change/)**, do a quick check. You [filter](http://api.jquery.com/filter/) by [`":checked"`](http://api.jquery.com/checked-selector/), and compare the length of the results of the `filter` to the length of the original set of checkboxes.
If they aren't equal, at least one of the expected boxes aren't checked!
Why is this answer better than others?
======================================
It's scalable
-------------
All you need to do is add new elements to `$toCheck` and the rest is automatic |
34,999,124 | I'm using Google Calendar API v3 to work a one-way sync from another calendar system to a Google calendar, and wondering - how should I be treating deleted Google calendar events that are not deleted in the other calendar system?
The 'cancelled'/deleted Google calendar event I attempted to update contains the ICalUID value from an event in the other calendar system (where the event is not deleted). When I try to update/revive the 'cancelled' event I get a "403: Forbidden" response, and when I try to insert a new event using that ICalUID I receive a "duplicate" event error response.
Is there any way to revive the 'cancelled' event or clear its ICalUID? Or maybe a known gotchya hidden somewhere within this scenario that I missed?
I can re-create them using a different ICalUID, but I'm hoping someone else can offer some insight from their experience before I abandon the ICalUID. Thanks! | 2016/01/25 | [
"https://Stackoverflow.com/questions/34999124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5834871/"
] | This answer works on the premise that you want to when *either* of the specified check-boxes are checked, rather than when they're *both* checked, this can be done with either comma separated selectors:
```
$('#first, #third')
```
Or through the use of a class-name to identify the relevant elements:
```
$('.alertIfSelectedClassName')
```
With the HTML of:
```
<form id="myForm">
<input type="checkbox" class="alertIfSelectedClassName" id="first" />
<input type="checkbox" id="second" />
<input type="checkbox" class="alertIfSelectedClassName" id="third" />
</form>
```
The use of CSS attribute selection,nbased on a shared attribute, such as the name of the `<input>`:
```
$('input[name=alertIfSelectedElementName')
```
HTML:
```
<form id="myForm">
<input type="checkbox" name="alertIfSelectedElementName" id="first" />
<input type="checkbox" id="second" />
<input type="checkbox" name="alertIfSelectedElementName" id="third" />
</form>
``` | In order to target a specific elements, try using a `css` class as a selector. Also, include the input `type` so that you don't have any conflict with other elements having the same class.
In order to check if all the required checkboxes are checked or not, you can use `.each()` loop and determine if they are all checked and based on that display the `alert()`. The following approach avoids any hardcoding and `multiple if` checks.
```
$("input:checkbox.test").click(function()
{
var allchecked = true;
$("input:checkbox.test").each(function(){
if(!$(this).is(":checked"))
allchecked = false;
});
if(allchecked)
alert("Im checked");
});
```
Working example : <https://jsfiddle.net/DinoMyte/fy1asfws/34/> |
34,999,124 | I'm using Google Calendar API v3 to work a one-way sync from another calendar system to a Google calendar, and wondering - how should I be treating deleted Google calendar events that are not deleted in the other calendar system?
The 'cancelled'/deleted Google calendar event I attempted to update contains the ICalUID value from an event in the other calendar system (where the event is not deleted). When I try to update/revive the 'cancelled' event I get a "403: Forbidden" response, and when I try to insert a new event using that ICalUID I receive a "duplicate" event error response.
Is there any way to revive the 'cancelled' event or clear its ICalUID? Or maybe a known gotchya hidden somewhere within this scenario that I missed?
I can re-create them using a different ICalUID, but I'm hoping someone else can offer some insight from their experience before I abandon the ICalUID. Thanks! | 2016/01/25 | [
"https://Stackoverflow.com/questions/34999124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5834871/"
] | You can iterate through them:
```
<form id="myForm">
<input type="checkbox" name="somename" id="first" />
<input type="checkbox" name="somename" id="second" />
<input type="checkbox" name="somename" id="third" />
</form>
$('checkbox[name=somename"]').each(function () {
if ($(this).prop("checked") == true) {
alert("I'm checked!");
}
});
``` | In order to target a specific elements, try using a `css` class as a selector. Also, include the input `type` so that you don't have any conflict with other elements having the same class.
In order to check if all the required checkboxes are checked or not, you can use `.each()` loop and determine if they are all checked and based on that display the `alert()`. The following approach avoids any hardcoding and `multiple if` checks.
```
$("input:checkbox.test").click(function()
{
var allchecked = true;
$("input:checkbox.test").each(function(){
if(!$(this).is(":checked"))
allchecked = false;
});
if(allchecked)
alert("Im checked");
});
```
Working example : <https://jsfiddle.net/DinoMyte/fy1asfws/34/> |
34,999,124 | I'm using Google Calendar API v3 to work a one-way sync from another calendar system to a Google calendar, and wondering - how should I be treating deleted Google calendar events that are not deleted in the other calendar system?
The 'cancelled'/deleted Google calendar event I attempted to update contains the ICalUID value from an event in the other calendar system (where the event is not deleted). When I try to update/revive the 'cancelled' event I get a "403: Forbidden" response, and when I try to insert a new event using that ICalUID I receive a "duplicate" event error response.
Is there any way to revive the 'cancelled' event or clear its ICalUID? Or maybe a known gotchya hidden somewhere within this scenario that I missed?
I can re-create them using a different ICalUID, but I'm hoping someone else can offer some insight from their experience before I abandon the ICalUID. Thanks! | 2016/01/25 | [
"https://Stackoverflow.com/questions/34999124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5834871/"
] | You can check if the checkbox is checked using `is(':checked')`, you can check the if the both are checked using `&&` sign check example bellow.
Hope this helps.
---
```js
$("#first, #third").click(function () {
if ($('#first').is(':checked') && $('#third').is(':checked'))
{
alert("Message!");
}
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="checkbox" id="first" />
<input type="checkbox" id="second" />
<input type="checkbox" id="third" />
</form>
``` | You can iterate through them:
```
<form id="myForm">
<input type="checkbox" name="somename" id="first" />
<input type="checkbox" name="somename" id="second" />
<input type="checkbox" name="somename" id="third" />
</form>
$('checkbox[name=somename"]').each(function () {
if ($(this).prop("checked") == true) {
alert("I'm checked!");
}
});
``` |
34,999,124 | I'm using Google Calendar API v3 to work a one-way sync from another calendar system to a Google calendar, and wondering - how should I be treating deleted Google calendar events that are not deleted in the other calendar system?
The 'cancelled'/deleted Google calendar event I attempted to update contains the ICalUID value from an event in the other calendar system (where the event is not deleted). When I try to update/revive the 'cancelled' event I get a "403: Forbidden" response, and when I try to insert a new event using that ICalUID I receive a "duplicate" event error response.
Is there any way to revive the 'cancelled' event or clear its ICalUID? Or maybe a known gotchya hidden somewhere within this scenario that I missed?
I can re-create them using a different ICalUID, but I'm hoping someone else can offer some insight from their experience before I abandon the ICalUID. Thanks! | 2016/01/25 | [
"https://Stackoverflow.com/questions/34999124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5834871/"
] | This answer works on the premise that you want to when *either* of the specified check-boxes are checked, rather than when they're *both* checked, this can be done with either comma separated selectors:
```
$('#first, #third')
```
Or through the use of a class-name to identify the relevant elements:
```
$('.alertIfSelectedClassName')
```
With the HTML of:
```
<form id="myForm">
<input type="checkbox" class="alertIfSelectedClassName" id="first" />
<input type="checkbox" id="second" />
<input type="checkbox" class="alertIfSelectedClassName" id="third" />
</form>
```
The use of CSS attribute selection,nbased on a shared attribute, such as the name of the `<input>`:
```
$('input[name=alertIfSelectedElementName')
```
HTML:
```
<form id="myForm">
<input type="checkbox" name="alertIfSelectedElementName" id="first" />
<input type="checkbox" id="second" />
<input type="checkbox" name="alertIfSelectedElementName" id="third" />
</form>
``` | You can iterate through them:
```
<form id="myForm">
<input type="checkbox" name="somename" id="first" />
<input type="checkbox" name="somename" id="second" />
<input type="checkbox" name="somename" id="third" />
</form>
$('checkbox[name=somename"]').each(function () {
if ($(this).prop("checked") == true) {
alert("I'm checked!");
}
});
``` |
627,687 | I am working on a Sometimes Connected CRUD application that will be primarily used by teams(2-4) of Social Workers and Nurses to track patient information in the form of a plan. The application is a revisualization of a ASP.Net app that was created before my time. There are approx 200 tables across 4 databases. The Web App version relied heavily on SP's but since this version is a winform app that will be pointing to a local db I see no reason to continue with SP's. Also of note, I had planned to use Merge Replication to handle the Sync'ing portion and there seems to be some issues with those two together.
I am trying to understand what approach to use for the DAL. I originally had planned to use LINQ to SQL but I have read tidbits that state it doesn't work in a Sometimes Connected setting. I have therefore been trying to read and experiment with numerous solutions; SubSonic, NHibernate, Entity Framework. This is a relatively simple application and due to a "looming" verion 3 redesign this effort can be borderline "throwaway." The emphasis here is on getting a desktop version up and running ASAP.
What i am asking here is for anyone with any experience using any of these technology's(or one I didn't list) to lend me your hard earned wisdom. What is my best approach, in your opinion, for me to pursue. Any other insights on creating this kind of App? I am really struggling with the DAL portion of this program.
Thank you! | 2009/03/09 | [
"https://Stackoverflow.com/questions/627687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46724/"
] | If the stored procedures do what you want them to, I would have to say I'm dubious that you will get benefits by throwing them away and reimplementing them. Moreover, it shouldn't matter if you use stored procedures or LINQ to SQL style data access when it comes time to replicate your data back to the master database, so worrying about which DAL you use seems to be a red herring.
The tricky part about sometimes connected applications is coming up with a good conflict resolution system. My suggestions:
* Always use RowGuids as your primary keys to tables. Merge replication works best if you always have new records uniquely keyed.
* Realize that merge replication can only do so much: it is *great* for bringing new data in disparate systems together. It can even figure out one sided updates. It *can't* magically determine that your new record and my new record are *actually the same* nor can it really deal with changes on both sides without human intervention or priority rules.
* Because of this, you will need "matching" rules to resolve records that are claiming to be new, but actually aren't. Note that this is a fuzzy step: rarely can you rely on a unique key to actually be entered exactly the same on both sides and without error. This means giving weighted matches where *many* of your indicators are the same or similar.
* The user interface for resolving conflicts and matching up "new" records with the original needs to be easy to operate. I use something that looks similar to the classic three way merge that many source control systems use: Record A, Record B, Merged Record. They can default the Merged Record to A or B by clicking a header button, and can select each field by clicking against them as well. Finally, Merged Records fields are open for edit, because sometimes you need to take parts of the address (say) from A *and* B.
None of this should affect your data access layer in the slightest: this is all either lower level (merge replication, provided by the database itself) or higher level (conflict resolution, provided by your business rules for resolution) than your DAL. | If you can install a db system locally, go for something you feel familiar with. The greatest problem I think will be the syncing and merging part. You must think of several possibilities: Changed something that someone else deleted on the server. Who does decide?
Never used the Sync framework myself, just read an article. But this may give you a solid foundation to built on. But each way you go with data access, the solution to the businesslogic will probably have a much wider impact... |
627,687 | I am working on a Sometimes Connected CRUD application that will be primarily used by teams(2-4) of Social Workers and Nurses to track patient information in the form of a plan. The application is a revisualization of a ASP.Net app that was created before my time. There are approx 200 tables across 4 databases. The Web App version relied heavily on SP's but since this version is a winform app that will be pointing to a local db I see no reason to continue with SP's. Also of note, I had planned to use Merge Replication to handle the Sync'ing portion and there seems to be some issues with those two together.
I am trying to understand what approach to use for the DAL. I originally had planned to use LINQ to SQL but I have read tidbits that state it doesn't work in a Sometimes Connected setting. I have therefore been trying to read and experiment with numerous solutions; SubSonic, NHibernate, Entity Framework. This is a relatively simple application and due to a "looming" verion 3 redesign this effort can be borderline "throwaway." The emphasis here is on getting a desktop version up and running ASAP.
What i am asking here is for anyone with any experience using any of these technology's(or one I didn't list) to lend me your hard earned wisdom. What is my best approach, in your opinion, for me to pursue. Any other insights on creating this kind of App? I am really struggling with the DAL portion of this program.
Thank you! | 2009/03/09 | [
"https://Stackoverflow.com/questions/627687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46724/"
] | If the stored procedures do what you want them to, I would have to say I'm dubious that you will get benefits by throwing them away and reimplementing them. Moreover, it shouldn't matter if you use stored procedures or LINQ to SQL style data access when it comes time to replicate your data back to the master database, so worrying about which DAL you use seems to be a red herring.
The tricky part about sometimes connected applications is coming up with a good conflict resolution system. My suggestions:
* Always use RowGuids as your primary keys to tables. Merge replication works best if you always have new records uniquely keyed.
* Realize that merge replication can only do so much: it is *great* for bringing new data in disparate systems together. It can even figure out one sided updates. It *can't* magically determine that your new record and my new record are *actually the same* nor can it really deal with changes on both sides without human intervention or priority rules.
* Because of this, you will need "matching" rules to resolve records that are claiming to be new, but actually aren't. Note that this is a fuzzy step: rarely can you rely on a unique key to actually be entered exactly the same on both sides and without error. This means giving weighted matches where *many* of your indicators are the same or similar.
* The user interface for resolving conflicts and matching up "new" records with the original needs to be easy to operate. I use something that looks similar to the classic three way merge that many source control systems use: Record A, Record B, Merged Record. They can default the Merged Record to A or B by clicking a header button, and can select each field by clicking against them as well. Finally, Merged Records fields are open for edit, because sometimes you need to take parts of the address (say) from A *and* B.
None of this should affect your data access layer in the slightest: this is all either lower level (merge replication, provided by the database itself) or higher level (conflict resolution, provided by your business rules for resolution) than your DAL. | There is a sample app called issueVision Microsoft put out back in 2004.
<http://windowsclient.net/downloads/folders/starterkits/entry1268.aspx>
Found link on old thread in joelonsoftware.com. <http://discuss.joelonsoftware.com/default.asp?joel.3.25830.10>
Other ideas...
What about mobile broadband? A couple 3G cellular cards will work tomorrow and your app will need no changes sans large pages/graphics.
Excel spreadsheet used in the field. DTS or SSIS to import data into application. While a "better" solution is created.
Good luck! |
627,687 | I am working on a Sometimes Connected CRUD application that will be primarily used by teams(2-4) of Social Workers and Nurses to track patient information in the form of a plan. The application is a revisualization of a ASP.Net app that was created before my time. There are approx 200 tables across 4 databases. The Web App version relied heavily on SP's but since this version is a winform app that will be pointing to a local db I see no reason to continue with SP's. Also of note, I had planned to use Merge Replication to handle the Sync'ing portion and there seems to be some issues with those two together.
I am trying to understand what approach to use for the DAL. I originally had planned to use LINQ to SQL but I have read tidbits that state it doesn't work in a Sometimes Connected setting. I have therefore been trying to read and experiment with numerous solutions; SubSonic, NHibernate, Entity Framework. This is a relatively simple application and due to a "looming" verion 3 redesign this effort can be borderline "throwaway." The emphasis here is on getting a desktop version up and running ASAP.
What i am asking here is for anyone with any experience using any of these technology's(or one I didn't list) to lend me your hard earned wisdom. What is my best approach, in your opinion, for me to pursue. Any other insights on creating this kind of App? I am really struggling with the DAL portion of this program.
Thank you! | 2009/03/09 | [
"https://Stackoverflow.com/questions/627687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46724/"
] | If the stored procedures do what you want them to, I would have to say I'm dubious that you will get benefits by throwing them away and reimplementing them. Moreover, it shouldn't matter if you use stored procedures or LINQ to SQL style data access when it comes time to replicate your data back to the master database, so worrying about which DAL you use seems to be a red herring.
The tricky part about sometimes connected applications is coming up with a good conflict resolution system. My suggestions:
* Always use RowGuids as your primary keys to tables. Merge replication works best if you always have new records uniquely keyed.
* Realize that merge replication can only do so much: it is *great* for bringing new data in disparate systems together. It can even figure out one sided updates. It *can't* magically determine that your new record and my new record are *actually the same* nor can it really deal with changes on both sides without human intervention or priority rules.
* Because of this, you will need "matching" rules to resolve records that are claiming to be new, but actually aren't. Note that this is a fuzzy step: rarely can you rely on a unique key to actually be entered exactly the same on both sides and without error. This means giving weighted matches where *many* of your indicators are the same or similar.
* The user interface for resolving conflicts and matching up "new" records with the original needs to be easy to operate. I use something that looks similar to the classic three way merge that many source control systems use: Record A, Record B, Merged Record. They can default the Merged Record to A or B by clicking a header button, and can select each field by clicking against them as well. Finally, Merged Records fields are open for edit, because sometimes you need to take parts of the address (say) from A *and* B.
None of this should affect your data access layer in the slightest: this is all either lower level (merge replication, provided by the database itself) or higher level (conflict resolution, provided by your business rules for resolution) than your DAL. | If by SP's you mean stored procedures... I'm not sure I understand your reasoning from trying to move away from them. Considering that they're fast, proven, and already written for you (ie. tested).
Surely, if you're making an app that will mimic the original, there are definite merits to keeping as much of the original (working) codebase as possible - the least of which is speed.
I'd try installing a local copy of the db, and then pushing all affected records since the last connected period to the master db when it does get connected. |
12,265,969 | So, I've been trying to figure out the following problem for the past few weeks, and at this point I'm almost exhausting my options because how contradictory the situation seems.
I have an application which is developed to work under SharePoint but it's basically ASP.NET code. I have an encrypted connection string which I decrypt it in memory and store it in a configuration object to access the database. My configuration object is static (accesible through a `Service Locator` pattern), which I later use to seed a LINQ-to-SQL data context.
My internal key for decryption is stored, privately in a class as `private static readonly string myPassword = "MyPassword";` (just an example, the actual password is more complex and valid). There's no single statement, anywhere, referencing that field, except one on a static method using it as a parameter for another decryption method (instance method), which instantiates a new `DESCryptoServiceProvider` with it.
And still, I get the following exception from time to time in my production server logs:
```
Exception type: CryptographicException
Exception message: Specified key is a known weak key for 'DES' and cannot be used.
```
As such, the connection string decryption fails and, of course, the database is not accessed anymore. Poof, application down.
How is this even possible?
**Disclaimer**: This is an old application I am maintaining. The description I provide here is to help troubleshoot, but I cannot change the way it works internally. Some will agree that this is not the best approach but the application has been running without a problem for more than 2 years and suddenly these exceptions are taking it down.
**Update**: I've been requested to clarify with a stack trace of the exception, but I cannot provide one full stack trace for NDA reasons. What I *can* tell is the following:
* The object throwing the exception is the `System.Security.DESCryptoServiceProvider.CreateDecryptor(Byte[] rgbKey, Byte[] rgbIV)` method
* The original key (the one we actually use) does validate and does not generate an exception. Still, we get this exception from time to time (not always), without knowing which is the current value which does not validate
* The instance of the `DESCryptoServiceProvider` is stored statically, privately, in a helper class
* This is all triggered by `System.Web.HttpApplication.InitModulesCommon()`, to initialize the application internal parts
Also, here is an obscured stack trace:
```
at System.Security.Cryptography.DESCryptoServiceProvider.CreateDecryptor(Byte[] rgbKey, Byte[] rgbIV)
at SymmetricEncryption.Decrypt(String contents, String key)
// our helper, just a wrapper, based from this class: http://www.codeproject.com/Articles/1967/Encryption-Decryption-with-NET
at EncryptedConnectionStringHelper.DecryptUserAndPass(String connectionString)\
// our container for parsing the connection string and decrypting the user and password, not the full connstring is encrypted
at OurModule.Init(OurConfigurationSection config)
at OurModule.Boot(OurConfigurationSection config)
at OurModule.Boot()
at OurModule.Init(HttpApplication context)
at System.Web.HttpApplication.InitModulesCommon()
at System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers)
at System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context)
at System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context)
at System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr)
```
Our application registers this module in the following way:
```
public class OurModule : IHttpModule
{
public static bool initialized = false;
public void Init(HttpApplication context)
{
if (!initialized) {
subscribe(context);
OurModule.Boot();
initialized = true;
}
}
``` | 2012/09/04 | [
"https://Stackoverflow.com/questions/12265969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147507/"
] | Have a look at your wrapper `SymmetricEncryption.Decrypt`. My guess would be that the issue is in there. How it creates the Key from your password. Does it use [PasswordDeriveBytes](http://msdn.microsoft.com/en-us/library/system.security.cryptography.passwordderivebytes.aspx "PasswordDiriveBytes") or some other half baked solution?
Failing that maybe you could try get a better key than "MyPassword".
Failing that maybe you could use web.config encryption. [Scott Gu wrote about it here.](http://weblogs.asp.net/scottgu/archive/2006/01/09/434893.aspx) | It doesn't sound like anything's *mutating* the object. It sounds like "something" (if you'd posted the stack trace it would be clearer) is *validating* the DES key... and complaining that it's a known weak key.
Ideally, you should change your password to be more secure, of course - but if you can't, you should look at exactly where that exception's coming from, and see if there are settings somewhere controlling how and when it's validated.
If you're not already logging the full stack trace (instead of just the exception message) that's the *first* thing you should do. |
50,972,926 | I have a query with the following `SELECT` statement:
`(ascii(substring((SELECT column_name FROM information_schema.columns WHERE table_name =\'admin-modules\' LIMIT 1,1),1,1))) > 0-- -`
But this gives me the following error:
`You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'admin-modules\' limit 1,1),1,1))) > 0-- -' at line 1`
Can someone help me figure out why I'm getting the error? | 2018/06/21 | [
"https://Stackoverflow.com/questions/50972926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9974157/"
] | Unfortunately default behavior of GNU toolchain is to not export symbols from executables by default (as opposed to shared libraries which default to exporting all their symbols). You can use a big-hammer `-rdynamic` flag which tells linker to export *all* symbols from your executable file. A less intrusive solution would be to provide explicit exports file via `-Wl,--dynamic-list` when linking (see example usage in [Clang sources](https://github.com/llvm-mirror/clang/blob/4920d3228938c5ca6d6dd267da640e9ff65b6802/lib/Driver/Tools.cpp#L3180)). | Ok, I will post an answer based on previous comments.
To make all functions dynamically exported: `-rdynamic`.
For a single function to be always linked (even if not referenced) you need to add `-u<function>` to the link line.
To link all functions (even unreferenced) use `--whole-archive`. To return to the normal linking use `--no-whole-archive` |
180,973 | I had a master with two slaves replicating. I added two more DBs in `my.cnf` for replication and did the standard procedure like lock the table for read, back up and restored the DBs to slaves. Now I am trying to restart my master MySQL server and getting error:
```
MySQL manager or server PID file could not be found! [FAILED]
Starting MySQL.Manager of pid-file quit without updating fi[FAILED]
```
The output from the error log is as follows:
```
100914 09:22:43 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/var
100914 9:22:43 [Warning] The syntax '--log' is deprecated and will be removed in MySQL 7.0. Please use '--general_log'/'--general_log_file' instead.
/usr/local/mysql/libexec/mysqld: File '/usr/local/mysql/var/mysql-bin.index' not found (Errcode: 13)
100914 9:22:43 [ERROR] Aborting
100914 9:22:43 [Note] /usr/local/mysql/libexec/mysqld: Shutdown complete
100914 09:22:43 mysqld_safe mysqld from pid file /usr/local/mysql/var/mysql1.sitelms.org.pid ended
```
I have the file `/usr/local/mysql/var/mysql-bin.index` and it does exist but `/usr/local/mysql/var/mysql1.sitelms.org.pid` file does not exist. Can someone help me? I don't know what happened here. | 2010/09/14 | [
"https://serverfault.com/questions/180973",
"https://serverfault.com",
"https://serverfault.com/users/36159/"
] | Are you sure you don't have a permission problem? I found [this link](http://forums.mysql.com/read.php?20,78674,78791#msg-78791) about Errcode 13.
Did you search other errors in system logs (messages, syslog, etc)? | You need to go back to the configuration without the two new slaves. Make sure everything is working.
THEN, configure your slaves. You shouldn't need to change anything on the master if it was replicating already. Once you transferred your backup to the slaves and verified that they start up okay, without replicating, then set up the master information.
Can you post the changes you made to your my.cnf file(s)? |
57,190 | 1 John 4:18 (ESV):
>
> There is **no fear in love**, but **perfect love casts out fear**. For fear has to do with punishment, and **whoever fears has not been perfected in love**.
>
>
>
2 Corinthians 7:1 (ESV):
>
> Since we have these promises, beloved, let us cleanse ourselves from every defilement of body and spirit, bringing holiness to completion **in the fear of God**.
>
>
>
According to John, we should seek to be perfected in love, which casts out all fear. In contrast, Paul encourages us to walk in the fear of God. A superficial reading of both verses might give the impression that the two apostles are contradicting each other. Which makes me believe that they are probably referring to different concepts of *fear*.
How should we understand *fear* in the contexts of *"perfect love casts out **fear**"* and *"**fear** of God"* such that there is no contradiction? | 2021/03/27 | [
"https://hermeneutics.stackexchange.com/questions/57190",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/-1/"
] | What is it we are afraid of?
---
I find Jesus' answer quite effective:
>
> And fear not them which kill the body, but are not able to kill the
> soul: but rather fear him which is able to destroy both soul and body
> in hell. (Matthew 10:28)
>
>
>
Let's look at 3 types of fear:
1. Fear of man - this could include worrying about bad things humans can do to you (I get why people worry about that), or it could be worrying about how people will perceive you (e.g. am I more motivated by what people think of me or what God thinks of me). Jesus did not appear to let fear of man hold him back.
2. Fear of the devil - this seems to be what Jesus is referring to in latter clause above. I don't know that He is counseling us to be so much afraid as cognizant. We could phrase this colloquially as: be mindful that spiritual dangers can do far more lasting damage than physical dangers. The damage that can be done--long-term--by sin is a frightening prospect indeed.
3. Fear of God - if one is wicked, God's judgement should be scary. I've heard it said that the prophets talk about hell in an effort to scare the hell out of people. If one is righteous, "fear of God" would be more plainly stated as "respect for God". Note that the Greek φόβος (phobos) has several known usages (see [here](https://biblehub.com/greek/5401.htm)):
(a) fear, terror, alarm
(b) the object or cause of fear
(c) reverence, respect
So I take Paul's counsel to mean that we should fear God--and we get to choose whether that fear is #1 or #3.
**Conclusion**
If we are filled with Christ-like love and motivation as John directs, #1 holds no lasting threat, #2 holds little tempting power, and #3 becomes respect for the Sovereign of the universe.
When scripture speaks of the great and dreadful day of the Lord, one way to read that (just a touch tongue-in-cheek), is that it will be great for the righteous, and dreadful for the wicked. | phobos phobia
The concepts of fear in both passages are the same. The issue, or the question your asking arises out of a ‘clash’ between our western understanding of ‘fear’ and ‘love’ *and* the intended biblical understanding of these.
In western ‘thinking’, the opposite of ‘love’ is ‘hate’. This is **not** biblical - at all. Biblically, the opposite of ‘love’ is ‘fear’. And reflecting on this leads to a different interpretation of those texts you quoted.
The ‘fear of God’ is a reverence, and holding God in ‘awe’. After he has done something that is absolutely overwhelming, or when you reflect on something He had done that is overwhelming - like he ‘saved’ you. And, his ‘act’ to you was solely done in Love. Out of Love. A ‘Godly Fear’ is the response - in fact, it is the only response possible.
Now in your other passage, if you sense you deserve punishment (e.g. for ‘sinning’), then you are not aware, or have not considered his Love. **IF** you were aware [deep down, in your heart] of his Love, you would have zero sense of punishment. Love does not punish - ever! |
57,190 | 1 John 4:18 (ESV):
>
> There is **no fear in love**, but **perfect love casts out fear**. For fear has to do with punishment, and **whoever fears has not been perfected in love**.
>
>
>
2 Corinthians 7:1 (ESV):
>
> Since we have these promises, beloved, let us cleanse ourselves from every defilement of body and spirit, bringing holiness to completion **in the fear of God**.
>
>
>
According to John, we should seek to be perfected in love, which casts out all fear. In contrast, Paul encourages us to walk in the fear of God. A superficial reading of both verses might give the impression that the two apostles are contradicting each other. Which makes me believe that they are probably referring to different concepts of *fear*.
How should we understand *fear* in the contexts of *"perfect love casts out **fear**"* and *"**fear** of God"* such that there is no contradiction? | 2021/03/27 | [
"https://hermeneutics.stackexchange.com/questions/57190",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/-1/"
] | What is it we are afraid of?
---
I find Jesus' answer quite effective:
>
> And fear not them which kill the body, but are not able to kill the
> soul: but rather fear him which is able to destroy both soul and body
> in hell. (Matthew 10:28)
>
>
>
Let's look at 3 types of fear:
1. Fear of man - this could include worrying about bad things humans can do to you (I get why people worry about that), or it could be worrying about how people will perceive you (e.g. am I more motivated by what people think of me or what God thinks of me). Jesus did not appear to let fear of man hold him back.
2. Fear of the devil - this seems to be what Jesus is referring to in latter clause above. I don't know that He is counseling us to be so much afraid as cognizant. We could phrase this colloquially as: be mindful that spiritual dangers can do far more lasting damage than physical dangers. The damage that can be done--long-term--by sin is a frightening prospect indeed.
3. Fear of God - if one is wicked, God's judgement should be scary. I've heard it said that the prophets talk about hell in an effort to scare the hell out of people. If one is righteous, "fear of God" would be more plainly stated as "respect for God". Note that the Greek φόβος (phobos) has several known usages (see [here](https://biblehub.com/greek/5401.htm)):
(a) fear, terror, alarm
(b) the object or cause of fear
(c) reverence, respect
So I take Paul's counsel to mean that we should fear God--and we get to choose whether that fear is #1 or #3.
**Conclusion**
If we are filled with Christ-like love and motivation as John directs, #1 holds no lasting threat, #2 holds little tempting power, and #3 becomes respect for the Sovereign of the universe.
When scripture speaks of the great and dreadful day of the Lord, one way to read that (just a touch tongue-in-cheek), is that it will be great for the righteous, and dreadful for the wicked. | **Perfect love drives out fear.**
1 John 4:18 (NASB)
>
> 18 There is no fear in love, but perfect love drives out fear, because
> fear involves punishment, and the one who fears is not perfected in
> love.
>
>
>
The degree to which a Christian loves God and senses God’s love for him has a direct effect on him in the future day of judgment. Those within whom love has been made “perfect” do not experience fear. ( 1 John 4:18, 19.) “Fear exercises a restraint” that would keep us from approaching God freely. So if we are experiencing such fear, ‘we have not been made perfect in love.’ But if we have been “made perfect in love,” this quality fills our hearts, impels us to do the divine will, and moves us to stay close to our heavenly Father in prayer and have no fear in the future day of Judgement. We certainly have reason to love God and pray to him, for as John says, ‘We love because God first loved us.’
A Christian must always have a reverential fear of our heavenly Father, born of deep respect for his position, power, and justice. But we also love God as our Father and feel a closeness to him and freeness to approach him. Rather than being inhibited by any terror of him, we trust that we can approach him, as a child feels open to approaching a loving parent.
**Bringing holiness to completion in the fear of God.**
2 Corinthians 7:1 ESV
>
> **Since we have these promises**, beloved, let us cleanse ourselves from
> every defilement of body and spirit, bringing holiness to completion
> in the fear of God.
>
>
>
From the above verse, we note that God wants us to be free of practices that pollute our fleshly bodies and damage our spiritual mental attitude. We must therefore avoid addictive behaviors that are known to be harmful to our physical and mental health.
To cleanse ourselves **we have these promises.** What promises? I will be a father to you, And you shall be sons and daughters to Me,”(2 Cor.6:17-18)
2 Corinthians 6:17-18 (NASB)
>
> 17 Therefore, come out from their midst and be separate,” says the
> Lord. “And do not touch what is unclean; And I will welcome you. 18
> And I will be a father to you, And you shall be sons and daughters to
> Me,” Says the Lord Almighty.
>
>
>
Just imagine God will become your Father, protect you, and love as a son or daughter, provided you avoid defilements of the flesh and mental spirit. Christians are constantly refined (bringing holiness to completion) as they strive to come closer to God’s perfect standards. They are motivated by wholesome “fear of God,” one that stems from deep love and profound reverence, or respect, for him
**Conclusion:** There is no contradiction. This fear is not the fear of expectation of harm or pain, but wholesome fear of incurring the displeasure of God our heavenly Father, because of our deep respect and love for him. |
57,190 | 1 John 4:18 (ESV):
>
> There is **no fear in love**, but **perfect love casts out fear**. For fear has to do with punishment, and **whoever fears has not been perfected in love**.
>
>
>
2 Corinthians 7:1 (ESV):
>
> Since we have these promises, beloved, let us cleanse ourselves from every defilement of body and spirit, bringing holiness to completion **in the fear of God**.
>
>
>
According to John, we should seek to be perfected in love, which casts out all fear. In contrast, Paul encourages us to walk in the fear of God. A superficial reading of both verses might give the impression that the two apostles are contradicting each other. Which makes me believe that they are probably referring to different concepts of *fear*.
How should we understand *fear* in the contexts of *"perfect love casts out **fear**"* and *"**fear** of God"* such that there is no contradiction? | 2021/03/27 | [
"https://hermeneutics.stackexchange.com/questions/57190",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/-1/"
] | What is it we are afraid of?
---
I find Jesus' answer quite effective:
>
> And fear not them which kill the body, but are not able to kill the
> soul: but rather fear him which is able to destroy both soul and body
> in hell. (Matthew 10:28)
>
>
>
Let's look at 3 types of fear:
1. Fear of man - this could include worrying about bad things humans can do to you (I get why people worry about that), or it could be worrying about how people will perceive you (e.g. am I more motivated by what people think of me or what God thinks of me). Jesus did not appear to let fear of man hold him back.
2. Fear of the devil - this seems to be what Jesus is referring to in latter clause above. I don't know that He is counseling us to be so much afraid as cognizant. We could phrase this colloquially as: be mindful that spiritual dangers can do far more lasting damage than physical dangers. The damage that can be done--long-term--by sin is a frightening prospect indeed.
3. Fear of God - if one is wicked, God's judgement should be scary. I've heard it said that the prophets talk about hell in an effort to scare the hell out of people. If one is righteous, "fear of God" would be more plainly stated as "respect for God". Note that the Greek φόβος (phobos) has several known usages (see [here](https://biblehub.com/greek/5401.htm)):
(a) fear, terror, alarm
(b) the object or cause of fear
(c) reverence, respect
So I take Paul's counsel to mean that we should fear God--and we get to choose whether that fear is #1 or #3.
**Conclusion**
If we are filled with Christ-like love and motivation as John directs, #1 holds no lasting threat, #2 holds little tempting power, and #3 becomes respect for the Sovereign of the universe.
When scripture speaks of the great and dreadful day of the Lord, one way to read that (just a touch tongue-in-cheek), is that it will be great for the righteous, and dreadful for the wicked. | In the statement “there is no fear in love” the author specifically addresses one type of fear, and that is the fear of judgment or, more precisely, the fear of punishment:
* v. 18 - There is no fear in love, but perfect love drives out fear, because *fear involves punishment* (1 Jn 4:18)
“But perfect love drives out fear.” The key to understanding this passage may lie in how we interpret the words “perfect love.” The word “perfect” hints that this love is first and foremost a love that can only come from God.
* v. 7 - Beloved, let’s love one another; *for love is from God*, and everyone who loves has been born of God and knows God. 8 The one who does not love does not know God, because *God is love*.
* v. 10 - In this is love, not that we loved God, but that He loved us and sent His Son to be the propitiation for our sins.
God’s perfect love is perfected in us when we mirror his love in our love for one another:
* v. 12 - If we love one another, God remains in us, and His love is perfected in us
When we love one another as God loves us, we will have fulfilled God’s commandment of love and can have confidence in the day of judgment:
* 17 - By this, love is perfected with us, so that we may have confidence in the day of judgment; because as He is, we also are in this world.
* v. 21 - And this commandment we have from Him, that the one who loves God must also love his brother and sister.
But the reason that “perfect love drives out fear” does not lie in the fact that we have fulfilled God’s commandment and therefore need not fear judgment. Rather, love drives out fear because our love is no longer governed by the fear of punishment. There is a subtle but distinct difference in what motivates our love. When God’s love is perfected in us, we love because God first loved us, not because we fear his judgment and punishment.
* v. 19 - We love, because He first loved us.
Perhaps the answer to the OP’s question is that *ideally*, when God’s love has been perfected in us, our fear of God will not arise from or be governed by any fear of judgment or punishment, and our motivation for fulfilling his commandment will lie solely in the desire to love God by perfectly imitating His love for us in our love for one another. |
57,190 | 1 John 4:18 (ESV):
>
> There is **no fear in love**, but **perfect love casts out fear**. For fear has to do with punishment, and **whoever fears has not been perfected in love**.
>
>
>
2 Corinthians 7:1 (ESV):
>
> Since we have these promises, beloved, let us cleanse ourselves from every defilement of body and spirit, bringing holiness to completion **in the fear of God**.
>
>
>
According to John, we should seek to be perfected in love, which casts out all fear. In contrast, Paul encourages us to walk in the fear of God. A superficial reading of both verses might give the impression that the two apostles are contradicting each other. Which makes me believe that they are probably referring to different concepts of *fear*.
How should we understand *fear* in the contexts of *"perfect love casts out **fear**"* and *"**fear** of God"* such that there is no contradiction? | 2021/03/27 | [
"https://hermeneutics.stackexchange.com/questions/57190",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/-1/"
] | **Perfect love drives out fear.**
1 John 4:18 (NASB)
>
> 18 There is no fear in love, but perfect love drives out fear, because
> fear involves punishment, and the one who fears is not perfected in
> love.
>
>
>
The degree to which a Christian loves God and senses God’s love for him has a direct effect on him in the future day of judgment. Those within whom love has been made “perfect” do not experience fear. ( 1 John 4:18, 19.) “Fear exercises a restraint” that would keep us from approaching God freely. So if we are experiencing such fear, ‘we have not been made perfect in love.’ But if we have been “made perfect in love,” this quality fills our hearts, impels us to do the divine will, and moves us to stay close to our heavenly Father in prayer and have no fear in the future day of Judgement. We certainly have reason to love God and pray to him, for as John says, ‘We love because God first loved us.’
A Christian must always have a reverential fear of our heavenly Father, born of deep respect for his position, power, and justice. But we also love God as our Father and feel a closeness to him and freeness to approach him. Rather than being inhibited by any terror of him, we trust that we can approach him, as a child feels open to approaching a loving parent.
**Bringing holiness to completion in the fear of God.**
2 Corinthians 7:1 ESV
>
> **Since we have these promises**, beloved, let us cleanse ourselves from
> every defilement of body and spirit, bringing holiness to completion
> in the fear of God.
>
>
>
From the above verse, we note that God wants us to be free of practices that pollute our fleshly bodies and damage our spiritual mental attitude. We must therefore avoid addictive behaviors that are known to be harmful to our physical and mental health.
To cleanse ourselves **we have these promises.** What promises? I will be a father to you, And you shall be sons and daughters to Me,”(2 Cor.6:17-18)
2 Corinthians 6:17-18 (NASB)
>
> 17 Therefore, come out from their midst and be separate,” says the
> Lord. “And do not touch what is unclean; And I will welcome you. 18
> And I will be a father to you, And you shall be sons and daughters to
> Me,” Says the Lord Almighty.
>
>
>
Just imagine God will become your Father, protect you, and love as a son or daughter, provided you avoid defilements of the flesh and mental spirit. Christians are constantly refined (bringing holiness to completion) as they strive to come closer to God’s perfect standards. They are motivated by wholesome “fear of God,” one that stems from deep love and profound reverence, or respect, for him
**Conclusion:** There is no contradiction. This fear is not the fear of expectation of harm or pain, but wholesome fear of incurring the displeasure of God our heavenly Father, because of our deep respect and love for him. | phobos phobia
The concepts of fear in both passages are the same. The issue, or the question your asking arises out of a ‘clash’ between our western understanding of ‘fear’ and ‘love’ *and* the intended biblical understanding of these.
In western ‘thinking’, the opposite of ‘love’ is ‘hate’. This is **not** biblical - at all. Biblically, the opposite of ‘love’ is ‘fear’. And reflecting on this leads to a different interpretation of those texts you quoted.
The ‘fear of God’ is a reverence, and holding God in ‘awe’. After he has done something that is absolutely overwhelming, or when you reflect on something He had done that is overwhelming - like he ‘saved’ you. And, his ‘act’ to you was solely done in Love. Out of Love. A ‘Godly Fear’ is the response - in fact, it is the only response possible.
Now in your other passage, if you sense you deserve punishment (e.g. for ‘sinning’), then you are not aware, or have not considered his Love. **IF** you were aware [deep down, in your heart] of his Love, you would have zero sense of punishment. Love does not punish - ever! |
57,190 | 1 John 4:18 (ESV):
>
> There is **no fear in love**, but **perfect love casts out fear**. For fear has to do with punishment, and **whoever fears has not been perfected in love**.
>
>
>
2 Corinthians 7:1 (ESV):
>
> Since we have these promises, beloved, let us cleanse ourselves from every defilement of body and spirit, bringing holiness to completion **in the fear of God**.
>
>
>
According to John, we should seek to be perfected in love, which casts out all fear. In contrast, Paul encourages us to walk in the fear of God. A superficial reading of both verses might give the impression that the two apostles are contradicting each other. Which makes me believe that they are probably referring to different concepts of *fear*.
How should we understand *fear* in the contexts of *"perfect love casts out **fear**"* and *"**fear** of God"* such that there is no contradiction? | 2021/03/27 | [
"https://hermeneutics.stackexchange.com/questions/57190",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/-1/"
] | **Perfect love drives out fear.**
1 John 4:18 (NASB)
>
> 18 There is no fear in love, but perfect love drives out fear, because
> fear involves punishment, and the one who fears is not perfected in
> love.
>
>
>
The degree to which a Christian loves God and senses God’s love for him has a direct effect on him in the future day of judgment. Those within whom love has been made “perfect” do not experience fear. ( 1 John 4:18, 19.) “Fear exercises a restraint” that would keep us from approaching God freely. So if we are experiencing such fear, ‘we have not been made perfect in love.’ But if we have been “made perfect in love,” this quality fills our hearts, impels us to do the divine will, and moves us to stay close to our heavenly Father in prayer and have no fear in the future day of Judgement. We certainly have reason to love God and pray to him, for as John says, ‘We love because God first loved us.’
A Christian must always have a reverential fear of our heavenly Father, born of deep respect for his position, power, and justice. But we also love God as our Father and feel a closeness to him and freeness to approach him. Rather than being inhibited by any terror of him, we trust that we can approach him, as a child feels open to approaching a loving parent.
**Bringing holiness to completion in the fear of God.**
2 Corinthians 7:1 ESV
>
> **Since we have these promises**, beloved, let us cleanse ourselves from
> every defilement of body and spirit, bringing holiness to completion
> in the fear of God.
>
>
>
From the above verse, we note that God wants us to be free of practices that pollute our fleshly bodies and damage our spiritual mental attitude. We must therefore avoid addictive behaviors that are known to be harmful to our physical and mental health.
To cleanse ourselves **we have these promises.** What promises? I will be a father to you, And you shall be sons and daughters to Me,”(2 Cor.6:17-18)
2 Corinthians 6:17-18 (NASB)
>
> 17 Therefore, come out from their midst and be separate,” says the
> Lord. “And do not touch what is unclean; And I will welcome you. 18
> And I will be a father to you, And you shall be sons and daughters to
> Me,” Says the Lord Almighty.
>
>
>
Just imagine God will become your Father, protect you, and love as a son or daughter, provided you avoid defilements of the flesh and mental spirit. Christians are constantly refined (bringing holiness to completion) as they strive to come closer to God’s perfect standards. They are motivated by wholesome “fear of God,” one that stems from deep love and profound reverence, or respect, for him
**Conclusion:** There is no contradiction. This fear is not the fear of expectation of harm or pain, but wholesome fear of incurring the displeasure of God our heavenly Father, because of our deep respect and love for him. | In the statement “there is no fear in love” the author specifically addresses one type of fear, and that is the fear of judgment or, more precisely, the fear of punishment:
* v. 18 - There is no fear in love, but perfect love drives out fear, because *fear involves punishment* (1 Jn 4:18)
“But perfect love drives out fear.” The key to understanding this passage may lie in how we interpret the words “perfect love.” The word “perfect” hints that this love is first and foremost a love that can only come from God.
* v. 7 - Beloved, let’s love one another; *for love is from God*, and everyone who loves has been born of God and knows God. 8 The one who does not love does not know God, because *God is love*.
* v. 10 - In this is love, not that we loved God, but that He loved us and sent His Son to be the propitiation for our sins.
God’s perfect love is perfected in us when we mirror his love in our love for one another:
* v. 12 - If we love one another, God remains in us, and His love is perfected in us
When we love one another as God loves us, we will have fulfilled God’s commandment of love and can have confidence in the day of judgment:
* 17 - By this, love is perfected with us, so that we may have confidence in the day of judgment; because as He is, we also are in this world.
* v. 21 - And this commandment we have from Him, that the one who loves God must also love his brother and sister.
But the reason that “perfect love drives out fear” does not lie in the fact that we have fulfilled God’s commandment and therefore need not fear judgment. Rather, love drives out fear because our love is no longer governed by the fear of punishment. There is a subtle but distinct difference in what motivates our love. When God’s love is perfected in us, we love because God first loved us, not because we fear his judgment and punishment.
* v. 19 - We love, because He first loved us.
Perhaps the answer to the OP’s question is that *ideally*, when God’s love has been perfected in us, our fear of God will not arise from or be governed by any fear of judgment or punishment, and our motivation for fulfilling his commandment will lie solely in the desire to love God by perfectly imitating His love for us in our love for one another. |
57,267,771 | I can't pass my data from the fakeGenreService.js via array.
Please check the screenshot for the data rendered.
You will see that all things are being rendered, just not (the movie Title, Genre, Stock and Rate) which are available in the fakeGenreService.js
Please do let me know where I am going wrong??????
PLEASE DO LET ME KNOW WHY MY DATA IS NOT BEING RENDERED AND WHAT I NEED TO MAKE THE CHANGES IN THE CODE
I WILL REALLY APPRECIATE YOUR HELP!!!!!!
I am uploading my three files below
1. App.js
2. fakeGenreService.js
3. movies.js
Please check if I am passing the array correctly in the state block?????``
Here is App.js
<http://prnt.sc/olccj9>
Here is fakegenreService.js
<http://prnt.sc/olcdr5>
Here is movies.js
<http://prnt.sc/olce2x>
Here is the final result for the developmentserver
<http://prnt.sc/olcejx>
Tried various troubsleshooting steps for the array function
This part deals with App.js
```
import React, { Component } from "react";
import React, { Component } from "react";
import Movies from "./components/movies";
import "./App.css";
class App extends Component {
render() {
return (
<main className="container">
<Movies />
</main>
);
}
}
export default App;
```
This part is for movies.js
```
import React, { Component } from "react";
import { getMovies } from "../services/fakeMovieService";
class Movies extends Component {
constructor(props) {
super(props);
this.state = {
movies: [getMovies()]
};
}
handleDelete = movie => {
console.log(movie);
};
render() {
return (
<table className="table">
<thead>
<tr>
<th>Title</th>
<th>Genre</th>
<th>Stock</th>
<th>Rate</th>
<th />
</tr>
</thead>
<tbody>
{this.state.movies.map(movie => (
<tr key={movie._id}>
<td>{movie.title}</td>
<td>{movie.genre}</td>
<td>{movie.numberInStock}</td>
<td>{movie.dailyRentalRate}</td>
<td>
<button
onCick={() => this.handleDelete(movie)}
className="btn btn-danger btn-sm"
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
);
}
}
export default Movies;
```
Here is fakeMovieService.js
```
import * as genresAPI from "./fakeGenreService";
const movies = [
{
_id: "5b21ca3eeb7f6fbccd471815",
title: "Terminator",
genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
numberInStock: 6,
dailyRentalRate: 2.5,
publishDate: "2018-01-03T19:04:28.809Z"
},
{
_id: "5b21ca3eeb7f6fbccd471816",
title: "Die Hard",
genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
numberInStock: 5,
dailyRentalRate: 2.5
},
{
_id: "5b21ca3eeb7f6fbccd471817",
title: "Get Out",
genre: { _id: "5b21ca3eeb7f6fbccd471820", name: "Thriller" },
numberInStock: 8,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd471819",
title: "Trip to Italy",
genre: { _id: "5b21ca3eeb7f6fbccd471814", name: "Comedy" },
numberInStock: 7,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd47181a",
title: "Airplane",
genre: { _id: "5b21ca3eeb7f6fbccd471814", name: "Comedy" },
numberInStock: 7,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd47181b",
title: "Wedding Crashers",
genre: { _id: "5b21ca3eeb7f6fbccd471814", name: "Comedy" },
numberInStock: 7,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd47181e",
title: "Gone Girl",
genre: { _id: "5b21ca3eeb7f6fbccd471820", name: "Thriller" },
numberInStock: 7,
dailyRentalRate: 4.5
},
{
_id: "5b21ca3eeb7f6fbccd47181f",
title: "The Sixth Sense",
genre: { _id: "5b21ca3eeb7f6fbccd471820", name: "Thriller" },
numberInStock: 4,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd471821",
title: "The Avengers",
genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
numberInStock: 7,
dailyRentalRate: 3.5
}
];
export function getMovies() {
return movies;
}
export function getMovie(id) {
return movies.find(m => m._id === id);
}
export function saveMovie(movie) {
let movieInDb = movies.find(m => m._id === movie._id) || {};
movieInDb.name = movie.name;
movieInDb.genre = genresAPI.genres.find(g => g._id === movie.genreId);
movieInDb.numberInStock = movie.numberInStock;
movieInDb.dailyRentalRate = movie.dailyRentalRate;
if (!movieInDb._id) {
movieInDb._id = Date.now();
movies.push(movieInDb);
}
return movieInDb;
}
export function deleteMovie(id) {
let movieInDb = movies.find(m => m._id === id);
movies.splice(movies.indexOf(movieInDb), 1);
return movieInDb;
}
```
The result of the data being rendered is shown here:
<http://prnt.sc/olcejx>
Please let me know how could the movies defined in getMovies() function coud be rendered in the table. | 2019/07/30 | [
"https://Stackoverflow.com/questions/57267771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11850763/"
] | The issue seems to be here. `getMovies` would already return an array. You're wrapping it inside another one. Here, in yout `Movies` Component class, change it to just the function call:
```
constructor(props) {
super(props);
this.state = {
movies: getMovies() // [getMovies()]
};
}
``` | You wrap the movies array into a second array. That does not work. You should write it like this :
```
this.state = {
movies: getMovies()
};
``` |
57,267,771 | I can't pass my data from the fakeGenreService.js via array.
Please check the screenshot for the data rendered.
You will see that all things are being rendered, just not (the movie Title, Genre, Stock and Rate) which are available in the fakeGenreService.js
Please do let me know where I am going wrong??????
PLEASE DO LET ME KNOW WHY MY DATA IS NOT BEING RENDERED AND WHAT I NEED TO MAKE THE CHANGES IN THE CODE
I WILL REALLY APPRECIATE YOUR HELP!!!!!!
I am uploading my three files below
1. App.js
2. fakeGenreService.js
3. movies.js
Please check if I am passing the array correctly in the state block?????``
Here is App.js
<http://prnt.sc/olccj9>
Here is fakegenreService.js
<http://prnt.sc/olcdr5>
Here is movies.js
<http://prnt.sc/olce2x>
Here is the final result for the developmentserver
<http://prnt.sc/olcejx>
Tried various troubsleshooting steps for the array function
This part deals with App.js
```
import React, { Component } from "react";
import React, { Component } from "react";
import Movies from "./components/movies";
import "./App.css";
class App extends Component {
render() {
return (
<main className="container">
<Movies />
</main>
);
}
}
export default App;
```
This part is for movies.js
```
import React, { Component } from "react";
import { getMovies } from "../services/fakeMovieService";
class Movies extends Component {
constructor(props) {
super(props);
this.state = {
movies: [getMovies()]
};
}
handleDelete = movie => {
console.log(movie);
};
render() {
return (
<table className="table">
<thead>
<tr>
<th>Title</th>
<th>Genre</th>
<th>Stock</th>
<th>Rate</th>
<th />
</tr>
</thead>
<tbody>
{this.state.movies.map(movie => (
<tr key={movie._id}>
<td>{movie.title}</td>
<td>{movie.genre}</td>
<td>{movie.numberInStock}</td>
<td>{movie.dailyRentalRate}</td>
<td>
<button
onCick={() => this.handleDelete(movie)}
className="btn btn-danger btn-sm"
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
);
}
}
export default Movies;
```
Here is fakeMovieService.js
```
import * as genresAPI from "./fakeGenreService";
const movies = [
{
_id: "5b21ca3eeb7f6fbccd471815",
title: "Terminator",
genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
numberInStock: 6,
dailyRentalRate: 2.5,
publishDate: "2018-01-03T19:04:28.809Z"
},
{
_id: "5b21ca3eeb7f6fbccd471816",
title: "Die Hard",
genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
numberInStock: 5,
dailyRentalRate: 2.5
},
{
_id: "5b21ca3eeb7f6fbccd471817",
title: "Get Out",
genre: { _id: "5b21ca3eeb7f6fbccd471820", name: "Thriller" },
numberInStock: 8,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd471819",
title: "Trip to Italy",
genre: { _id: "5b21ca3eeb7f6fbccd471814", name: "Comedy" },
numberInStock: 7,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd47181a",
title: "Airplane",
genre: { _id: "5b21ca3eeb7f6fbccd471814", name: "Comedy" },
numberInStock: 7,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd47181b",
title: "Wedding Crashers",
genre: { _id: "5b21ca3eeb7f6fbccd471814", name: "Comedy" },
numberInStock: 7,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd47181e",
title: "Gone Girl",
genre: { _id: "5b21ca3eeb7f6fbccd471820", name: "Thriller" },
numberInStock: 7,
dailyRentalRate: 4.5
},
{
_id: "5b21ca3eeb7f6fbccd47181f",
title: "The Sixth Sense",
genre: { _id: "5b21ca3eeb7f6fbccd471820", name: "Thriller" },
numberInStock: 4,
dailyRentalRate: 3.5
},
{
_id: "5b21ca3eeb7f6fbccd471821",
title: "The Avengers",
genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
numberInStock: 7,
dailyRentalRate: 3.5
}
];
export function getMovies() {
return movies;
}
export function getMovie(id) {
return movies.find(m => m._id === id);
}
export function saveMovie(movie) {
let movieInDb = movies.find(m => m._id === movie._id) || {};
movieInDb.name = movie.name;
movieInDb.genre = genresAPI.genres.find(g => g._id === movie.genreId);
movieInDb.numberInStock = movie.numberInStock;
movieInDb.dailyRentalRate = movie.dailyRentalRate;
if (!movieInDb._id) {
movieInDb._id = Date.now();
movies.push(movieInDb);
}
return movieInDb;
}
export function deleteMovie(id) {
let movieInDb = movies.find(m => m._id === id);
movies.splice(movies.indexOf(movieInDb), 1);
return movieInDb;
}
```
The result of the data being rendered is shown here:
<http://prnt.sc/olcejx>
Please let me know how could the movies defined in getMovies() function coud be rendered in the table. | 2019/07/30 | [
"https://Stackoverflow.com/questions/57267771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11850763/"
] | The issue seems to be here. `getMovies` would already return an array. You're wrapping it inside another one. Here, in yout `Movies` Component class, change it to just the function call:
```
constructor(props) {
super(props);
this.state = {
movies: getMovies() // [getMovies()]
};
}
``` | getMovies() already returning array. You are calling that function inside an array. so movies have an array of array. like this movies: [[datas]].
In movies.js file do this changes in the constructor. It should work.
```
this.state = {
movies: getMovies();
}
``` |
17,826,995 | Is there a way with C# generics to limit a type `T` to be castable from another type?
**Example**:
Lets say I am saving information in the registry as a `string`, and when I restore the information I would like to have a function that looks something like that:
```
static T GetObjectFromRegistry<T>(string regPath) where T castable from string
{
string regValue = //Getting the registry value...
T objectValue = (T)regValue;
return objectValue ;
}
``` | 2013/07/24 | [
"https://Stackoverflow.com/questions/17826995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/900570/"
] | There is no such type of constraints in .NET. There is only six types of constraints available (see [Constraints on Type Parameters](http://msdn.microsoft.com/en-us/library/d5x73970.aspx)):
* `where T: struct` type argument must be a value type
* `where T: class` type argument must be a reference type
* `where T: new()` type argument must have a public parameterless constructor
* `where T: <base class name>` type argument must be or derive from the specified base class
* `where T: <interface name>` type argument must be or implement the specified interface
* `where T: U` type argument supplied for T must be or derive from the argument supplied for U
If you want to cast string to your type, you can do casting to object first. But you can't put constraint on type parameter to make sure this casting can occur:
```
static T GetObjectFromRegistry<T>(string regPath)
{
string regValue = //Getting the regisstry value...
T objectValue = (T)(object)regValue;
return objectValue ;
}
```
Another option - create interface:
```
public interface IInitializable
{
void InitFrom(string s);
}
```
And put it as constraint:
```
static T GetObjectFromRegistry<T>(string regPath)
where T: IInitializable, new()
{
string regValue = //Getting the regisstry value...
T objectValue = new T();
objectValue.InitFrom(regValue);
return objectValue ;
}
``` | Types are determined during compilation. You can't change the types during runtime. It is possible to cast object to its base or child class
Ref -
[Difference between object a = new Dog() vs Dog a = new Dog()](https://stackoverflow.com/questions/8556651/difference-between-object-a-new-dog-vs-dog-a-new-dog) |
17,826,995 | Is there a way with C# generics to limit a type `T` to be castable from another type?
**Example**:
Lets say I am saving information in the registry as a `string`, and when I restore the information I would like to have a function that looks something like that:
```
static T GetObjectFromRegistry<T>(string regPath) where T castable from string
{
string regValue = //Getting the registry value...
T objectValue = (T)regValue;
return objectValue ;
}
``` | 2013/07/24 | [
"https://Stackoverflow.com/questions/17826995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/900570/"
] | There is no such type of constraints in .NET. There is only six types of constraints available (see [Constraints on Type Parameters](http://msdn.microsoft.com/en-us/library/d5x73970.aspx)):
* `where T: struct` type argument must be a value type
* `where T: class` type argument must be a reference type
* `where T: new()` type argument must have a public parameterless constructor
* `where T: <base class name>` type argument must be or derive from the specified base class
* `where T: <interface name>` type argument must be or implement the specified interface
* `where T: U` type argument supplied for T must be or derive from the argument supplied for U
If you want to cast string to your type, you can do casting to object first. But you can't put constraint on type parameter to make sure this casting can occur:
```
static T GetObjectFromRegistry<T>(string regPath)
{
string regValue = //Getting the regisstry value...
T objectValue = (T)(object)regValue;
return objectValue ;
}
```
Another option - create interface:
```
public interface IInitializable
{
void InitFrom(string s);
}
```
And put it as constraint:
```
static T GetObjectFromRegistry<T>(string regPath)
where T: IInitializable, new()
{
string regValue = //Getting the regisstry value...
T objectValue = new T();
objectValue.InitFrom(regValue);
return objectValue ;
}
``` | Constraints spell out like "the type of T must either be of type U or inherit type U", so the constraint you are looking for isn't doable.
*everything* is "castable" to `String` anyway, through `.ToString()` (YMMV) |
25,145,446 | I have a similar question to this:
<https://superuser.com/questions/140242/why-my-browsers-display-xml-files-as-blank-pages?rq=1>
I don't see my xml in my browser, but just a blank page. I only checked Chrome and firefox, but it's happening in both.
The difference is that I'm getting data from MySQL and echoing it. So the file extension is .php and not .xml
```
$row = mysqli_fetch_assoc($resource);
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<video>\n";
echo "<path>" . $row['path'] . "</path>\n";
echo "</video>\n";
```
I see a blank page when I go to the url. But when I "View Source", I see the xml tree.
```
<video>
<path>URLtoVideo.mp4</path>
</video>
```
My main goal is to grab the xml data and request it in Flash using URLRequest(). But I get this error
```
TypeError: Error #1088: The markup in the document following the root element must be well-formed.
```
I think this may be the problem to the error I get in Flash. I only have one root node, and I don't think I have any problems with the child nodes. So my only assumption is that the error occurs because of the blank page. | 2014/08/05 | [
"https://Stackoverflow.com/questions/25145446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3893794/"
] | Try adding an XML header before your output. Your browser is trying to read it like HTML otherwise
```
header('Content-type: text/xml');
``` | You need to make and xml object/element and then echo it, plus dont forget to add `header('Content-Type: text/xml');` before echo.
For more refer this link <http://php.net/manual/en/simplexml.examples-basic.php> |
25,145,446 | I have a similar question to this:
<https://superuser.com/questions/140242/why-my-browsers-display-xml-files-as-blank-pages?rq=1>
I don't see my xml in my browser, but just a blank page. I only checked Chrome and firefox, but it's happening in both.
The difference is that I'm getting data from MySQL and echoing it. So the file extension is .php and not .xml
```
$row = mysqli_fetch_assoc($resource);
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<video>\n";
echo "<path>" . $row['path'] . "</path>\n";
echo "</video>\n";
```
I see a blank page when I go to the url. But when I "View Source", I see the xml tree.
```
<video>
<path>URLtoVideo.mp4</path>
</video>
```
My main goal is to grab the xml data and request it in Flash using URLRequest(). But I get this error
```
TypeError: Error #1088: The markup in the document following the root element must be well-formed.
```
I think this may be the problem to the error I get in Flash. I only have one root node, and I don't think I have any problems with the child nodes. So my only assumption is that the error occurs because of the blank page. | 2014/08/05 | [
"https://Stackoverflow.com/questions/25145446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3893794/"
] | The XML is not displayed because the browser interpret it.
When you write
```
<table></table>
```
In your HTML page, you will not see the string
```
"<table><table\>"
```
But an empty table.
This is the same things about XML content.
Another Stack overflow post got an answer to this [HERE](https://stackoverflow.com/questions/7519618/display-xml-content-in-html-page)
Here I copy past the answer of mellamokb
>
> Simple solution is to embed inside of a element, which will
> preserve both the formatting and the angle brackets. I have also
> removed the border with style="border:none;" which makes the textarea
> invisible.
>
>
> Here is a sample: xxxx
>
>
> | You need to make and xml object/element and then echo it, plus dont forget to add `header('Content-Type: text/xml');` before echo.
For more refer this link <http://php.net/manual/en/simplexml.examples-basic.php> |
212,982 | Example: I want to get **all tag names** that are inside **field\_tags** of node 5.
I can get the target\_id with $node->field\_tags->[getValue()](https://api.drupal.org/api/drupal/core!modules!views!src!Plugin!views!field!Field.php/function/Field%3A%3AgetValue/8.2.x);
[![enter image description here](https://i.stack.imgur.com/m15Go.jpg)](https://i.stack.imgur.com/m15Go.jpg)
But the problem is, I don't know what entity the target\_id value belongs to. Could be a node id, term id, user id. Without that info, I am not able to use the target\_id to get the name of the tag.
How can I get all the names of an entity reference field? | 2016/08/28 | [
"https://drupal.stackexchange.com/questions/212982",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/27710/"
] | The easiest way to get what you want is something like this:
```
$names = [];
foreach ($node->field_tags as $item) {
if ($item->entity) {
$names[$item->entity->id()] = $item->entity->label();
}
}
```
`->entity` is a so called computed property, it doesn't show up in `getValues()`. All reference fields have it.
And yes, forget about `print_r()` on entity or other complex objects. They contain objects that reference each other, and `print_r()` can't handle that. If you have an entity, always use `print_r($entity->toArray())`, then you get the field values only. You could install devel module or use a debugger, but that will give you the internal structure of an entity, which is not really want you want to see. | An entity reference field, by definition, can only target one entity type so you can know what your target type is by calling up [`getSetting()`](https://api.drupal.org/api/drupal/core%21modules%21field%21src%21Entity%21FieldStorageConfig.php/function/FieldStorageConfig%3A%3AgetSettings/8.2.x) on the field definition.
```
// Print the targeted entity type field.
$field = \Drupal\field\Entity\FieldStorageConfig::loadByName('node','field_tags');
echo $field->getSetting('target_type');
```
Or better yet, use [`EntityReferenceFieldItemList::referencedEntities()`](https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Field!EntityReferenceFieldItemList.php/function/EntityReferenceFieldItemList%3A%3AreferencedEntities/8.2.x) to pull up the node's referenced entities and the associated data you need.
```
// Return an array of Entity objects referenced in the field.
$node->field_tags->referencedEntities();
``` |
34,526,413 | I have an array in my database that is being stored in the following format
>
> ["size:medium","height:10cm"]
>
>
>
this is problematic to display in a table.
Is there any way that I can convert this into a Javascript object or a JSON string like this?
>
> {"size":"medium","height":"10cm"
> }
>
>
>
p.s:i know json.stringfy,json\_encode.the thing is they have stored key value pair as one string | 2015/12/30 | [
"https://Stackoverflow.com/questions/34526413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5491725/"
] | In Javascript you can use JSON.parse(), in order to convert your array in Javascript Object. | **In PHP Use : json\_encode(text)**
**In JavaScript : JSON.parse(text)** |
34,526,413 | I have an array in my database that is being stored in the following format
>
> ["size:medium","height:10cm"]
>
>
>
this is problematic to display in a table.
Is there any way that I can convert this into a Javascript object or a JSON string like this?
>
> {"size":"medium","height":"10cm"
> }
>
>
>
p.s:i know json.stringfy,json\_encode.the thing is they have stored key value pair as one string | 2015/12/30 | [
"https://Stackoverflow.com/questions/34526413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5491725/"
] | You can try something like this:
**Note:** *Following code will make array of objects. I don't think `{["size:medium", "height:10cm"]}` is a valid object*
```js
(function() {
var styleArr = ["size:medium", "height:10cm", "font-size: 18px"];
var resultObject = {};
styleArr.forEach(function(item) {
var values = item.replace(/\"/g, '').split(':');
resultObject[values[0]] = values[1];
});
console.log(resultObject)
})()
``` | In Javascript you can use JSON.parse(), in order to convert your array in Javascript Object. |
34,526,413 | I have an array in my database that is being stored in the following format
>
> ["size:medium","height:10cm"]
>
>
>
this is problematic to display in a table.
Is there any way that I can convert this into a Javascript object or a JSON string like this?
>
> {"size":"medium","height":"10cm"
> }
>
>
>
p.s:i know json.stringfy,json\_encode.the thing is they have stored key value pair as one string | 2015/12/30 | [
"https://Stackoverflow.com/questions/34526413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5491725/"
] | You can build an object with the elements of the array and the left part as key and the right part as value of the by `:` separated strings.
```
array object
--------------------------- ---------------------------
[ -> {
"size:medium", -> size: "medium",
"height:10cm" -> height: "10cm"
] -> }
```
```js
var array = ["size:medium", "height:10cm"],
object = array.reduce(function (r, a) {
var t = a.split(':');
r[t[0]] = t[1];
return r;
}, {});
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
``` | In Javascript you can use JSON.parse(), in order to convert your array in Javascript Object. |
34,526,413 | I have an array in my database that is being stored in the following format
>
> ["size:medium","height:10cm"]
>
>
>
this is problematic to display in a table.
Is there any way that I can convert this into a Javascript object or a JSON string like this?
>
> {"size":"medium","height":"10cm"
> }
>
>
>
p.s:i know json.stringfy,json\_encode.the thing is they have stored key value pair as one string | 2015/12/30 | [
"https://Stackoverflow.com/questions/34526413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5491725/"
] | You can try something like this:
**Note:** *Following code will make array of objects. I don't think `{["size:medium", "height:10cm"]}` is a valid object*
```js
(function() {
var styleArr = ["size:medium", "height:10cm", "font-size: 18px"];
var resultObject = {};
styleArr.forEach(function(item) {
var values = item.replace(/\"/g, '').split(':');
resultObject[values[0]] = values[1];
});
console.log(resultObject)
})()
``` | **In PHP Use : json\_encode(text)**
**In JavaScript : JSON.parse(text)** |
34,526,413 | I have an array in my database that is being stored in the following format
>
> ["size:medium","height:10cm"]
>
>
>
this is problematic to display in a table.
Is there any way that I can convert this into a Javascript object or a JSON string like this?
>
> {"size":"medium","height":"10cm"
> }
>
>
>
p.s:i know json.stringfy,json\_encode.the thing is they have stored key value pair as one string | 2015/12/30 | [
"https://Stackoverflow.com/questions/34526413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5491725/"
] | You can build an object with the elements of the array and the left part as key and the right part as value of the by `:` separated strings.
```
array object
--------------------------- ---------------------------
[ -> {
"size:medium", -> size: "medium",
"height:10cm" -> height: "10cm"
] -> }
```
```js
var array = ["size:medium", "height:10cm"],
object = array.reduce(function (r, a) {
var t = a.split(':');
r[t[0]] = t[1];
return r;
}, {});
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
``` | **In PHP Use : json\_encode(text)**
**In JavaScript : JSON.parse(text)** |
203,043 | Started this unfortunately as an answer in this question on GPUs under Mma12:
[previous GPU question](https://mathematica.stackexchange.com/questions/195348/mathematica-12-supported-gpus), while it should have gone into a new question. I will try to answer questions already posted on the other thread here (or directly in this new description)
After today's upgrade to MMA12 I am running into a CUDA issue with my Quadro RTX 4000. (@CA Trevillian: The Quadro RTX4000 is the entry level Quadro card, not a mobile. It is the equivalent of a 2070.)
* OS is Win 8.1 x64 latest patch level.
* Latest NVidia driver version "431.02-quadro-desktop-notebook-win8-win7-64bit-international-whql". @Trevillian: 431.02 is also what the CUDADriverVersion[] reflects.
* Latest CUDA install, "cuda\_10.1.168\_425.25\_windows". Installation will not overwrite newer display drivers even if it is configured to install during installation (states drivers for display and audio are newer and leaves them).
* CUDA samples from the CUDA install, e.g., under extras/demo\_suite are running fine (no errors).
* Paclet installs:
+ CUDAQ[] triggering install? I thought it should only return True/False, so False if paclet is not installed?
+ paclet installs from the network are slow (half hour, not my internet connection, has anyone also noticed the paclet server being slow?)
+ paclet reinstall with Update-True is not too smooth. It complains that after the CUDAQ[] install it cannot deinstall completely and the state of the install is not always obvious
+ install from local paclet file works. I tried a few variations to test if there would be differences, e.g., PacletInstall and CUDAResourcesInstall with or without the Update Flag. All appear to be the same.
* The CudaResourcesInstall or paclet install with a RebuildPacletData[] results in Paclet[CUDAResources,12.0.359,<>] . So things are looking fine.
* However a CUDAResourcesInformation[] then goes haywire:
+ StringToStream: String expected at position 1 in StringToStream[ImportExport`HashDump`expr].
+ BinaryReadList: \$Failed is not a string, SocketObject, InputStream[ ], or OutputStream[ ].
+ Java: Method named update defined in class java.security. MessageDigest$Delegate was called with an incorrect number or type of arguments. The arguments, shown here in a list, were {BinaryReadList[$Failed,Byte,131072],0,3}.
+ etc., about 9 lines total, until "Further output of Java::argx will be suppressed during this calculation"
+ Then hangs until manually aborted.
+ CUDA with 9.x under Mma 11.3 did not hang, but as it did not know the card, it had some form of generic resource listed as in CUDAResourcesInformation[] resulting in:
{{Name->CUDAResources,Version->11.3.82,BuildNumber->,Qualifier->Win64,WolframVersion->11.2,11.3,SystemID->{Windows-x86-64},Description->{ToolkitVersion -> v9.1, MinimumDriver -> 290},etc.
@Kuba: thanks for the heads up. Indeed, this also went to WRI support. However I posted this here once more, as there might be other persons with the Quadro RTX4000 card or encountering issues with Mma12 and CUDA as the other post suggested. I cannot enter the new tags for quadro or RTX4000 yet. Hopefully the post is now correct.
The error messages sound as if some jumbled arguments might be fed to a java routine, maybe the Quadro card is not properly recognized, resulting in an empty string entering the "gears" of the CUDALink software?
Certainly would be curious if someone would have any ideas. There are a few CUDA/MMa projects waiting. Thanks in advance. | 2019/07/31 | [
"https://mathematica.stackexchange.com/questions/203043",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/66772/"
] | Answer: CUDA does not load correctly under mma12.0 in my case (Win 8.1/x64, installation on D drive, no other obvious issues).
**Workaround:** In addition to Needs["CUDALink`"], as a manual load of libeay32.dll, e.g., LibraryLoad["\SystemFiles\Libraries\Windows-\
x86-64\libeay32.dll"]
then things proceed as intended.
The cause appears to be buried in how the paths were written in OpenSSLLink64.dll for mma12.0. Hashes and checksums of my installation match Wolframs'. Other checks together with Wolfram support also bore out. Even substituting the 11.3 version of the OpenSSLLink64.dll in place for the 12.0 version worked loading the missing library. It failed using the vanilla installation only loading CUDALink.
It could be that things work with the default installation. In my case with Mma installed on a D drive, it did not work for 12.0 but worked on 11.3.
If I had to guess, it could be e.g., a missing quote, then paths working under Linux or MacOS but not with Windows formats, including spaces etc. A full solution is out of reach for the user, except with the workaround provided. | CUDA package works for me. UBUNTU 20.04, WL/MMA 12.03.0.0, NVIDIA GTX 1650, NVidia Driver 470.86, CUDA version 11.4
Everything works just fine, as long as (for some reason) you do not run CUDAResourcesInformation[ ]. If I run it, I've to restart my pc, to get CUDA package works again. |
7,440 | Many religions share same stories, Christianity, Judaism and Islam for example (the ones I know of at least). Some of those stories could even be traced to earlier civilizations in the Middle East region, like the belief in resurrection, God (gods) intervention in the worldly affairs, heaven, hell etc. My question is could we trace these ideas to one ancient religion? That is was their a religion to have been a focal point of all religion of which basic religious ideas came up and been absorbed and modified by other religions? Or were they generally the product of many stories of many unrelated not connected religions which developed separately? | 2013/01/26 | [
"https://history.stackexchange.com/questions/7440",
"https://history.stackexchange.com",
"https://history.stackexchange.com/users/1681/"
] | Religions are cultural concepts, they evolve through the time, adapting some ideas from others, providing some new ones, etc. For example, having Christianity of 500 AD, you'd be able to point out some concepts taken (directly or not quite so) from Judaism, Zoroastrianism, Neoplatonism, etc. Then, Christianity itself influenced Islam, Manicheism, lots of Gnostic denominations. Putting these influences graphically, the graph would be in my opinion pretty dense.
The answer to the question would be, that yes, we'd be able to point out some religions, like Judaism, Zoroastrianism, hypothetical Proto-Indo-European cult, etc., which had greater influence than others, and developed concepts used later by many others through the time. But, whose influence was greater, more inspirational, etc., that's highly speculative and controversional, hence - there will be no concrete answer. | No I dont think we could trace it all back to one religion. Religion is a big part of the human experience the need to create a mythical realm where we go after death, seems to be a part of just about every culture. The major religions of today are likely derived from several older religions. |
7,440 | Many religions share same stories, Christianity, Judaism and Islam for example (the ones I know of at least). Some of those stories could even be traced to earlier civilizations in the Middle East region, like the belief in resurrection, God (gods) intervention in the worldly affairs, heaven, hell etc. My question is could we trace these ideas to one ancient religion? That is was their a religion to have been a focal point of all religion of which basic religious ideas came up and been absorbed and modified by other religions? Or were they generally the product of many stories of many unrelated not connected religions which developed separately? | 2013/01/26 | [
"https://history.stackexchange.com/questions/7440",
"https://history.stackexchange.com",
"https://history.stackexchange.com/users/1681/"
] | Religions are cultural concepts, they evolve through the time, adapting some ideas from others, providing some new ones, etc. For example, having Christianity of 500 AD, you'd be able to point out some concepts taken (directly or not quite so) from Judaism, Zoroastrianism, Neoplatonism, etc. Then, Christianity itself influenced Islam, Manicheism, lots of Gnostic denominations. Putting these influences graphically, the graph would be in my opinion pretty dense.
The answer to the question would be, that yes, we'd be able to point out some religions, like Judaism, Zoroastrianism, hypothetical Proto-Indo-European cult, etc., which had greater influence than others, and developed concepts used later by many others through the time. But, whose influence was greater, more inspirational, etc., that's highly speculative and controversional, hence - there will be no concrete answer. | There are lots of religions that was inspired by others.
Roman mythology is in fact almost fully taken from the Greeks. There are some differences, like gods' names and heroes (Ulysses vs Oddyseus), and the main difference is the legend of foundation of Rome (Romulus, Remus and she-wolf).
In the [Acts of Apostles chapter 17](http://www.catholic.org/bible/book.php?id=51&bible_chapter=17) there is a story about St. Paul in Athens where he finds an altar "to the unknown god" and he uses this to introduce Christian God to people. This altar was made because there where many cultures (Persian, Egyptian etc.) having their own gods, which were not treated as wrong by the Greeks, but some kind of supplement to their pantheon. I think many foreign gods became also Olympian gods, for example there was always a god responsible for some territory or terrain feature (like gods of rivers, forests etc.). They were accepted while visiting new countries.
And of course the idea of one god (God) is an Israeli development, which was then taken (or improved) by Christianity and then by Islam. Combination of many religions led in later times to creation new ones, like eg. [Voodoo](http://en.wikipedia.org/wiki/West_African_Vodun).
However, answering to your question. Some religions state, that they were revealed by god(s). In fact, the latest sources of the religions are holy books of themselves and there is no written moment "ok, for now we were atheists and we begin to believe that the truth is out there".
We can only imagine what is the reason of "creation" of gods, of course if they had not existed forever. The natural forces which were not to be explained by small brain, were inspiration of gods. There are lots of natural forces that have (good or devastating) impact on the environment (like rain, thunderbolt, grow of flora, large animals, astronomical events etc.), or on the human himself (like fire that is hot, death of old age). I think that primitive man seeing these random events must have thought that there is some kind of supernatural control in this.
I don't know when this happened, but I think this is the answer to your question: the oldest religion of man is the Nature itself. Because it is much stronger than human, not controllable, not explainable and sometimes acting like it was pleased or angry, this can be considered by the oldest god.
In every (I think) religion gods can control the Nature, like an archer controls his arrow, spearman controls his spear, a farmer controls his corn, a shepherd controls his flock. This control seems to be such obvious, that nothing in the world should have not been left without control. The feeling that everything has its controller fulfils one of human basic needs: the need of security. |
7,440 | Many religions share same stories, Christianity, Judaism and Islam for example (the ones I know of at least). Some of those stories could even be traced to earlier civilizations in the Middle East region, like the belief in resurrection, God (gods) intervention in the worldly affairs, heaven, hell etc. My question is could we trace these ideas to one ancient religion? That is was their a religion to have been a focal point of all religion of which basic religious ideas came up and been absorbed and modified by other religions? Or were they generally the product of many stories of many unrelated not connected religions which developed separately? | 2013/01/26 | [
"https://history.stackexchange.com/questions/7440",
"https://history.stackexchange.com",
"https://history.stackexchange.com/users/1681/"
] | Religions are cultural concepts, they evolve through the time, adapting some ideas from others, providing some new ones, etc. For example, having Christianity of 500 AD, you'd be able to point out some concepts taken (directly or not quite so) from Judaism, Zoroastrianism, Neoplatonism, etc. Then, Christianity itself influenced Islam, Manicheism, lots of Gnostic denominations. Putting these influences graphically, the graph would be in my opinion pretty dense.
The answer to the question would be, that yes, we'd be able to point out some religions, like Judaism, Zoroastrianism, hypothetical Proto-Indo-European cult, etc., which had greater influence than others, and developed concepts used later by many others through the time. But, whose influence was greater, more inspirational, etc., that's highly speculative and controversional, hence - there will be no concrete answer. | Well, the obvious answer is that both Christianity and Islam emerged from Judaism. Christianity is pretty easy to see, since most of us in the West have at least a passing familiarity with the documents (particularly the New Testament) which note the early consolidation of a particular apocalyptic Jewish death cult into what we now know as the Christian religion.
The direct link between Judaism and Islam is a bit more tenuous and, given the poor relationship between the adherents of those religions right now, controversial. However, Wikipedia notes that there was at the very least a bit of tolerance between Mohammed and the earlier religions:
<http://en.wikipedia.org/wiki/Islamic%E2%80%93Jewish_relations#Religious_figures>
>
> In the course of Muhammad's proselytizing in Makkah/Mecca, he initially viewed Christians and Jews (both of whom he referred to as "People of the Book") as natural allies, sharing the core principles of his teachings, and anticipated their acceptance and support.
>
>
>
I read a narrative a few years ago whose name completely escapes me that hid a fairly plausible explanation for this camaraderie: that Islam itself arose from a coalition of Arabs and messianic Jews, and that while Muhammed himself may or may not have been born Jewish, he based much of Islam on Jewish teaching. It was an interesting book, wrapped up in the narrative format because it was aimed at the general public rather than academia.
Otherwise, I've heard people (not all of them evangelists) insist that LDS is not a Christian religion, and if you believe this to be the case, then that is most certainly an example of a large religion which has its basis in another one. There is no question that Joseph Smith drew heavily on the Old and New Testaments for inspiration. |
7,440 | Many religions share same stories, Christianity, Judaism and Islam for example (the ones I know of at least). Some of those stories could even be traced to earlier civilizations in the Middle East region, like the belief in resurrection, God (gods) intervention in the worldly affairs, heaven, hell etc. My question is could we trace these ideas to one ancient religion? That is was their a religion to have been a focal point of all religion of which basic religious ideas came up and been absorbed and modified by other religions? Or were they generally the product of many stories of many unrelated not connected religions which developed separately? | 2013/01/26 | [
"https://history.stackexchange.com/questions/7440",
"https://history.stackexchange.com",
"https://history.stackexchange.com/users/1681/"
] | Religions are cultural concepts, they evolve through the time, adapting some ideas from others, providing some new ones, etc. For example, having Christianity of 500 AD, you'd be able to point out some concepts taken (directly or not quite so) from Judaism, Zoroastrianism, Neoplatonism, etc. Then, Christianity itself influenced Islam, Manicheism, lots of Gnostic denominations. Putting these influences graphically, the graph would be in my opinion pretty dense.
The answer to the question would be, that yes, we'd be able to point out some religions, like Judaism, Zoroastrianism, hypothetical Proto-Indo-European cult, etc., which had greater influence than others, and developed concepts used later by many others through the time. But, whose influence was greater, more inspirational, etc., that's highly speculative and controversional, hence - there will be no concrete answer. | If you read the Old Testament, you will see hints of polytheism being at the roots of Judaism. Comparing the different names you see this as well.
The story of Abraham choosing one god above the others is a case in point. El, a Canaanite god name etymologically related to Allah, is generally the original word for God in Judaism. After Moses, however, you have that and YHWH. It was written this way to hide the true name. One theory I read is that Moses actually picked up this name from his father-in-law when he was in exile and combined it with the Hebrew El. It is my opinion that Elyah sounds a lot like Allah.
As the nations develop, there are lots of references to other gods getting in the way and causing El's anger against a king. Even later in the Old Testament when they were in exile in Persia (practicing monotheistic Zoroastrianism) you see the leaders of Persia and the Hebrews talking about God as if it's the same one as their own. Persia's religion is derived from the Indo-European religions where Zoroaster also chose one god above the others, Ahura Mazda over the Devas.
Note in Hinduism it's the reverse, the Devas beat the Asura. The Hindu Asura, being composed of gods like Dyaus Pita (sky father) which is etymologically equivalent to Zeus Pitar (Greek), Jupiter (Roman), and Tiu (Norse/German) which Tuesday is named for. Asura is etymologically related to Aesir and Asgard from Norse.
Buddhism is an offshoot of Hinduism. It is fairly clear Hinduism/Buddhism is derived from the the same roots ultimately as Greek, Roman, Norse, and Zoroastrianism.
Christianity and Islam are derived from Judaism. Less clear is the influence of Zoroasterianism on the Judaism/Christian/Islam monotheism. The Persian connection is interesting. One possibility is monotheism didn't actually exist in Isra-El and Judah until the Persians influenced them.
In that case it's possible that all of these major religions are partially derived from the base Indo-European pantheon with heavy influence from Semitic polytheism (Canaan, Egypt, and Babylon). Another possibility is Abraham, Moses, and Zoroaster independently came up with monotheism. Even later people such as King Josiah may have. It's probably a big jumble of influences with one group of people deciding there is only one God.
My sources are reading the English Bible, Wikipedia, and Online Etymology. |
7,440 | Many religions share same stories, Christianity, Judaism and Islam for example (the ones I know of at least). Some of those stories could even be traced to earlier civilizations in the Middle East region, like the belief in resurrection, God (gods) intervention in the worldly affairs, heaven, hell etc. My question is could we trace these ideas to one ancient religion? That is was their a religion to have been a focal point of all religion of which basic religious ideas came up and been absorbed and modified by other religions? Or were they generally the product of many stories of many unrelated not connected religions which developed separately? | 2013/01/26 | [
"https://history.stackexchange.com/questions/7440",
"https://history.stackexchange.com",
"https://history.stackexchange.com/users/1681/"
] | No I dont think we could trace it all back to one religion. Religion is a big part of the human experience the need to create a mythical realm where we go after death, seems to be a part of just about every culture. The major religions of today are likely derived from several older religions. | There are lots of religions that was inspired by others.
Roman mythology is in fact almost fully taken from the Greeks. There are some differences, like gods' names and heroes (Ulysses vs Oddyseus), and the main difference is the legend of foundation of Rome (Romulus, Remus and she-wolf).
In the [Acts of Apostles chapter 17](http://www.catholic.org/bible/book.php?id=51&bible_chapter=17) there is a story about St. Paul in Athens where he finds an altar "to the unknown god" and he uses this to introduce Christian God to people. This altar was made because there where many cultures (Persian, Egyptian etc.) having their own gods, which were not treated as wrong by the Greeks, but some kind of supplement to their pantheon. I think many foreign gods became also Olympian gods, for example there was always a god responsible for some territory or terrain feature (like gods of rivers, forests etc.). They were accepted while visiting new countries.
And of course the idea of one god (God) is an Israeli development, which was then taken (or improved) by Christianity and then by Islam. Combination of many religions led in later times to creation new ones, like eg. [Voodoo](http://en.wikipedia.org/wiki/West_African_Vodun).
However, answering to your question. Some religions state, that they were revealed by god(s). In fact, the latest sources of the religions are holy books of themselves and there is no written moment "ok, for now we were atheists and we begin to believe that the truth is out there".
We can only imagine what is the reason of "creation" of gods, of course if they had not existed forever. The natural forces which were not to be explained by small brain, were inspiration of gods. There are lots of natural forces that have (good or devastating) impact on the environment (like rain, thunderbolt, grow of flora, large animals, astronomical events etc.), or on the human himself (like fire that is hot, death of old age). I think that primitive man seeing these random events must have thought that there is some kind of supernatural control in this.
I don't know when this happened, but I think this is the answer to your question: the oldest religion of man is the Nature itself. Because it is much stronger than human, not controllable, not explainable and sometimes acting like it was pleased or angry, this can be considered by the oldest god.
In every (I think) religion gods can control the Nature, like an archer controls his arrow, spearman controls his spear, a farmer controls his corn, a shepherd controls his flock. This control seems to be such obvious, that nothing in the world should have not been left without control. The feeling that everything has its controller fulfils one of human basic needs: the need of security. |
7,440 | Many religions share same stories, Christianity, Judaism and Islam for example (the ones I know of at least). Some of those stories could even be traced to earlier civilizations in the Middle East region, like the belief in resurrection, God (gods) intervention in the worldly affairs, heaven, hell etc. My question is could we trace these ideas to one ancient religion? That is was their a religion to have been a focal point of all religion of which basic religious ideas came up and been absorbed and modified by other religions? Or were they generally the product of many stories of many unrelated not connected religions which developed separately? | 2013/01/26 | [
"https://history.stackexchange.com/questions/7440",
"https://history.stackexchange.com",
"https://history.stackexchange.com/users/1681/"
] | Well, the obvious answer is that both Christianity and Islam emerged from Judaism. Christianity is pretty easy to see, since most of us in the West have at least a passing familiarity with the documents (particularly the New Testament) which note the early consolidation of a particular apocalyptic Jewish death cult into what we now know as the Christian religion.
The direct link between Judaism and Islam is a bit more tenuous and, given the poor relationship between the adherents of those religions right now, controversial. However, Wikipedia notes that there was at the very least a bit of tolerance between Mohammed and the earlier religions:
<http://en.wikipedia.org/wiki/Islamic%E2%80%93Jewish_relations#Religious_figures>
>
> In the course of Muhammad's proselytizing in Makkah/Mecca, he initially viewed Christians and Jews (both of whom he referred to as "People of the Book") as natural allies, sharing the core principles of his teachings, and anticipated their acceptance and support.
>
>
>
I read a narrative a few years ago whose name completely escapes me that hid a fairly plausible explanation for this camaraderie: that Islam itself arose from a coalition of Arabs and messianic Jews, and that while Muhammed himself may or may not have been born Jewish, he based much of Islam on Jewish teaching. It was an interesting book, wrapped up in the narrative format because it was aimed at the general public rather than academia.
Otherwise, I've heard people (not all of them evangelists) insist that LDS is not a Christian religion, and if you believe this to be the case, then that is most certainly an example of a large religion which has its basis in another one. There is no question that Joseph Smith drew heavily on the Old and New Testaments for inspiration. | There are lots of religions that was inspired by others.
Roman mythology is in fact almost fully taken from the Greeks. There are some differences, like gods' names and heroes (Ulysses vs Oddyseus), and the main difference is the legend of foundation of Rome (Romulus, Remus and she-wolf).
In the [Acts of Apostles chapter 17](http://www.catholic.org/bible/book.php?id=51&bible_chapter=17) there is a story about St. Paul in Athens where he finds an altar "to the unknown god" and he uses this to introduce Christian God to people. This altar was made because there where many cultures (Persian, Egyptian etc.) having their own gods, which were not treated as wrong by the Greeks, but some kind of supplement to their pantheon. I think many foreign gods became also Olympian gods, for example there was always a god responsible for some territory or terrain feature (like gods of rivers, forests etc.). They were accepted while visiting new countries.
And of course the idea of one god (God) is an Israeli development, which was then taken (or improved) by Christianity and then by Islam. Combination of many religions led in later times to creation new ones, like eg. [Voodoo](http://en.wikipedia.org/wiki/West_African_Vodun).
However, answering to your question. Some religions state, that they were revealed by god(s). In fact, the latest sources of the religions are holy books of themselves and there is no written moment "ok, for now we were atheists and we begin to believe that the truth is out there".
We can only imagine what is the reason of "creation" of gods, of course if they had not existed forever. The natural forces which were not to be explained by small brain, were inspiration of gods. There are lots of natural forces that have (good or devastating) impact on the environment (like rain, thunderbolt, grow of flora, large animals, astronomical events etc.), or on the human himself (like fire that is hot, death of old age). I think that primitive man seeing these random events must have thought that there is some kind of supernatural control in this.
I don't know when this happened, but I think this is the answer to your question: the oldest religion of man is the Nature itself. Because it is much stronger than human, not controllable, not explainable and sometimes acting like it was pleased or angry, this can be considered by the oldest god.
In every (I think) religion gods can control the Nature, like an archer controls his arrow, spearman controls his spear, a farmer controls his corn, a shepherd controls his flock. This control seems to be such obvious, that nothing in the world should have not been left without control. The feeling that everything has its controller fulfils one of human basic needs: the need of security. |
7,440 | Many religions share same stories, Christianity, Judaism and Islam for example (the ones I know of at least). Some of those stories could even be traced to earlier civilizations in the Middle East region, like the belief in resurrection, God (gods) intervention in the worldly affairs, heaven, hell etc. My question is could we trace these ideas to one ancient religion? That is was their a religion to have been a focal point of all religion of which basic religious ideas came up and been absorbed and modified by other religions? Or were they generally the product of many stories of many unrelated not connected religions which developed separately? | 2013/01/26 | [
"https://history.stackexchange.com/questions/7440",
"https://history.stackexchange.com",
"https://history.stackexchange.com/users/1681/"
] | If you read the Old Testament, you will see hints of polytheism being at the roots of Judaism. Comparing the different names you see this as well.
The story of Abraham choosing one god above the others is a case in point. El, a Canaanite god name etymologically related to Allah, is generally the original word for God in Judaism. After Moses, however, you have that and YHWH. It was written this way to hide the true name. One theory I read is that Moses actually picked up this name from his father-in-law when he was in exile and combined it with the Hebrew El. It is my opinion that Elyah sounds a lot like Allah.
As the nations develop, there are lots of references to other gods getting in the way and causing El's anger against a king. Even later in the Old Testament when they were in exile in Persia (practicing monotheistic Zoroastrianism) you see the leaders of Persia and the Hebrews talking about God as if it's the same one as their own. Persia's religion is derived from the Indo-European religions where Zoroaster also chose one god above the others, Ahura Mazda over the Devas.
Note in Hinduism it's the reverse, the Devas beat the Asura. The Hindu Asura, being composed of gods like Dyaus Pita (sky father) which is etymologically equivalent to Zeus Pitar (Greek), Jupiter (Roman), and Tiu (Norse/German) which Tuesday is named for. Asura is etymologically related to Aesir and Asgard from Norse.
Buddhism is an offshoot of Hinduism. It is fairly clear Hinduism/Buddhism is derived from the the same roots ultimately as Greek, Roman, Norse, and Zoroastrianism.
Christianity and Islam are derived from Judaism. Less clear is the influence of Zoroasterianism on the Judaism/Christian/Islam monotheism. The Persian connection is interesting. One possibility is monotheism didn't actually exist in Isra-El and Judah until the Persians influenced them.
In that case it's possible that all of these major religions are partially derived from the base Indo-European pantheon with heavy influence from Semitic polytheism (Canaan, Egypt, and Babylon). Another possibility is Abraham, Moses, and Zoroaster independently came up with monotheism. Even later people such as King Josiah may have. It's probably a big jumble of influences with one group of people deciding there is only one God.
My sources are reading the English Bible, Wikipedia, and Online Etymology. | There are lots of religions that was inspired by others.
Roman mythology is in fact almost fully taken from the Greeks. There are some differences, like gods' names and heroes (Ulysses vs Oddyseus), and the main difference is the legend of foundation of Rome (Romulus, Remus and she-wolf).
In the [Acts of Apostles chapter 17](http://www.catholic.org/bible/book.php?id=51&bible_chapter=17) there is a story about St. Paul in Athens where he finds an altar "to the unknown god" and he uses this to introduce Christian God to people. This altar was made because there where many cultures (Persian, Egyptian etc.) having their own gods, which were not treated as wrong by the Greeks, but some kind of supplement to their pantheon. I think many foreign gods became also Olympian gods, for example there was always a god responsible for some territory or terrain feature (like gods of rivers, forests etc.). They were accepted while visiting new countries.
And of course the idea of one god (God) is an Israeli development, which was then taken (or improved) by Christianity and then by Islam. Combination of many religions led in later times to creation new ones, like eg. [Voodoo](http://en.wikipedia.org/wiki/West_African_Vodun).
However, answering to your question. Some religions state, that they were revealed by god(s). In fact, the latest sources of the religions are holy books of themselves and there is no written moment "ok, for now we were atheists and we begin to believe that the truth is out there".
We can only imagine what is the reason of "creation" of gods, of course if they had not existed forever. The natural forces which were not to be explained by small brain, were inspiration of gods. There are lots of natural forces that have (good or devastating) impact on the environment (like rain, thunderbolt, grow of flora, large animals, astronomical events etc.), or on the human himself (like fire that is hot, death of old age). I think that primitive man seeing these random events must have thought that there is some kind of supernatural control in this.
I don't know when this happened, but I think this is the answer to your question: the oldest religion of man is the Nature itself. Because it is much stronger than human, not controllable, not explainable and sometimes acting like it was pleased or angry, this can be considered by the oldest god.
In every (I think) religion gods can control the Nature, like an archer controls his arrow, spearman controls his spear, a farmer controls his corn, a shepherd controls his flock. This control seems to be such obvious, that nothing in the world should have not been left without control. The feeling that everything has its controller fulfils one of human basic needs: the need of security. |
11,644,382 | >
> **Possible Duplicate:**
>
> [Getting ' bad\_request invalid\_json' error when trying to insert document into CouchDB from Node.js](https://stackoverflow.com/questions/11647656/getting-bad-request-invalid-json-error-when-trying-to-insert-document-into-co)
>
>
>
The highest voted answer on
[CouchDB and Node.js - What module do you recommend?](https://stackoverflow.com/questions/5532209/couchdb-and-node-js-what-module-do-you-recommend)
recommends not to use libraries such as nano or cradle for starting with Node.js and CouchDB.
However I haven't found any tutorial on how to perform standard operations for all DBMSes like create database, create table, add and view data etc. programmatically.
EDIT: (partial answer) after installing and starting CouchDB go to `http://localhost:5984/_utils/script/couch.js`. | 2012/07/25 | [
"https://Stackoverflow.com/questions/11644382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/263485/"
] | Thanks to [`Ruben Verborgh`](https://stackoverflow.com/questions/11647656/getting-bad-request-invalid-json-error-when-trying-to-insert-document-into-co#answer-11649320), I compiled micro-tutorial from several sources myself.
```
var http = require('http')
var sys = require('sys')
var couchdbPath = 'http://localhost:5984/'
request = require('request')
h = {accept: 'application/json', 'content-type': 'application/json'}
request(
{uri: couchdbPath + '_all_dbs', headers:h},
function(err, response, body) { console.log(sys.inspect(JSON.parse(body))); }
)
// add database
request(
{uri: couchdbPath + 'dbname', method:'PUT', headers:h},
function (err, response, body) {
if (err)
throw err;
if (response.statusCode !== 201)
throw new Error("Could not create database. " + body);
}
)
// Modify existing document
var options = {
host: "localhost",
port: 5984,
path: "/dbname",
headers: {"content-type": "application/json"},
method: "PUT"
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
//console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(JSON.stringify({
"_id":"rabbit",
"_rev":"4-8cee219da7e61616b7ab22c3614b9526",
"Subject":"I like Plankton"
}));
req.end();
```
I used following documentation:
* [`http.request()`](http://nodejs.org/api/http.html#http_http_request_options_callback)
* [CouchDB Complete HTTP API Reference](http://wiki.apache.org/couchdb/Complete_HTTP_API_Reference) | CouchDB is not an SQL database engine. It's in the family of the "NoSQL" ones.
You don't do select, you don't create tables, etc.
It's completely different.
It's actually using a REST API to work. Like, to access all the documents, you access them using an HTTP GET on the following URL: <http://some.server/someDbName/_all_docs>
For a more thorough introduction, I suggest looking for "CouchDB tutorial" on Google.
You'll find good links like [this one](http://net.tutsplus.com/tutorials/getting-started-with-couchdb/) or [this one](http://nosql.mypopescu.com/post/3767157786/couchdb-tutorial-getting-started-with-couchdb). (I'm not vouching for any, they just look good as an introduction.)
To make an http request in node.js, you can use the [`request`](http://nodejs.org/api/http.html#http_http_request_options_callback) method of the built-in `http` module. A shortcut method is `http.get`, which you can use like this:
```
var http = require( 'http' );
http.get( 'http://some.url/with/params', function( res ) {
// res has the values returned
});
```
**Edit after reading your code:**
Firstly, the doc you're using if outdated. Node is at v0.8, not 0.4.
Secondly, your `request = require('request')` must give some problems (does the module exist?). I don't think the first part is even executed.
Thirdly, just try a GET request for now. Something like:
```
var http = require( 'http' );
http.get( 'http://localhost:5984/_all_dbs', function( res ) {
console.log( res );
});
```
See if it's working. If it is, you already know how to use couchdb ;)
Lastly, your request at the end doesn't seem wrong. Maybe it's related to `require('request')` though, so I don't know. |
11,644,382 | >
> **Possible Duplicate:**
>
> [Getting ' bad\_request invalid\_json' error when trying to insert document into CouchDB from Node.js](https://stackoverflow.com/questions/11647656/getting-bad-request-invalid-json-error-when-trying-to-insert-document-into-co)
>
>
>
The highest voted answer on
[CouchDB and Node.js - What module do you recommend?](https://stackoverflow.com/questions/5532209/couchdb-and-node-js-what-module-do-you-recommend)
recommends not to use libraries such as nano or cradle for starting with Node.js and CouchDB.
However I haven't found any tutorial on how to perform standard operations for all DBMSes like create database, create table, add and view data etc. programmatically.
EDIT: (partial answer) after installing and starting CouchDB go to `http://localhost:5984/_utils/script/couch.js`. | 2012/07/25 | [
"https://Stackoverflow.com/questions/11644382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/263485/"
] | You should start by reading the [CouchDB book](http://guide.couchdb.org/editions/1/en/index.html).
No idea why you don't want to use a module: I think you took an answer out of context (an answer that is probably one year old) and made your decision not to use a module.
That is not likely to be helpful to get stuff done. :) You are just repeating work that is done, and issues that have been fixed, etc.
If you want to learn CouchDB, read the book. You can read nano's source as it maps really closely to the API and should be easy to read, but the book is the full way to go.
If by any reason you decide you still want to implement your own module to do what others already do well, go for it :)
If instead you are looking for resources on using nano there are quite a few:
* readme: [github](https://github.com/dscape/nano/blob/master/README.md)
* screencast: [couchdb and nano](http://nodetuts.com/tutorials/30-couchdb-and-nano.html#video)
* article: [nano - a minimalistic couchdb client for nodejs](http://writings.nunojob.com/2011/08/nano-minimalistic-couchdb-client-for-nodejs.html)
* article: [getting started with node.js and couchdb](http://writings.nunojob.com/2011/09/getting-started-with-nodejs-and-couchdb.html)
* article: [document update handler support](http://jackhq.tumblr.com/post/16035106690/nano-v1-2-x-document-update-handler-support-v1-2-x)
* article: [nano 3](http://writings.nunojob.com/2012/05/Nano-3.html)
* article: [securing a site with couchdb cookie authentication using node.js and nano](http://mahoney.eu/2012/05/23/couchdb-cookie-authentication-nodejs-nano/)
* article: [adding copy to nano](http://blog.jlank.com/2012/07/04/adding-copy-to-nano/)
* article: [how to update a document with nano](http://writings.nunojob.com/2012/07/How-To-Update-A-Document-With-Nano-The-CouchDB-Client-for-Node.js.html)
* article: [mock http integration testing in node.js using nock and specify](http://writings.nunojob.com/2012/05/Mock-HTTP-Integration-Testing-in-Node.js-using-Nock-and-Specify.html)
* article: [mock testing couchdb in node.js with nock and tap](http://writings.nunojob.com/2011/12/Mock-Testing-CouchDB-Using-NodeJS-With-Nock-And-TAP.html) | CouchDB is not an SQL database engine. It's in the family of the "NoSQL" ones.
You don't do select, you don't create tables, etc.
It's completely different.
It's actually using a REST API to work. Like, to access all the documents, you access them using an HTTP GET on the following URL: <http://some.server/someDbName/_all_docs>
For a more thorough introduction, I suggest looking for "CouchDB tutorial" on Google.
You'll find good links like [this one](http://net.tutsplus.com/tutorials/getting-started-with-couchdb/) or [this one](http://nosql.mypopescu.com/post/3767157786/couchdb-tutorial-getting-started-with-couchdb). (I'm not vouching for any, they just look good as an introduction.)
To make an http request in node.js, you can use the [`request`](http://nodejs.org/api/http.html#http_http_request_options_callback) method of the built-in `http` module. A shortcut method is `http.get`, which you can use like this:
```
var http = require( 'http' );
http.get( 'http://some.url/with/params', function( res ) {
// res has the values returned
});
```
**Edit after reading your code:**
Firstly, the doc you're using if outdated. Node is at v0.8, not 0.4.
Secondly, your `request = require('request')` must give some problems (does the module exist?). I don't think the first part is even executed.
Thirdly, just try a GET request for now. Something like:
```
var http = require( 'http' );
http.get( 'http://localhost:5984/_all_dbs', function( res ) {
console.log( res );
});
```
See if it's working. If it is, you already know how to use couchdb ;)
Lastly, your request at the end doesn't seem wrong. Maybe it's related to `require('request')` though, so I don't know. |
11,644,382 | >
> **Possible Duplicate:**
>
> [Getting ' bad\_request invalid\_json' error when trying to insert document into CouchDB from Node.js](https://stackoverflow.com/questions/11647656/getting-bad-request-invalid-json-error-when-trying-to-insert-document-into-co)
>
>
>
The highest voted answer on
[CouchDB and Node.js - What module do you recommend?](https://stackoverflow.com/questions/5532209/couchdb-and-node-js-what-module-do-you-recommend)
recommends not to use libraries such as nano or cradle for starting with Node.js and CouchDB.
However I haven't found any tutorial on how to perform standard operations for all DBMSes like create database, create table, add and view data etc. programmatically.
EDIT: (partial answer) after installing and starting CouchDB go to `http://localhost:5984/_utils/script/couch.js`. | 2012/07/25 | [
"https://Stackoverflow.com/questions/11644382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/263485/"
] | Thanks to [`Ruben Verborgh`](https://stackoverflow.com/questions/11647656/getting-bad-request-invalid-json-error-when-trying-to-insert-document-into-co#answer-11649320), I compiled micro-tutorial from several sources myself.
```
var http = require('http')
var sys = require('sys')
var couchdbPath = 'http://localhost:5984/'
request = require('request')
h = {accept: 'application/json', 'content-type': 'application/json'}
request(
{uri: couchdbPath + '_all_dbs', headers:h},
function(err, response, body) { console.log(sys.inspect(JSON.parse(body))); }
)
// add database
request(
{uri: couchdbPath + 'dbname', method:'PUT', headers:h},
function (err, response, body) {
if (err)
throw err;
if (response.statusCode !== 201)
throw new Error("Could not create database. " + body);
}
)
// Modify existing document
var options = {
host: "localhost",
port: 5984,
path: "/dbname",
headers: {"content-type": "application/json"},
method: "PUT"
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
//console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(JSON.stringify({
"_id":"rabbit",
"_rev":"4-8cee219da7e61616b7ab22c3614b9526",
"Subject":"I like Plankton"
}));
req.end();
```
I used following documentation:
* [`http.request()`](http://nodejs.org/api/http.html#http_http_request_options_callback)
* [CouchDB Complete HTTP API Reference](http://wiki.apache.org/couchdb/Complete_HTTP_API_Reference) | Here are a few hands-on examples, thoughts and code-snippets which should help in your study
[Simple Blog with Coffeescript, Express and CoudbDB](http://blog.koostudios.com/?p=398)
[Thoughts on development using CouchDB and Nodejs](http://tbranyen.com/post/thoughts-on-development-using-couchdb-with-nodejs)
[Bind CouchDB and Node.js](http://architects.dzone.com/articles/glue-bind-couchdb-and-nodejs)
[Getting Started with Node.js, Express and CouchDB](http://www.bytemuse.com/2011/06/getting-started-with-node-js-express-and-couchdb/) - this link does not seem to be accessible now, but it seems a temporary issue.
Here's one on testing CouchDB - [Mock testing CouchDB using Node.js](http://writings.nunojob.com/2011/12/Mock-Testing-CouchDB-Using-NodeJS-With-Nock-And-TAP.html)
Hope it helps. |
11,644,382 | >
> **Possible Duplicate:**
>
> [Getting ' bad\_request invalid\_json' error when trying to insert document into CouchDB from Node.js](https://stackoverflow.com/questions/11647656/getting-bad-request-invalid-json-error-when-trying-to-insert-document-into-co)
>
>
>
The highest voted answer on
[CouchDB and Node.js - What module do you recommend?](https://stackoverflow.com/questions/5532209/couchdb-and-node-js-what-module-do-you-recommend)
recommends not to use libraries such as nano or cradle for starting with Node.js and CouchDB.
However I haven't found any tutorial on how to perform standard operations for all DBMSes like create database, create table, add and view data etc. programmatically.
EDIT: (partial answer) after installing and starting CouchDB go to `http://localhost:5984/_utils/script/couch.js`. | 2012/07/25 | [
"https://Stackoverflow.com/questions/11644382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/263485/"
] | You should start by reading the [CouchDB book](http://guide.couchdb.org/editions/1/en/index.html).
No idea why you don't want to use a module: I think you took an answer out of context (an answer that is probably one year old) and made your decision not to use a module.
That is not likely to be helpful to get stuff done. :) You are just repeating work that is done, and issues that have been fixed, etc.
If you want to learn CouchDB, read the book. You can read nano's source as it maps really closely to the API and should be easy to read, but the book is the full way to go.
If by any reason you decide you still want to implement your own module to do what others already do well, go for it :)
If instead you are looking for resources on using nano there are quite a few:
* readme: [github](https://github.com/dscape/nano/blob/master/README.md)
* screencast: [couchdb and nano](http://nodetuts.com/tutorials/30-couchdb-and-nano.html#video)
* article: [nano - a minimalistic couchdb client for nodejs](http://writings.nunojob.com/2011/08/nano-minimalistic-couchdb-client-for-nodejs.html)
* article: [getting started with node.js and couchdb](http://writings.nunojob.com/2011/09/getting-started-with-nodejs-and-couchdb.html)
* article: [document update handler support](http://jackhq.tumblr.com/post/16035106690/nano-v1-2-x-document-update-handler-support-v1-2-x)
* article: [nano 3](http://writings.nunojob.com/2012/05/Nano-3.html)
* article: [securing a site with couchdb cookie authentication using node.js and nano](http://mahoney.eu/2012/05/23/couchdb-cookie-authentication-nodejs-nano/)
* article: [adding copy to nano](http://blog.jlank.com/2012/07/04/adding-copy-to-nano/)
* article: [how to update a document with nano](http://writings.nunojob.com/2012/07/How-To-Update-A-Document-With-Nano-The-CouchDB-Client-for-Node.js.html)
* article: [mock http integration testing in node.js using nock and specify](http://writings.nunojob.com/2012/05/Mock-HTTP-Integration-Testing-in-Node.js-using-Nock-and-Specify.html)
* article: [mock testing couchdb in node.js with nock and tap](http://writings.nunojob.com/2011/12/Mock-Testing-CouchDB-Using-NodeJS-With-Nock-And-TAP.html) | Here are a few hands-on examples, thoughts and code-snippets which should help in your study
[Simple Blog with Coffeescript, Express and CoudbDB](http://blog.koostudios.com/?p=398)
[Thoughts on development using CouchDB and Nodejs](http://tbranyen.com/post/thoughts-on-development-using-couchdb-with-nodejs)
[Bind CouchDB and Node.js](http://architects.dzone.com/articles/glue-bind-couchdb-and-nodejs)
[Getting Started with Node.js, Express and CouchDB](http://www.bytemuse.com/2011/06/getting-started-with-node-js-express-and-couchdb/) - this link does not seem to be accessible now, but it seems a temporary issue.
Here's one on testing CouchDB - [Mock testing CouchDB using Node.js](http://writings.nunojob.com/2011/12/Mock-Testing-CouchDB-Using-NodeJS-With-Nock-And-TAP.html)
Hope it helps. |
11,644,382 | >
> **Possible Duplicate:**
>
> [Getting ' bad\_request invalid\_json' error when trying to insert document into CouchDB from Node.js](https://stackoverflow.com/questions/11647656/getting-bad-request-invalid-json-error-when-trying-to-insert-document-into-co)
>
>
>
The highest voted answer on
[CouchDB and Node.js - What module do you recommend?](https://stackoverflow.com/questions/5532209/couchdb-and-node-js-what-module-do-you-recommend)
recommends not to use libraries such as nano or cradle for starting with Node.js and CouchDB.
However I haven't found any tutorial on how to perform standard operations for all DBMSes like create database, create table, add and view data etc. programmatically.
EDIT: (partial answer) after installing and starting CouchDB go to `http://localhost:5984/_utils/script/couch.js`. | 2012/07/25 | [
"https://Stackoverflow.com/questions/11644382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/263485/"
] | You should start by reading the [CouchDB book](http://guide.couchdb.org/editions/1/en/index.html).
No idea why you don't want to use a module: I think you took an answer out of context (an answer that is probably one year old) and made your decision not to use a module.
That is not likely to be helpful to get stuff done. :) You are just repeating work that is done, and issues that have been fixed, etc.
If you want to learn CouchDB, read the book. You can read nano's source as it maps really closely to the API and should be easy to read, but the book is the full way to go.
If by any reason you decide you still want to implement your own module to do what others already do well, go for it :)
If instead you are looking for resources on using nano there are quite a few:
* readme: [github](https://github.com/dscape/nano/blob/master/README.md)
* screencast: [couchdb and nano](http://nodetuts.com/tutorials/30-couchdb-and-nano.html#video)
* article: [nano - a minimalistic couchdb client for nodejs](http://writings.nunojob.com/2011/08/nano-minimalistic-couchdb-client-for-nodejs.html)
* article: [getting started with node.js and couchdb](http://writings.nunojob.com/2011/09/getting-started-with-nodejs-and-couchdb.html)
* article: [document update handler support](http://jackhq.tumblr.com/post/16035106690/nano-v1-2-x-document-update-handler-support-v1-2-x)
* article: [nano 3](http://writings.nunojob.com/2012/05/Nano-3.html)
* article: [securing a site with couchdb cookie authentication using node.js and nano](http://mahoney.eu/2012/05/23/couchdb-cookie-authentication-nodejs-nano/)
* article: [adding copy to nano](http://blog.jlank.com/2012/07/04/adding-copy-to-nano/)
* article: [how to update a document with nano](http://writings.nunojob.com/2012/07/How-To-Update-A-Document-With-Nano-The-CouchDB-Client-for-Node.js.html)
* article: [mock http integration testing in node.js using nock and specify](http://writings.nunojob.com/2012/05/Mock-HTTP-Integration-Testing-in-Node.js-using-Nock-and-Specify.html)
* article: [mock testing couchdb in node.js with nock and tap](http://writings.nunojob.com/2011/12/Mock-Testing-CouchDB-Using-NodeJS-With-Nock-And-TAP.html) | Thanks to [`Ruben Verborgh`](https://stackoverflow.com/questions/11647656/getting-bad-request-invalid-json-error-when-trying-to-insert-document-into-co#answer-11649320), I compiled micro-tutorial from several sources myself.
```
var http = require('http')
var sys = require('sys')
var couchdbPath = 'http://localhost:5984/'
request = require('request')
h = {accept: 'application/json', 'content-type': 'application/json'}
request(
{uri: couchdbPath + '_all_dbs', headers:h},
function(err, response, body) { console.log(sys.inspect(JSON.parse(body))); }
)
// add database
request(
{uri: couchdbPath + 'dbname', method:'PUT', headers:h},
function (err, response, body) {
if (err)
throw err;
if (response.statusCode !== 201)
throw new Error("Could not create database. " + body);
}
)
// Modify existing document
var options = {
host: "localhost",
port: 5984,
path: "/dbname",
headers: {"content-type": "application/json"},
method: "PUT"
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
//console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(JSON.stringify({
"_id":"rabbit",
"_rev":"4-8cee219da7e61616b7ab22c3614b9526",
"Subject":"I like Plankton"
}));
req.end();
```
I used following documentation:
* [`http.request()`](http://nodejs.org/api/http.html#http_http_request_options_callback)
* [CouchDB Complete HTTP API Reference](http://wiki.apache.org/couchdb/Complete_HTTP_API_Reference) |
53,505,794 | I use Hibernate JPA in my application. I have a Table that has a Primary key(Sequence). Service inserts records to that table.
Version: Oracle 12c
Dialect: org.hibernate.dialect.Oracle10gDialect
**Issue :**
We face problem(Unique constraint violation on SEQUENCE Key) during the load testing.
**Questions :**
1. This issue is not occurring all the time. But only during load test. Can someone please check and help to use thread safe generator?
2. Is it DB side sequence definition issue or at Java side?
**DB Sequence :**
```
CREATE SEQUENCE MY_SEQ
START WITH 1
INCREMENT BY 1
NOMINVALUE
NOMAXVALUE
CACHE 30
NOORDER;
CREATE TABLE MY_TABLE (
MY_PRIMARY_KEY INT default MY_SEQ.nextval NOT NULL,
VALUE_COL VARCHAR2(10) NULL
);
```
**Entity :**
```
public class MyTableEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "MY_PRIMARY_KEY")
@GenericGenerator(
name = "mySequenceGenerator",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
@Parameter(name = "sequence_name", value = "SEQUENCE MY_SEQ"),
@Parameter(name = "increment_size", value = "1")
}
)
@GeneratedValue(generator = "mySequenceGenerator")
private long myPrimaryKey;
@Column(name = "VALUE")
private String value;
}
``` | 2018/11/27 | [
"https://Stackoverflow.com/questions/53505794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7360447/"
] | Oracle 10 Dialect
-----------------
For **Oracle10gDialect** use this configuration
```
@Id
@Column(name = "MY_PRIMARY_KEY")
@GeneratedValue(strategy=GenerationType.AUTO)
Long myPrimaryKey;
```
Hibernate creates a table and a sequence:
```
create table MY_TABLE (
MY_PRIMARY_KEY number(19,0) not null,
VALUE varchar2(255 char),
primary key (MY_PRIMARY_KEY))
create sequence hibernate_sequence
```
While storing it first gets the new sequence ID and than passes it in the `INSERT` statement
```
select hibernate_sequence.nextval from dual
insert into MY_TABLE (VALUE, MY_PRIMARY_KEY) values (?, ?)
```
Oracle 12 Dialect
-----------------
If you use **Oracle 12** that natively supports [`IDENTITY column`](https://docs.oracle.com/en/database/oracle/oracle-database/18/sqlrf/CREATE-TABLE.html#GUID-F9CE0CC3-13AE-4744-A43C-EAC7A71AAAB6) it is prefered to upgrade to **Oracle12cDialect** (note that this requires Hibernate 5.3)
Set the `strategy` to `GenerationType.IDENTITY`
```
@Id
@Column(name = "MY_PRIMARY_KEY", updatable = false, nullable = false)
@GeneratedValue(strategy=GenerationType.IDENTITY)
Long myPrimaryKey;
```
The following table is created - the important part is `generated as identity` which provides the unique velues.
Note that no explicite `sequence` is required to be created, it is managed internally .
```
create table MY_TABLE (
MY_PRIMARY_KEY number(19,0) generated as identity,
VALUE varchar2(255 char),
primary key (MY_PRIMARY_KEY))
```
While storing **no ID is passed in the INSERT**, it is assigned by Oracle and returned to the session
```
insert into MY_TABLE (VALUE) values (?) RETURNING MY_PRIMARY_KEY INTO ?
```
Note that in contrary to the Oracle 10 you save one round trip to the database. | Change long to Long
-------------------
Because if you use long, it (by default) is 0. No generator is allowed to change existing values!
<https://docs.oracle.com/javaee/7/api/javax/persistence/GeneratedValue.html> |
392,694 | I'm getting really slow queries in MS SQL Server 2008 R2 on my dev machine. This problem has been plaguing me for about a month. Other developers don't have the same problem, but we all run the same code. It seems to be that any query that includes a `JOIN` takes >20s, some taking up to a minute. Inserts and updates are fast. The total database size is about 30MB, so it's hardly huge.
During the laggy queries, the CPU usage stays flat, the IO rates stay low, and the pagefault delta stays low too. I've not tweaked any performance settings in the db config - it's all stock from the setup.
The software that connects to the SQL server is running on the same machine as it. I've tried multiple dev database copies, and customer databases that are known to be fine, all to no avail.
Any ideas what might be causing this? | 2012/05/25 | [
"https://serverfault.com/questions/392694",
"https://serverfault.com",
"https://serverfault.com/users/100092/"
] | Maybe you have a lot of BLOBs (Binary Large OBJectS) stored in your database. That happens if you store very large binary objects in your db, such as other databases, or perhaps zip packages or whatnot.
That can become a performance killer, and is quite possible if you allow folks to upload files through something like Sharepoint. | Joins can press the envelope on tempdb performance. Generally speaking, tempdb should be the fastest and most optimized database on the server. The reality is often quite different.
Tempdb should be on an ssd, and it should not be configured to auto-grow. Auto-grow can be a huge performance killer. On a production system, tempdb should have one partition/file per processor core. |
43,533,755 | I was recently asked to come up with an Oracle query that returns the USA holidays. After doing some research I couldn't find anything in this regard. Most of the solutions found were for C# or VB. | 2017/04/21 | [
"https://Stackoverflow.com/questions/43533755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4602526/"
] | You can try this query.Its worked for me.
```
CREATE SEQUENCE tablename_colname_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 1 ---> here you can mention startup nummber as you need
CACHE 1;
CREATE TABLE tablename (
colname integer NOT NULL DEFAULT nextval('tablename_colname_seq')
);
``` | Identity Columns
================
There is no currently no way to do this in a `CREATE TABLE` command in PostgreSQL 9.x using the PostgreSQL-specific [serial-type syntax](https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL). However, it's coming in PostgreSQL 10 using the [standardized *Identity Columns* syntax, see my answer on it here](https://dba.stackexchange.com/a/169347/2639)
Here is how it will look
```
CREATE TABLE foo (
id int GENERATED { ALWAYS | BY DEFAULT }
AS IDENTITY [ ( sequence_options ) ]
);
```
Where `(sequence_options)` is `START WITH 1000`, so something like this.
```
CREATE TABLE foo (
foo_id int GENERATED ALWAYS AS IDENTITY (START WITH 1000)
);
``` |
23,617,657 | I am novice in asp.net and am trying to send email via this short code.
```
Public Class sMail
Public emailBody As String
Public emailSubject As String
'Public sendTo As String
Public Function sendMail() As Boolean
Dim eMail As New System.Net.Mail.MailMessage
Dim smtpClient As New System.Net.Mail.SmtpClient("mydomain", 25)
Dim credentials As New System.Net.NetworkCredential("info@mydomain.com", "password")
smtpClient.Credentials = credentials
smtpClient.UseDefaultCredentials = True
smtpClient.DeliveryMethod = Net.Mail.SmtpDeliveryMethod.Network
eMail.From = New System.Net.Mail.MailAddress("info@mydomain.com", "Info")
eMail.To.Add(New Net.Mail.MailAddress("example@outsidedomain.com"))
eMail.Subject = emailSubject
eMail.Body = emailBody
eMail.BodyEncoding = System.Text.Encoding.UTF8
eMail.IsBodyHtml = False
Try
smtpClient.Send(eMail)
Return True
Catch ex As Exception
Return False
End Try
End Function
End Class
```
On sending mails *outside my domain*(gMail,Hotmail etc) I get :
**Mailbox unavailable. The server response was: Authentication is required for relay**
However I have no trouble in sending emails on my own domain.
I have tried several changes but same error. Following does not work
1. changing UseDefaultCredentials;
2. enabling/disabling ssl ;
However when i used same SMTP settings in Outlook I got same error **Server error: '550 Authentication is required for relay'** When sending mails outside my own domain. such as on hotmail, gmail.
But when i changed accounts setting in outlook and ticked : **My outgoing (SMTP) server requires authentication -> Use same settings as incoming mail server**, I was able to send email to any domain.
I cant figure this out, can any one guide me? | 2014/05/12 | [
"https://Stackoverflow.com/questions/23617657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1977361/"
] | Ensure that the defaultCredentials attribute of the network element in your web.config isn't set to "true". [See here](http://msdn.microsoft.com/en-us/library/w355a94k%28v=vs.110%29.aspx) for more details on how to configure mailSettings for use with `System.Net.Mail`. | I figured it out somehow, but still cant explain why this is
Instead of declaring credentials in codebehind i declared **mailsettings** in webconfig
```
<system.net>
<mailSettings>
<smtp from="info@mydomain.com">
<network host="info@mydomain.com" port="25" userName="info@mydomain.com" password="secret" defaultCredentials="false" enableSsl="false" clientDomain="mydomain.com"/>
</smtp>
</mailSettings>
</system.net>
```
Then just used smtp client in code behind **without setting credentials** :
```
Public Class sMail
Public emailBody As String
Public emailSubject As String
Public sendTo As String
Public Function sendMail() As Boolean
Dim eMail As New System.Net.Mail.MailMessage
eMail.Sender = New System.Net.Mail.MailAddress("info@mydomain.com")
eMail.Priority = Net.Mail.MailPriority.High
eMail.From = New System.Net.Mail.MailAddress("info@mydomain.com")
eMail.To.Add(sendTo)
eMail.Subject = emailSubject
eMail.Body = emailBody
eMail.IsBodyHtml = True
eMail.BodyEncoding = Encoding.Default
Dim smtpClient As New System.Net.Mail.SmtpClient()
Try
smtpClient.Send(eMail)
Return True
Catch ex As Exception
Return False
End Try
End Function
End Class
```
This method worked for me,It should also work with credentials declared in code behind instead of in web.config I guess, I am not sure, but didn't work for me |
11,054,830 | The Go language has interface types as features, analogous to C-style interfaces. Go's interface types, though, don't seem to be enforced -- they merely define protocol without actually being applied to a type. As they are not enforced, is it still a good idea to use interfaces? | 2012/06/15 | [
"https://Stackoverflow.com/questions/11054830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200619/"
] | Yes. Go doesn't allow you to build type-hierarchies, so interfaces are very important to allow some polymorphism. Consider the [`sort.Interface`](http://golang.org/pkg/sort/#Interface) defined in the package `sort`:
```
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less returns whether the element with index i should sort
// before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
```
The `sort` package contains a function [`sort(data Interface)`](http://golang.org/pkg/sort/#Sort) that expects any object that implements this interface. Without interfaces, such form of polymorphism would not be possible in go. The fact that you don't have to explicitly annotate that your type implements this interface, is irrelevant.
The cool part about go is that you can even implement this interface on primitive types, as long as the type is defined in the same package. So the following code defines a sortable array of integers:
```
type Sequence []int
// Methods required by sort.Interface.
func (s Sequence) Len() int {
return len(s)
}
func (s Sequence) Less(i, j int) bool {
return s[i] < s[j]
}
func (s Sequence) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
``` | I hope to know what a type check, both statical and at run time is, but I have no idea what is to "enforce an interface". |
11,054,830 | The Go language has interface types as features, analogous to C-style interfaces. Go's interface types, though, don't seem to be enforced -- they merely define protocol without actually being applied to a type. As they are not enforced, is it still a good idea to use interfaces? | 2012/06/15 | [
"https://Stackoverflow.com/questions/11054830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200619/"
] | Yes. Go doesn't allow you to build type-hierarchies, so interfaces are very important to allow some polymorphism. Consider the [`sort.Interface`](http://golang.org/pkg/sort/#Interface) defined in the package `sort`:
```
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less returns whether the element with index i should sort
// before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
```
The `sort` package contains a function [`sort(data Interface)`](http://golang.org/pkg/sort/#Sort) that expects any object that implements this interface. Without interfaces, such form of polymorphism would not be possible in go. The fact that you don't have to explicitly annotate that your type implements this interface, is irrelevant.
The cool part about go is that you can even implement this interface on primitive types, as long as the type is defined in the same package. So the following code defines a sortable array of integers:
```
type Sequence []int
// Methods required by sort.Interface.
func (s Sequence) Len() int {
return len(s)
}
func (s Sequence) Less(i, j int) bool {
return s[i] < s[j]
}
func (s Sequence) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
``` | Yes, it is still an excellent idea to use interfaces. Go emphases interfaces. See <https://talks.golang.org/2014/go4gophers.slide#5>. Extending @ElianEbbing outstanding answer, methods on any types and ad hoc interfaces make for a light-weight OO programming style. See <https://talks.golang.org/2012/goforc.slide#48>.
An example might illustrate this.
```
package main
import . "fmt"
func main() {
c.Cry() // Meow
Cryer.Eat(c) // Fish
}
var c = cat{"Fish"}
type cat struct{ s string }
type Eater interface{ Eat() }
type Cryer interface {
Cry()
Eater
}
func (c cat) Eat() { Println(c.s) }
func (cat) Cry() { Println("Meow") }
```
The `Cryer` interface lets you access both the `Cry()` and `Eat()` methods. See <https://talks.golang.org/2012/zen.slide#16>. You can add `Cryer` to the underlying code without its alteration. See <https://stackoverflow.com/a/11753508/12817546>. And the code works fine if we remove it. You can still access a method directly as shown by `c.Cry()`. This is because Go lets you do two things.
First, you can implement an interface implicitly. An interface is simply a set of methods. See <https://talks.golang.org/2013/go4python.slide#33>. An interface variable can store any non-interface value as long as it implements the interface's methods. See <https://blog.golang.org/laws-of-reflection>.
Values of any type that implement all methods of an interface can be assigned to a variable of that interface. See <https://talks.golang.org/2014/taste.slide#20>.
`c` is a variable of `cat`. `cat` implements the `Eat()` and `Cry()` methods. `Eater` explicitly implements `Eat()`. `Cryer` explicitly implements `Cry()` and `Eat()`. Therefore `cat` implicitly implements the `Eater` and `Cryer` interface. See <https://talks.golang.org/2012/goforc.slide#40>. Thus `c` a variable of `cat` can be a variable of `Eater` and `Cryer`. See <https://golang.org/doc/effective_go.html#blank_implements>.
Second, struct and interface types can be embedded in other struct and interface types. See <https://golang.org/doc/effective_go.html#embedding>. `Cryer.Eat(c)` calls `Eat()` since it embeds `Eater`. Interfaces in Go are thus the primary means for decoupling components of our programs. See <https://www.reddit.com/r/golang/comments/6rwq2g>. And why interfaces can provide a nice API between packages, clients or servers. See <https://stackoverflow.com/a/39100038/12817546>.
If you don’t see a benefit, then don’t add an interface. See the comment in <https://stackoverflow.com/a/39100038/12817546>. There is no explicit hierarchy and thus no need to design one! See <https://talks.golang.org/2012/goforc.slide#46>. Add an interface when you need it. Define your data types first and build your 1-3 method(s) `interface` as you go along. See <https://stackoverflow.com/a/11753508/12817546>. Quotes edited to match example. |
11,054,830 | The Go language has interface types as features, analogous to C-style interfaces. Go's interface types, though, don't seem to be enforced -- they merely define protocol without actually being applied to a type. As they are not enforced, is it still a good idea to use interfaces? | 2012/06/15 | [
"https://Stackoverflow.com/questions/11054830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200619/"
] | Yes, it is still an excellent idea to use interfaces. Go emphases interfaces. See <https://talks.golang.org/2014/go4gophers.slide#5>. Extending @ElianEbbing outstanding answer, methods on any types and ad hoc interfaces make for a light-weight OO programming style. See <https://talks.golang.org/2012/goforc.slide#48>.
An example might illustrate this.
```
package main
import . "fmt"
func main() {
c.Cry() // Meow
Cryer.Eat(c) // Fish
}
var c = cat{"Fish"}
type cat struct{ s string }
type Eater interface{ Eat() }
type Cryer interface {
Cry()
Eater
}
func (c cat) Eat() { Println(c.s) }
func (cat) Cry() { Println("Meow") }
```
The `Cryer` interface lets you access both the `Cry()` and `Eat()` methods. See <https://talks.golang.org/2012/zen.slide#16>. You can add `Cryer` to the underlying code without its alteration. See <https://stackoverflow.com/a/11753508/12817546>. And the code works fine if we remove it. You can still access a method directly as shown by `c.Cry()`. This is because Go lets you do two things.
First, you can implement an interface implicitly. An interface is simply a set of methods. See <https://talks.golang.org/2013/go4python.slide#33>. An interface variable can store any non-interface value as long as it implements the interface's methods. See <https://blog.golang.org/laws-of-reflection>.
Values of any type that implement all methods of an interface can be assigned to a variable of that interface. See <https://talks.golang.org/2014/taste.slide#20>.
`c` is a variable of `cat`. `cat` implements the `Eat()` and `Cry()` methods. `Eater` explicitly implements `Eat()`. `Cryer` explicitly implements `Cry()` and `Eat()`. Therefore `cat` implicitly implements the `Eater` and `Cryer` interface. See <https://talks.golang.org/2012/goforc.slide#40>. Thus `c` a variable of `cat` can be a variable of `Eater` and `Cryer`. See <https://golang.org/doc/effective_go.html#blank_implements>.
Second, struct and interface types can be embedded in other struct and interface types. See <https://golang.org/doc/effective_go.html#embedding>. `Cryer.Eat(c)` calls `Eat()` since it embeds `Eater`. Interfaces in Go are thus the primary means for decoupling components of our programs. See <https://www.reddit.com/r/golang/comments/6rwq2g>. And why interfaces can provide a nice API between packages, clients or servers. See <https://stackoverflow.com/a/39100038/12817546>.
If you don’t see a benefit, then don’t add an interface. See the comment in <https://stackoverflow.com/a/39100038/12817546>. There is no explicit hierarchy and thus no need to design one! See <https://talks.golang.org/2012/goforc.slide#46>. Add an interface when you need it. Define your data types first and build your 1-3 method(s) `interface` as you go along. See <https://stackoverflow.com/a/11753508/12817546>. Quotes edited to match example. | I hope to know what a type check, both statical and at run time is, but I have no idea what is to "enforce an interface". |
47,365,683 | I've linked Google data studio with a MySQL database using the standard connector. Almost everything works fine except for ***date*** and ***datetime*** fields.
I have these 2 fields in phpmyadmin (field name, ***field type***, `output`):
* Validated\_date ***datetime*** `2017-09-27 12:31:04`
* Expiration\_date ***date*** `2017-12-24`
In Data Studio I've set these types, but none of them are recognised:
* Validated\_date ***Date Hour (YYYYMMDDHH)***
* Expiration\_date ***Date (YYYYMMDD)***
I tried to format the field with date\_format in my SELECT:
```
DATE_FORMAT(p.Expiration_date, '%Y%m%d') AS "Expiration Date"
```
I even tried other date\_formats but they're never recognised as dates in Data Studio:
```
DATE_FORMAT(p.Expiration_date, '%Y/%m/%d') AS "Expiration Date"
DATE_FORMAT(p.Expiration_date, '%Y-%m-%d') AS "Expiration Date"
```
Any idea? | 2017/11/18 | [
"https://Stackoverflow.com/questions/47365683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2404798/"
] | I had the same issue. My approach to solve this is to modify the date format within Google Data Studio by creating a new dimension, reformatting the mySQL Datetime into the desired format.
In your example you use DATE\_FORMAT. I wonder if you apply this in Data Studio (which does not know DATE\_FORMAT) or in mySQL?. If you do it in data studio and leave your mySQL/phpmyadmin untouched you can use this:
```
TODATE(your-date-field, 'DEFAULT_DASH', '%Y%m%d')
```
This will take the date format YYYY-MM-DD with optional time in HH:ii:ss and reformat it into YYYYMMDD which works with data studio. | I've never tried directly with Data Studio but when I extract datetime fields from mySQL to use in BigQuery I use:
>
> CONVERT(DATETIME2(0), [DATETIME\_FIELD])
>
>
>
This removed any milliseconds which generally cause problems and convert it to a recognisable datetime format for Google |
47,365,683 | I've linked Google data studio with a MySQL database using the standard connector. Almost everything works fine except for ***date*** and ***datetime*** fields.
I have these 2 fields in phpmyadmin (field name, ***field type***, `output`):
* Validated\_date ***datetime*** `2017-09-27 12:31:04`
* Expiration\_date ***date*** `2017-12-24`
In Data Studio I've set these types, but none of them are recognised:
* Validated\_date ***Date Hour (YYYYMMDDHH)***
* Expiration\_date ***Date (YYYYMMDD)***
I tried to format the field with date\_format in my SELECT:
```
DATE_FORMAT(p.Expiration_date, '%Y%m%d') AS "Expiration Date"
```
I even tried other date\_formats but they're never recognised as dates in Data Studio:
```
DATE_FORMAT(p.Expiration_date, '%Y/%m/%d') AS "Expiration Date"
DATE_FORMAT(p.Expiration_date, '%Y-%m-%d') AS "Expiration Date"
```
Any idea? | 2017/11/18 | [
"https://Stackoverflow.com/questions/47365683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2404798/"
] | I had the same issue. My approach to solve this is to modify the date format within Google Data Studio by creating a new dimension, reformatting the mySQL Datetime into the desired format.
In your example you use DATE\_FORMAT. I wonder if you apply this in Data Studio (which does not know DATE\_FORMAT) or in mySQL?. If you do it in data studio and leave your mySQL/phpmyadmin untouched you can use this:
```
TODATE(your-date-field, 'DEFAULT_DASH', '%Y%m%d')
```
This will take the date format YYYY-MM-DD with optional time in HH:ii:ss and reformat it into YYYYMMDD which works with data studio. | I have used the follow formule and working for me:
```
TODATE(yor-field-from-mysql, '%Y-%m-%dT%H:%M:%S', "%Y%m%d%H%M")
```
Then I choose \*\*\*YYYYMMDDhhmm\*\*\* format in DataStudio. I hope it helps.
***Edit***: In this case, date came from javascript using moment.js |
47,365,683 | I've linked Google data studio with a MySQL database using the standard connector. Almost everything works fine except for ***date*** and ***datetime*** fields.
I have these 2 fields in phpmyadmin (field name, ***field type***, `output`):
* Validated\_date ***datetime*** `2017-09-27 12:31:04`
* Expiration\_date ***date*** `2017-12-24`
In Data Studio I've set these types, but none of them are recognised:
* Validated\_date ***Date Hour (YYYYMMDDHH)***
* Expiration\_date ***Date (YYYYMMDD)***
I tried to format the field with date\_format in my SELECT:
```
DATE_FORMAT(p.Expiration_date, '%Y%m%d') AS "Expiration Date"
```
I even tried other date\_formats but they're never recognised as dates in Data Studio:
```
DATE_FORMAT(p.Expiration_date, '%Y/%m/%d') AS "Expiration Date"
DATE_FORMAT(p.Expiration_date, '%Y-%m-%d') AS "Expiration Date"
```
Any idea? | 2017/11/18 | [
"https://Stackoverflow.com/questions/47365683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2404798/"
] | I had the same issue. My approach to solve this is to modify the date format within Google Data Studio by creating a new dimension, reformatting the mySQL Datetime into the desired format.
In your example you use DATE\_FORMAT. I wonder if you apply this in Data Studio (which does not know DATE\_FORMAT) or in mySQL?. If you do it in data studio and leave your mySQL/phpmyadmin untouched you can use this:
```
TODATE(your-date-field, 'DEFAULT_DASH', '%Y%m%d')
```
This will take the date format YYYY-MM-DD with optional time in HH:ii:ss and reformat it into YYYYMMDD which works with data studio. | I had the same issue. For me, the only solution was create a formula this way:
```
CONCAT(SUBSTR(field, 1, 4), SUBSTR(field, 6, 2), SUBSTR(field, 9, 2))
```
and use this as AAAAMMDD format |
61,284,939 | I'm developing an android application using java and Firebase. This is my code for creating a user profile and store the data in firebase database.
```
package com.eNotification.getnotify;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.eNotification.getnotify.utils.Utils;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import com.google.firebase.storage.UploadTask;
import com.mikhaellopez.circularimageview.CircularImageView;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.util.ArrayList;
import java.util.List;
public class MainActivityCreateProfile extends AppCompatActivity {
private static final int STORAGE_PERMISSION_CODE=1;
private TextInputLayout dUsername,dRegNo;
private TextInputEditText dEditUsername,dEditRegNo;
private CircularImageView dProfileImage;
private Spinner dCourse;
private TextView selected;
private Button dDoneBtn;
private String uid,email;
private String select="Select course",maxid,s;
private Uri selectedImage=null,uri;
private FirebaseDatabase firebaseDatabase;
private DatabaseReference databaseReference;
private StorageReference storageReference;
private FirebaseStorage firebaseStorage;
private StorageTask mUploadTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_profile);
firebaseDatabase = FirebaseDatabase.getInstance();
firebaseStorage = FirebaseStorage.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference().child("USERS");
storageReference = firebaseStorage.getReference("Profile images");
uid = getIntent().getStringExtra("uid");
email = getIntent().getStringExtra("email");
dProfileImage = findViewById(R.id.dProfileImg);
dUsername = findViewById(R.id.dUsername);
dRegNo = findViewById(R.id.dRegNo);
dEditUsername = findViewById(R.id.dEditUsername);
dEditRegNo = findViewById(R.id.dEditReg);
selected = findViewById(R.id.course);
dCourse = findViewById(R.id.dCourse);
List<String> categories = new ArrayList<>();
categories.add(0,"Select course");
categories.add("BCA");
categories.add("BBA");
categories.add("BCOM");
categories.add("BA");
ArrayAdapter<String> dataAdapter;
dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dCourse.setAdapter(dataAdapter);
dCourse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// if (parent.getItemAtPosition(position).equals("Select course")){
// Toast.makeText(MainActivityCreateProfile.this, "Select the course", Toast.LENGTH_SHORT).show();
//} else {
selected.setText(parent.getSelectedItem().toString());
//}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivityCreateProfile.this, "Select a course", Toast.LENGTH_SHORT).show();
}
});
dDoneBtn = findViewById(R.id.dDoneBtn);
dDoneBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
inputValidation();
}
});
dProfileImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivityCreateProfile.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivityCreateProfile.this, "You have already granted permission", Toast.LENGTH_SHORT).show();
SelectImage();
} else {
requestStoragePermission();
}
}
});
}
private void requestStoragePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivityCreateProfile.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(this)
.setTitle("Permission needed")
.setMessage("This Permission is needed for uploading the Image")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivityCreateProfile.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
SelectImage();
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
}
public void SelectImage() {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
selectedImage = result.getUri();
Picasso.get().load(selectedImage).into(dProfileImage);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void inputValidation() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
//Username validation
if (!Utils.inputValidation(dEditUsername)) {
Toast.makeText(this, "Enter the username", Toast.LENGTH_SHORT).show();
return;
} else if (!Utils.usernameVerify(dEditUsername)) {
Toast.makeText(this, "A Username should not exceed 15 characters", Toast.LENGTH_SHORT).show();
return;
} else {
dUsername.setErrorEnabled(false);
}
//Reg no Validation
if (!Utils.inputValidation(dEditRegNo)) {
Toast.makeText(this, "Enter the Register No", Toast.LENGTH_SHORT).show();
return;
} else if (!Utils.regNoVerify(dEditRegNo)) {
Toast.makeText(this, "Enter correct Register No", Toast.LENGTH_SHORT).show();
return;
}
createProfile();
}else {
Toast.makeText(this, "Check internet connection", Toast.LENGTH_SHORT).show();
}
}
public String GetFileExtension(Uri uri) {
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)) ;
}
private void createProfile(){
final String username = dEditUsername.getText().toString();
final String regNo = dEditRegNo.getText().toString();
final String course = dCourse.getSelectedItem().toString();
maxid = databaseReference.push().getKey();
if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(regNo))) {
if (!course.equals(select)) {
databaseReference.orderByChild("regNo").equalTo(regNo).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(MainActivityCreateProfile.this, "Reg no. exist", Toast.LENGTH_SHORT).show();
} else {
s = "https://firebasestorage.googleapis.com/v0/b/getnotify-da5c1.appspot.com/o/Permanent%2Fuser.png?alt=media&token=017d9013-ede2-49c7-b53b-6e96d90e3398";
UserDetails userDetails = new UserDetails(s, username, regNo, course, email);
databaseReference.child(maxid).setValue(userDetails);
Toast.makeText(MainActivityCreateProfile.this, "Upload Successful", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(MainActivityCreateProfile.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "Select a course", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Enter username and Register No.", Toast.LENGTH_SHORT).show();
}
}
}
```
I'm facing a problem where i want to check whether the Register No. already exist in the database or not
and this is code to check that.
```
databaseReference.orderByChild("regNo").equalTo(regNo).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(MainActivityCreateProfile.this, "Reg no. exist", Toast.LENGTH_SHORT).show();
} else {
s = "https://firebasestorage.googleapis.com/v0/b/getnotify-da5c1.appspot.com/o/Permanent%2Fuser.png?alt=media&token=017d9013-ede2-49c7-b53b-6e96d90e3398";
UserDetails userDetails = new UserDetails(s, username, regNo, course, email);
databaseReference.child(maxid).setValue(userDetails);
Toast.makeText(MainActivityCreateProfile.this, "Upload Successful", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(MainActivityCreateProfile.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
```
The code works correctly. It detects if the value exist in database and shows Toast message Reg No. exist. If the value does not exist it successfully creates the child in database but it also displays Toast message Reg No. exist instead of Upload successful. I'm new to these concept so if you know anything please help.
[Database node](https://i.stack.imgur.com/Szoyt.png) | 2020/04/18 | [
"https://Stackoverflow.com/questions/61284939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12775226/"
] | As per Hussain Answer. `addValueEventListener()` is called each time there is changes in Your Database to overcome this situation you can call `addListenerForSingleValueEvent()`. Which will called once.
Other than that there is no Get option in Realtime Database
```
databaseReference.orderByChild("regNo").equalTo(regNo)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//Do what you want to try
}else{
//Create New Node in Database
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
``` | Here is what might be going wrong with the code. You are trying to check if the `regno` exist with `addValueEventListener` on user `databaseReference`.
From Android Documentation `addValueEventListener` does this
>
> Add a listener for changes in the data at this location. Each time time the data changes, your listener will be called with an immutable snapshot of the data.
>
>
>
Therefore, when the `dataSnapshot` does not exists it creates a new node and eventually `addValueEventListener` fires again and your toast prints ***Reg no. exist***.
What you can do is
```
databaseReference
.child(regNo)
.addListenerForSingleValueEvent(new ValueEventListenerAdapter() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
// Document exists
} else {
// Do something
}
}
});
``` |
2,873,678 | I am working on an Eclipse plugin that modifies Java code in a user's project.
Basically the result of this plugin is that Java annotations are added to some methods, so
```
void foo() { ... }
```
becomes
```
@MyAnnotation
void foo() { ... }
```
Except that it doesn't quite look like that; the indentation on the newly inserted annotation is wack (specifically, the new annotation is all the way to the left-hand side of the line). I'd like to make all my changes to the file, and then programmatically call "Correct Indentation."
Does anyone know how to do this? I can't find the answer here or in the JDT forums, and all the classes that look relevant (IndentAction, JavaIndenter) are in internal packages which I'm not supposed to use...
Thanks! | 2010/05/20 | [
"https://Stackoverflow.com/questions/2873678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/250096/"
] | Well I think I may have figured out the solution I want. Guess I should have spend more time searching before asking... but for future reference, here's what I did! The good stuff was in the ToolFactory...
```
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.jdt.core.ICompilationUnit;
...
ICompilationUnit cu = ...
...
CodeFormatter formatter = ToolFactory.createCodeFormatter(null);
ISourceRange range = cu.getSourceRange();
TextEdit indent_edit =
formatter.format(CodeFormatter.K_COMPILATION_UNIT,
cu.getSource(), range.getOffset(), range.getLength(), 0, null);
cu.applyTextEdit(indent_edit, null);
cu.reconcile();
```
This reformats the entire file. There are other options if you need to reformat less... | It's probably easier to add the indentation as you process the Java code.
Your Eclipse plugin had to read the `void foo() { ... }` line to know to add the `@MyAnnotation`, right? Just get the indentation from the Java line, and append your annotation to the indentation. |
71,853,039 | In short, how do I get this:
[![enter image description here](https://i.stack.imgur.com/JBBws.jpg)](https://i.stack.imgur.com/JBBws.jpg)
From this:
```py
def fiblike(ls, n):
store = []
for i in range(n):
a = ls.pop(0)
ls.append(sum(ls)+a)
store.append(a)
return store
```
With all the indentation guide and code highlighting.
I have written hundreds of Python scripts and I need to convert all of them to images...
I have seen this:
```py
import Image
import ImageDraw
import ImageFont
def getSize(txt, font):
testImg = Image.new('RGB', (1, 1))
testDraw = ImageDraw.Draw(testImg)
return testDraw.textsize(txt, font)
if __name__ == '__main__':
fontname = "Arial.ttf"
fontsize = 11
text = "example@gmail.com"
colorText = "black"
colorOutline = "red"
colorBackground = "white"
font = ImageFont.truetype(fontname, fontsize)
width, height = getSize(text, font)
img = Image.new('RGB', (width+4, height+4), colorBackground)
d = ImageDraw.Draw(img)
d.text((2, height/2), text, fill=colorText, font=font)
d.rectangle((0, 0, width+3, height+3), outline=colorOutline)
img.save("D:/image.png")
```
from [here](https://www.codegrepper.com/code-examples/python/how+to+convert+text+file+to+image+in+python)
But it does not do code highlighting and I want either a `numpy` or `cv2` based solution.
How can I do it? | 2022/04/13 | [
"https://Stackoverflow.com/questions/71853039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | * Getting pair token balance of contracts
>
> web3.eth.contract(address=token\_address,abi=abi).functions.balanceOf(contract\_address).call()
>
>
>
* and then get current price of each token / USDT by calling function slot0 in pool tokenA/USDT & tokenB/USDT
>
> slot0 = contract.functions.slot0().call()
>
>
>
>
> sqrtPriceCurrent = slot0[0] / (1 << 96)
>
>
>
>
> priceCurrent = sqrtPriceCurrent \*\* 2
>
>
>
>
> decimal\_diff = USDT\_decimal - TOKEN\_A\_decimal
>
>
>
>
> token\_price = 10\*\*(-decimal\_diff)/( priceCurrent) if token0\_address == USDT\_address else priceCurrent/(10\*\*decimal\_diff)
>
>
>
* Finally, TVL = sum(token\_balance \* token\_price)
\*\* Remember: check price from big pool | No offense but you are following a hard way, which needs to use `TickBitmap` to get the next initialized tick (Remember not all ticks are initialized unless necessary.)
Alternatively the easy way to get a pool's TVL is to query Uniswap V3's [subgraph](https://thegraph.com/hosted-service/subgraph/ianlapham/uniswap-v3-subgraph?selected=playground): like
```
{
pool(id: "0x4e68ccd3e89f51c3074ca5072bbac773960dfa36") {
id
token0 {symbol}
totalValueLockedToken0
token1 {symbol}
totalValueLockedToken1
}
}
```
(for some reason it doesn't show result if you put checksum address)
or
```
{
pools(first: 5) {
id
token0 {symbol}
totalValueLockedToken0
token1 {symbol}
totalValueLockedToken1
}
}
``` |
23,785,383 | i have an android trivia app. some players get errors when they click on "new game".
for me it works fine, and for it works fine also for most of the players.
the problem is most of the times at galaxy devices, but there are same devices with the same version that everything works right for them.
here is the error
```
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sportrivia.hapoelbeershevatrivia/com.dimikit.trivia.SingleplayerActivity}: android.database.sqlite.SQLiteException: no such column: BannerAdImageURL (code 1): , while compiling: SELECT _id, RemoteServer, ChatServer, CommonBackground, SyncFrequencyDays, NumberOfLevels, BackgroundMusic, BannerAdImageURL, BannerAdLinkURL FROM settings
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2092)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
at android.app.ActivityThread.access$700(ActivityThread.java:134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4867)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: no such column: BannerAdImageURL (code 1): , while compiling: SELECT _id, RemoteServer, ChatServer, CommonBackground, SyncFrequencyDays, NumberOfLevels, BackgroundMusic, BannerAdImageURL, BannerAdLinkURL FROM settings
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1013)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:624)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
at com.dimikit.trivia.utilities.settings.SettingsDataSource.getAllSettings(SettingsDataSource.java:99)
at com.dimikit.trivia.SingleplayerActivity.initializeAllData(SingleplayerActivity.java:322)
at com.dimikit.trivia.SingleplayerActivity.onCreate(SingleplayerActivity.java:218)
at android.app.Activity.performCreate(Activity.java:5047)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056)
... 11 more
```
do you have any idea what is the problem?
thanks | 2014/05/21 | [
"https://Stackoverflow.com/questions/23785383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2392915/"
] | There are a few things wrong with this.
The header doesn't need to float left for one. It looks fine. If anything add a display block. When using floats, only move items to the left/right that need to be beside another element.
```
#header {
float: left; // Remove This
height: 25px;
width: 100%;
background: #FF6633;
}
```
Since #leftcolumn floats to the left and is on the left in your design. #contentliquid should float to the right, since this is a left/right column base. I say this because in your html, #left column came after #contentliquid. When writing html, anything that you should see first, comes first. You write the html in order of what is meant to be displayed.
```
<div id="contentliquid">
<div id="content">
<p>CONTENT</p>
</div>
</div>
<div id="leftcolumn"> // This element should come before #contentliquid
<p>MENU</p>
</div>
```
You have #contentliquid taking up 100% width, meaning it takes up the entire screen. This is wrong. The two elements combined should equal 100% since 120% doesn't exist except for off-screen. That means #leftcolumn should be 20% and the #contentliquid should be 80%. (or whatever percentages you see fit.
```
#contentliquid {
float: left;
width: 100%; //bad : see below
}
<--------------------------------No Room For Anything Else----------------------->
<-----20----><------------------------------80----------------------------------->
```
The #leftcolumn does not need a negative margin-left. It fits comfortably where it is after adding the fixes i've mentioned.
Finally. To have a div stay the same height, but scroll with content. Set the desired height upon it, but set the overflow to auto/scroll. Either is fine. It will scroll if the content on the page is more than the room provided for it.
```
#contentliquid {
float: right;
width: 80%;
height: 200px;
overflow: auto;
}
```
Last but not least, My (updated) JSFiddle: <http://jsfiddle.net/Az2ws/2/> | You could `fixed` the elements and use `percents` and `overflow` properties.
```
<!DOCTYPE html>
<head>
</head>
<style>
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
p {
padding: 10px;
}
#wrapper {
width: 100%;
min-width: 1000px;
max-width: 2000px;
margin: 0 auto;
overflow:hidden;
}
#header {
position:fixed;
z-index:1;
top:0;
height: 25px;
width: 100%;
background: #FF6633;
}
#contentliquid {
position:absolute;
top:25px;
left:20%;
width: 80%;
z-index:0;
padding-bottom: 40px;
}
#content {
background: #FFFFFF;
overflow:hidden;
}
#leftcolumn {
background: #CC33FF;
width: 20%;
height: 100%;
position: fixed;
padding-top: 25px;
box-sizing: border-box;
padding-bottom: 40px;
z-index: 0;
}
#footer {
position: fixed;
bottom: 0;
height: 40px;
width: 100%;
background: #33FF66;
clear: both;
z-index:1;
}
</style>
<body>
<div id="wrapper">
<div id="header">
<p>HEADER</p>
</div>
<div id="contentliquid">
<div id="content">
<p>CONTENT</p>
<p>CONTENT</p>
<p>CONTENT</p>
<p>CONTENT</p>
<p>CONTENT</p>
<p>CONTENT</p>
<p>CONTENT</p>
<p>CONTENT</p>
<p>CONTENT</p>
<p>CONTENT</p>
<p>CONTENT</p>
<p>CONTENT</p>
<p>CONTENT</p>
<p>CONTENT</p>
</div>
</div>
<div id="leftcolumn">
<p>MENU</p>
</div>
<div id="footer">
<p>FOOTER</p>
</div>
</div>
</body>
</html>
```
[You could see this working here](http://jsfiddle.net/NEOLPAR/Dnpg7/1/) |
113,441 | We're currently working on a medium/large PHP/MySQL project. We're doing unit testing with PHPUnit & QUnit and we have two full time testers that are manually testing the application. Our test (mock) data is currently created with SQL scripts.
We have problem with maintaining scripts for test data. The business logic is pretty complex and one "simple" change in the test data often produces several bugs in the application (which are not real bugs, just the product of invalid data). This has become big burden to the whole team because we are constantly creating and changing tables.
I don't really see the point of maintaining the test data in the scripts because everything can be manually added in the application in about 5 minutes with the UI. Our PM disagrees and says that having project that we can’t deploy with test data is a bad practice.
Should we abandon maintenance of the scripts with test data and just let the testers to test the application without data? What’s the best practice? | 2011/10/10 | [
"https://softwareengineering.stackexchange.com/questions/113441",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/8093/"
] | You are mixing two different concepts. One is **verification**, which is based on Unit Testing and Peer Reviews. This can be done by the developers themselves, without test data and its intent is to verify that a set of requirements are met.
The second one is **validation**, and this is done by QA (your testers). For this step you do need test data since the tester do not need to have any knowledge of the programming in the application, only its intended use cases. Its objective is to validate that the application behaves as intended in a production environment.
Both processes are important and necessary to deliver a quality product to the customer. You can't rely on unit tests alone. What you need to figure out is a reliable way to handle your test data to ensure its valid.
**EDIT:** OK, I get what you are asking. The answer is yes, because the Tester's job is not to generate the test data, just to test the application. You need to build your scripts in a way that allows easier maintenance and ensures valid data is inserted. Without the test data, tester will have nothing to test. Having said that, however, **if you have access to the testing environment**, I don't see why you can't you insert the test data manually rather than by using scripts. | This is a very common problem and very difficult one as well. Automated tests that run against a databse (even an in-memory database, such as [HSQLDB](http://hsqldb.org/)) are usually slow, non-deterministic and, since a test failure only indicates that there is a problem *somewhere* in your code or in you data, they are not much informative.
In my experience, the best strategy is to focus on unit tests for business logic. Try to cover as much as possible of your core domain code. If you get this part right, which is itself quite a challenge, you will be achieving the best cost-benefit relationship for automated tests. As for the persistence layer, I normally invest much less effort on automated tests and leave it to dedicated manual testers.
But if you really want (or need) to automate persistence tests, I would recommend you to read [*Growing Object-Oriented Software, Guided by Tests*](http://rads.stackoverflow.com/amzn/click/0321503627). This book has a whole chapter dedicated to persistence tests. |
113,441 | We're currently working on a medium/large PHP/MySQL project. We're doing unit testing with PHPUnit & QUnit and we have two full time testers that are manually testing the application. Our test (mock) data is currently created with SQL scripts.
We have problem with maintaining scripts for test data. The business logic is pretty complex and one "simple" change in the test data often produces several bugs in the application (which are not real bugs, just the product of invalid data). This has become big burden to the whole team because we are constantly creating and changing tables.
I don't really see the point of maintaining the test data in the scripts because everything can be manually added in the application in about 5 minutes with the UI. Our PM disagrees and says that having project that we can’t deploy with test data is a bad practice.
Should we abandon maintenance of the scripts with test data and just let the testers to test the application without data? What’s the best practice? | 2011/10/10 | [
"https://softwareengineering.stackexchange.com/questions/113441",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/8093/"
] | Yes, having unit tests and data mock-ups is a best practice. The project manager is correct. Since performing a "simple" change in the test data often produces bugs, then that is the core of the problem.
The code needs improvement. Not doing so (saying hey we don't need tests) is not a fix, that is simply adding [technical debt](http://martinfowler.com/bliki/TechnicalDebt.html). Break the code down into smaller more test-able units because being unable to identify units without breakage is a problem.
Start doing a refactor. Keep the improvements small so they are manageable. Look for anti-patterns like God classes/methods, not following DRY, single-responsibility, etc...
Finally, look into [TDD](http://en.wikipedia.org/wiki/Test-driven_development) to see if it works for the team. TDD works well for ensuring all your code is test-able (because you write the tests first) and also ensuring you stay [lean](http://en.wikipedia.org/wiki/Lean_manufacturing) by writing just enough code to pass the tests (minimize over engineering).
In general, if a series of complex business logic processes produce a set of data, then I view this as a report. Encapsulate the report. Run the report and use the resultant object as input to the next test. | This is a very common problem and very difficult one as well. Automated tests that run against a databse (even an in-memory database, such as [HSQLDB](http://hsqldb.org/)) are usually slow, non-deterministic and, since a test failure only indicates that there is a problem *somewhere* in your code or in you data, they are not much informative.
In my experience, the best strategy is to focus on unit tests for business logic. Try to cover as much as possible of your core domain code. If you get this part right, which is itself quite a challenge, you will be achieving the best cost-benefit relationship for automated tests. As for the persistence layer, I normally invest much less effort on automated tests and leave it to dedicated manual testers.
But if you really want (or need) to automate persistence tests, I would recommend you to read [*Growing Object-Oriented Software, Guided by Tests*](http://rads.stackoverflow.com/amzn/click/0321503627). This book has a whole chapter dedicated to persistence tests. |
71,281,408 | I'm trying to use firebase with Micropython. It doesn't matter how many times I do this
`print(firebase.get(URL))`. If I use `firebase.put(URL, datas)` or `firebase.patch(URL, datas)` then it successfully posts that data, but if I try to read the data `print(firebase.get(URL))` then this error pops up.
Firebase library: <https://github.com/vishal-android-freak/firebase-micropython-esp32>
Code:
```
import network
import ufirebase as firebase
from time import sleep
URL = 'https://xxxxxxxxxxxxxxxx.firebaseio.com/'
wlan = network.WLAN(network.STA_IF)
if not wlan.active() or not wlan.isconnected():
wlan.active(True)
print('connecting to: xxxx')
wlan.connect('xxxx', 'xxxxxxxxx')
while not wlan.isconnected():
pass
print('network config:', wlan.ifconfig())
datas = {'Shape': {'hos': 'fse', 'xxe': 'ter'}, 'Wps': 'Wps'}
firebase.put(URL, datas)
sleep(5)
print(firebase.get(URL))
```
Error:
```
Traceback (most recent call last):
File "main.py", line 21, in <module>
File "ufirebase.py", line 124, in get
File "urequests.py", line 116, in get
File "urequests.py", line 62, in request
OSError: [Errno 12] ENOMEM
MicroPython v1.18 on 2022-01-17; 4MB/OTA module with ESP32
Type "help()" for more information.
``` | 2022/02/27 | [
"https://Stackoverflow.com/questions/71281408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16169605/"
] | got it problem is with urequests library, if you can switchback to usocket and close the socket before timeout then works fine. For urequests you need to have a board with spiram. For non-spiram based borads here is a good firebase library based on sockets [micropython-firebase-realtime-database](https://github.com/ckoever/micropython-firebase-realtime-database) | You're calling `firebase.get(URL)` and getting an out of memory error.
This call returns the entire contents of the database. Apparently this is more than the amount of RAM available to MicroPython (which isn't a lot). `ENOMEM` means "no memory" - Python has run out of memory.
You need to change the call to request just what you're trying to fetch. In this case you might try
```
print(firebase.get(URL + 'Shape'))
print(firebase.get(URL + 'Was'))
```
You can refer to [the library's documentation](https://github.com/vishal-android-freak/firebase-micropython-esp32) to see how to better use the `get()` method. |
23,668,416 | I am trying to add JQuery functionality to my Rails application; however, it is not working. I am using JQuery draggable to move images around the screen. I have it working in a stand alone html file but I'm having a lot of difficulty adding it to my Rails application. This is the stand alone file:
```
<!DOCTYPE html>
<html>
<head>
<title>City</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="js/jquery-ui-1.10.4/themes/base/jquery-ui.css">
<script type="text/javascript" src="js/jquery-ui-1.10.4/jquery-1.10.2.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.4/ui/jquery-ui.js"></script>
<style type="text/css">
h1, h3
{
text-align: center;
margin: 0px;
}
/* style the list to maximize the droppable hitarea */
#canvas
{
width: 600px;
height: 600px;
border: 1px solid black;
margin: 0px auto;
overflow: hidden;
}
/*#canvas ol { margin: 0; padding: 1em 0 1em 3em; }*/
/*li { list-style: none;}*/
.canvas-area
{
width: 600px;
height: 600px;
}
/* map background */
/* img {
position: relative;
left: 50%;
top: 50%;
}*/
/* draggable icons */
.draggable
{
background: transparent url('images/transparent.png') repeat center top;
width: 40px;
height: 40px;
padding: 5px;
float: left;
margin: 0 10px 10px 0;
font-size: .9em;
border: hidden;
/*position: absolute;*/
}
#draggable
{
width: 40px;
height: 40px;
}
div img
{
margin: 0px auto;
position: relative;
top: 0px;
left: 0px;
width: 40px;
height: 40px;
}
.arrow img
{
width: 200px;
height: 200px;
}
.arrow
{
width: 200px;
height: 200px;
border: 1px solid black;
}
.commercial100 img
{
width: 100px;
height: 100px;
}
.commercial100
{
width: 100px;
height: 100px;
}
#building img
{
height: 150px;
}
</style>
<script>
// jquery ui script for snapping to grid
$(function() {
$( ".draggable" ).draggable({ grid: [10,10] });
$( "#draggable4" ).draggable({ grid: [ 20, 20 ], snap: true });
});
</script>
</head>
<body>
<div class="content">
<!-- Canvas for building the city -->
<h1>Mock view of my city</h1>
<h3>600 x 600</h3>
<div id="canvas">
<div id="ignoreThis" class="ui-widget-content canvas-area">
<p class="placeholder">Add your items here</p>
<div id="arrowSvg" class="draggable ui-widget-content arrow">
<img src="images/arrow.svg" alt="house" type="image/svg+xml" /> SVG (200px x 200px)
</div>
<div id="arrowPng" class="draggable ui-widget-content arrow">
<img src="images/arrow.png" alt="house"> PNG (200px x 200px)
</div>
<div id="building" class="draggable ui-widget-content commercial100">
<img src="images/building.png" alt="building" />
</div>
<div id="factory" class="draggable ui-widget-content commercial100" >
<img src="images/factory.png" alt="factory" />
</div>
<div id="ferry" class="draggable ui-widget-content commercial100" >
<img src="images/ferry.png" alt="ferry" />
</div>
<div id="house2l" class="draggable ui-widget-content" >
<img src="images/house2l.png" alt="two level house" />
</div>
<div id="houseSvg" class="draggable ui-widget-content">
<img src="images/house.svg" alt="house" type="image/svg+xml" /> SVG
</div>
<div id="housePng" class="draggable ui-widget-content">
<img src="images/house.png" alt="house" />
</div>
<div id="houseSF" class="draggable ui-widget-content" >
<img src="images/housesf.png" alt="SF house" />
</div>
<div id="street1" class="draggable ui-widget-content street" >
<img src="images/street.png" alt="street">
</div>
<div id="street2" class="draggable ui-widget-content street" >
<img src="images/street.png" alt="street">
</div>
<div id="street3" class="draggable ui-widget-content street" >
<img src="images/street.png" alt="street">
</div>
<div id="street4" class="draggable ui-widget-content street" >
<img src="images/street.png" alt="street">
</div>
</div>
<script>
// code to make the active div move to the front
// code from http://www.codingforums.com/javascript-programming/260289-bring-div-element-front-click.html
// create an array to hold the (buildings, streets, landmarks) element's id
var ids=[],
// grab all the divs (each icon) and put it into thedivs
thedivs = document.getElementById("canvas").getElementsByTagName("div");
for (var i = 0; i < thedivs.length; i++) {
// add the id of each div to the ids array
//alert(thedivs[i].id);
ids.push(thedivs[i].id);
thedivs[i].onclick = function() {
for (var a = 0; a < ids.length; a++) {
if (this.id == ids[a]) {
// take current id that matches the selected id and move it to the end
ids.push(ids.splice(a,1));
}
document.getElementById(ids[a]).style.zIndex=a;
}
}
}
</script>
</div>
<input type="button" value="save" onclick="saveAction()">
<script>
//Cycle through images and grab their x/y positions
var saveAction = function(){
elementNames = document.getElementById("canvas").getElementsByTagName("div");
for(var i = 0; i < elementNames.length; i++)
{
var idName = $( "#" + elementNames[i].id);
var offset = idName.offset();
alert("Left pos: " + offset.left + " Top pos: " + offset.top);
}
};
</script>
</div>
</body>
</html>
```
I have placed the Javascript in assets/javascripts/custom\_map.js and I have placed the html / css in my new\_map.html.erb view. The images are showing up fine in the Rails app but they are not draggable. How can I fix this? Thanks! | 2014/05/15 | [
"https://Stackoverflow.com/questions/23668416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2827885/"
] | Perhaps your load order is incorrect or your assets path is wrong. Try linking your script as the last thing on your page and wrap everything in it inside a jquery ready function:
```
$(function() {
// all your scripts here
});
```
Also try viewing your source and making sure that your .js file is serving correctly
It should be /assets/yourjs.js rather than /assets/javascripts/yourjs.js
Also, I think you may be able to use the jquery ui stack function to make items settle on top (not sure, you might want to try it):
```
$( ".draggable" ).draggable({ stack: ".draggable" });
``` | Without knowing the specific errors you're receiving, I can only detail why you're having a problem, and how to resolve it generally:
---
[**Unobtrusive**](https://stackoverflow.com/questions/8392374/difference-between-obtrusive-and-unobtrusive-javascript)
You should never put javascript in your HTML code (known as inline JS). Problems being that it's messy & can be easily tampered with... hence making it relatively insecure, and generally seen as amateurish
A better way is to use `unobtrusive` JS (where the JS is stored in files loaded outside the scope of HTML). Rails uses the [`asset pipeline`](http://edgeguides.rubyonrails.org/asset_pipeline.html) for this:
```
#app/assets/javascripts/application.js
var ready = function() { // -> you said JQuery :)
$( ".draggable" ).draggable({ grid: [10,10] });
$( "#draggable4" ).draggable({ grid: [ 20, 20 ], snap: true });
/////////////////////////////////
var ids=[],
// grab all the divs (each icon) and put it into thedivs
thedivs = document.getElementById("canvas").getElementsByTagName("div");
for (var i = 0; i < thedivs.length; i++) {
// add the id of each div to the ids array
//alert(thedivs[i].id);
ids.push(thedivs[i].id);
thedivs[i].onclick = function() {
for (var a = 0; a < ids.length; a++) {
if (this.id == ids[a]) {
// take current id that matches the selected id and move it to the end
ids.push(ids.splice(a,1));
}
document.getElementById(ids[a]).style.zIndex=a;
}
}
}
};
$(document).on("page:load ready", ready);
```
If you migrate your JS from your `views` and put into your `asset` files, you'll be in a much better position to give us feedback, which we can then use to help fix your problem further |
51,975,313 | I am just starting to use docker and I wanted to pull the latest MongoDB image from docker hub.
So, from the command line I used:
```
docker pull mongo
```
this is what I found here (<https://hub.docker.com/_/mongo/>)
Now, this comes back with:
```
Using default tag: latest
latest: Pulling from library/mongo
no matching manifest for unknown in the manifest list entries
```
I also tried something like:
```
docker pull python:3.6
```
and this works.
I am on Mac OSX (High Sierra 10.13.6). I am not sure what I am doing wrong. | 2018/08/22 | [
"https://Stackoverflow.com/questions/51975313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2713740/"
] | >
> My obvious expectation was that I could do something like Stringified (or something).
>
>
>
You'll need to create your own `Stringified` and `PrasedErrorProperty` along with `function parseError(error:string): Stringified<ParsedErrorProperty>`.
This is not provided natively. | You can use an index signature to type a stringified object.
```js
type Stringified<T> = {
[P in keyof T]: string
};
interface Obj {
value: number
}
const test : Stringified<Obj> = {
value: "string"
}
``` |
30,268,311 | I have a svg image that contains a circle group and a text group. The circle group consists of multiple dots. This Circle group should rotate around its circle center, but it keeps rotating around the svg's top left corner. To solve this issue I have searched everywhere, but I was not able to change the rotation center of that circle without placing the circle group at a totally wrong position.
So my question is: How can I define the rotation center of a svg image group without changing the groups position?
This is the code I'm using: <https://jsfiddle.net/1pe2c837/1/>
```css
svg {
width: 50%;
}
/* Rotate around the circle center */
#Circleelement {
-webkit-animation-name: rotate;
-webkit-animation-duration: 2s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
-moz-animation-name: rotate;
-moz-animation-duration: 2s;
-moz-animation-iteration-count: infinite;
-moz-animation-timing-function: linear;
animation-name: rotate;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
@-webkit-keyframes rotate {
from {-webkit-transform: rotate(0deg);}
to {-webkit-transform: rotate(360deg);}
}
@-moz-keyframes rotate {
from {-moz-transform: rotate(0deg);}
to {-moz-transform: rotate(360deg);}
}
@keyframes rotate {
from {transform: rotate(0deg);}
to {transform: rotate(360deg);}
}
/* _x31_ */
#_x31_, #_x32_7, #_x33_1, #_x31_3 {
-webkit-animation: flickerAnimation 3s infinite;
-moz-animation: flickerAnimation 3s infinite;
-o-animation: flickerAnimation 3s infinite;
animation: flickerAnimation 3s infinite;
animation-delay: 0s;
-webkit-animation-delay: 0s;
-moz-animation-delay: 0s;
-o-animation-delay: 0s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x32_ */
#_x32_, #_x32_8, #_x32_3, #_x31_0 {
animation: flickerAnimation 9s infinite;
-webkit-animation: flickerAnimation 9s infinite;
-moz-animation: flickerAnimation 9s infinite;
-o-animation: flickerAnimation 9s infinite;
animation-delay: 0.5s;
-webkit-animation-delay: 0.5s;
-moz-animation-delay: 0.5s;
-o-animation-delay: 0.5s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x3_ */
#_x33_, #_x33_2, #_x32_5, #_x31_7 {
-webkit-animation: flickerAnimation 13s infinite;
-moz-animation: flickerAnimation 13s infinite;
-o-animation: flickerAnimation 13s infinite;
animation: flickerAnimation 13s infinite;
animation-delay: 0.75s;
-webkit-animation-delay: 0.75s;
-moz-animation-delay: 0.75s;
-o-animation-delay: 0.75s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x34_ */
#_x34_, #_x32_4, #_x33_6, #_x33_5, #_x31_5 {
-webkit-animation: flickerAnimation 23s infinite;
-moz-animation: flickerAnimation 23s infinite;
-o-animation: flickerAnimation 23s infinite;
animation: flickerAnimation 23s infinite;
animation-delay: 0s;
-webkit-animation-delay: 0s;
-moz-animation-delay: 0s;
-o-animation-delay: 0s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x35_ */
#_x35_, #_x32_2, #_x33_0, #_x31_9 {
-webkit-animation: flickerAnimation 15s infinite;
-moz-animation: flickerAnimation 15s infinite;
-o-animation: flickerAnimation 15s infinite;
animation: flickerAnimation 15s infinite;
animation-delay: 1s;
-webkit-animation-delay: 1s;
-moz-animation-delay: 1s;
-o-animation-delay: 1s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x36_ */
#_x36_, #_x32_0, #_x32_9, #_x31_1 {
-webkit-animation: flickerAnimation 18s infinite;
-moz-animation: flickerAnimation 18s infinite;
-o-animation: flickerAnimation 18s infinite;
animation: flickerAnimation 18s infinite;
animation-delay: 1.5s;
-webkit-animation-delay: 1.5s;
-moz-animation-delay: 1.5s;
-o-animation-delay: 1.5s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x37_ */
#_x37_, #_x33_4, #_x31_2 {
-webkit-animation: flickerAnimation 6s infinite;
-moz-animation: flickerAnimation 6s infinite;
-o-animation: flickerAnimation 6s infinite;
animation: flickerAnimation 6s infinite;
animation-delay: 0.5s;
-webkit-animation-delay: 0.5s;
-moz-animation-delay: 0.5s;
-o-animation-delay: 0.5s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x38_ */
#_x38_, #_x32_6, #_x31_6 {
-webkit-animation: flickerAnimation 10s infinite;
-moz-animation: flickerAnimation 10s infinite;
-o-animation: flickerAnimation 10s infinite;
animation: flickerAnimation 10s infinite;
animation-delay: 0.2s;
-webkit-animation-delay: 0.2s;
-moz-animation-delay: 0.2s;
-o-animation-delay: 0.2s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x39_ */
#_x39_, #_x33_3, #_x31_4 {
-webkit-animation: flickerAnimation 25s infinite;
-moz-animation: flickerAnimation 25s infinite;
-o-animation: flickerAnimation 25s infinite;
animation: flickerAnimation 25s infinite;
animation-delay: 0.8s;
-webkit-animation-delay: 0.8s;
-moz-animation-delay: 0.8s;
-o-animation-delay: 0.8s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x31_0 */
#_x31_0, #_x32_1, #_x31_8 {
-webkit-animation: flickerAnimation 30s infinite;
-moz-animation: flickerAnimation 30s infinite;
-o-animation: flickerAnimation 30s infinite;
animation: flickerAnimation 30s infinite;
animation-delay: 2s;
-webkit-animation-delay: 2s;
-moz-animation-delay: 2s;
-o-animation-delay: 2s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
```
```html
<body>
<svg version="1.1" id="Logo" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 500 500" enable-background="new 0 0 500 500" xml:space="preserve">
<g id="Circleelement" transform="translate(150 170) rotate(45) translate(-150 -170)">
<circle id="_x31_" fill="#000000" stroke-miterlimit="10" cx="242.5" cy="81.5" r="11.1"> </circle>
<circle id="_x32_" fill="#000000" stroke-miterlimit="10" cx="277.1" cy="87" r="10.8"/>
<circle id="_x33_" fill="#000000" stroke-miterlimit="10" cx="307.5" cy="102" r="10.5"/>
<circle id="_x34_" fill="#000000" stroke-miterlimit="10" cx="332.1" cy="124.9" r="10.2"/>
<circle id="_x35_" fill="#000000" stroke-miterlimit="10" cx="349.1" cy="154.2" r="9.9"/>
<circle id="_x36_" fill="#000000" stroke-miterlimit="10" cx="357" cy="188.1" r="9.6"/>
<circle id="_x37_" fill="#000000" stroke-miterlimit="10" cx="354.3" cy="223.4" r="9.4"/>
<circle id="_x38_" fill="#000000" stroke-miterlimit="10" cx="341.7" cy="255.1" r="9.1"/>
<circle id="_x39_" fill="#000000" stroke-miterlimit="10" cx="320.7" cy="281.4" r="8.8"/>
<circle id="_x31_0" fill="#000000" stroke-miterlimit="10" cx="293.1" cy="300.6" r="8.5"/>
<circle id="_x31_1" fill="#000000" stroke-miterlimit="10" cx="260.3" cy="311.1" r="8.2"/>
<circle id="_x31_2" fill="#000000" stroke-miterlimit="10" cx="224.7" cy="311.3" r="7.9"/>
<circle id="_x31_3" fill="#000000" stroke-miterlimit="10" cx="191.8" cy="301.2" r="7.6"/>
<circle id="_x31_4" fill="#000000" stroke-miterlimit="10" cx="164" cy="282.3" r="7.3"/>
<circle id="_x31_5" fill="#000000" stroke-miterlimit="10" cx="142.7" cy="256.3" r="7"/>
<circle id="_x31_6" fill="#000000" stroke-miterlimit="10" cx="129.7" cy="224.7" r="6.8"/>
<circle id="_x31_7" fill="#000000" stroke-miterlimit="10" cx="126.6" cy="189.4" r="6.5"/>
<circle id="_x31_8" fill="#000000" stroke-miterlimit="10" cx="134" cy="155.5" r="6.2"/>
<circle id="_x31_9" fill="#000000" stroke-miterlimit="10" cx="150.7" cy="126.1" r="5.9"/>
<circle id="_x32_0" fill="#000000" stroke-miterlimit="10" cx="174.9" cy="102.9" r="5.6"/>
<circle id="_x32_1" fill="#000000" stroke-miterlimit="10" cx="205.2" cy="87.5" r="5.3"/>
<circle id="_x32_2" fill="#000000" stroke-miterlimit="10" cx="242.6" cy="123.6" r="10.4"/>
<circle id="_x32_3" fill="#000000" stroke-miterlimit="10" cx="282.5" cy="136.5" r="9.7"/>
<circle id="_x32_4" fill="#000000" stroke-miterlimit="10" cx="308.8" cy="168" r="9.1"/>
<circle id="_x32_5" fill="#000000" stroke-miterlimit="10" cx="314" cy="210.3" r="8.4"/>
<circle id="_x32_6" fill="#000000" stroke-miterlimit="10" cx="261.1" cy="269.4" r="7.1"/>
<circle id="_x32_7" fill="#000000" stroke-miterlimit="10" cx="218.3" cy="268.8" r="6.5"/>
<circle id="_x32_8" fill="#000000" stroke-miterlimit="10" cx="184.1" cy="246.1" r="5.8"/>
<circle id="_x32_9" fill="#000000" stroke-miterlimit="10" cx="167.1" cy="208.3" r="5.2"/>
<circle id="_x33_0" fill="#000000" stroke-miterlimit="10" cx="200.5" cy="135.4" r="3.9"/>
<circle id="_x33_1" fill="#000000" stroke-miterlimit="10" cx="242.2" cy="164.1" r="5.4"/>
<circle id="_x33_2" fill="#000000" stroke-miterlimit="10" cx="271.9" cy="181.8" r="4.8"/>
<circle id="_x33_3" fill="#000000" stroke-miterlimit="10" cx="271.5" cy="216.9" r="4.1"/>
<circle id="_x33_4" fill="#000000" stroke-miterlimit="10" cx="241.3" cy="233.9" r="3.5"/>
<circle id="_x33_5" fill="#000000" stroke-miterlimit="10" cx="211.4" cy="216.5" r="2.8"/>
<circle id="_x33_6" fill="#000000" stroke-miterlimit="10" cx="211.4" cy="181.4" r="2.2"/>
</g>
<g id="Name">
<text transform="matrix(1 0 0 1 44 439.7)" font-family="'Gotham-Book'" font-size="54">S O M E T E X T</text>
</g>
</svg>
</body>
``` | 2015/05/15 | [
"https://Stackoverflow.com/questions/30268311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4905300/"
] | You can also work around any browser problems with `transform-origin` by using nested groups.
```
<g transform="translate(243.35 194.85)">
<g id="Circleelement">
<g transform="translate(-243.35 -194.85)">
```
That way the CSS rotation is working on a group that it thinks is centred on the origin. So the element stays in place.
```css
svg {
width: 50%;
}
/* Rotate around the circle center */
#Circleelement {
-webkit-animation-name: rotate;
-webkit-animation-duration: 2s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
-moz-animation-name: rotate;
-moz-animation-duration: 2s;
-moz-animation-iteration-count: infinite;
-moz-animation-timing-function: linear;
animation-name: rotate;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
@-webkit-keyframes rotate {
from {-webkit-transform: rotate(0deg);}
to {-webkit-transform: rotate(360deg);}
}
@-moz-keyframes rotate {
from {-moz-transform: rotate(0deg);}
to {-moz-transform: rotate(360deg);}
}
@keyframes rotate {
from {transform: rotate(0deg);}
to {transform: rotate(360deg);}
}
/* _x31_ */
#_x31_, #_x32_7, #_x33_1, #_x31_3 {
-webkit-animation: flickerAnimation 3s infinite;
-moz-animation: flickerAnimation 3s infinite;
-o-animation: flickerAnimation 3s infinite;
animation: flickerAnimation 3s infinite;
animation-delay: 0s;
-webkit-animation-delay: 0s;
-moz-animation-delay: 0s;
-o-animation-delay: 0s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x32_ */
#_x32_, #_x32_8, #_x32_3, #_x31_0 {
animation: flickerAnimation 9s infinite;
-webkit-animation: flickerAnimation 9s infinite;
-moz-animation: flickerAnimation 9s infinite;
-o-animation: flickerAnimation 9s infinite;
animation-delay: 0.5s;
-webkit-animation-delay: 0.5s;
-moz-animation-delay: 0.5s;
-o-animation-delay: 0.5s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x3_ */
#_x33_, #_x33_2, #_x32_5, #_x31_7 {
-webkit-animation: flickerAnimation 13s infinite;
-moz-animation: flickerAnimation 13s infinite;
-o-animation: flickerAnimation 13s infinite;
animation: flickerAnimation 13s infinite;
animation-delay: 0.75s;
-webkit-animation-delay: 0.75s;
-moz-animation-delay: 0.75s;
-o-animation-delay: 0.75s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x34_ */
#_x34_, #_x32_4, #_x33_6, #_x33_5, #_x31_5 {
-webkit-animation: flickerAnimation 23s infinite;
-moz-animation: flickerAnimation 23s infinite;
-o-animation: flickerAnimation 23s infinite;
animation: flickerAnimation 23s infinite;
animation-delay: 0s;
-webkit-animation-delay: 0s;
-moz-animation-delay: 0s;
-o-animation-delay: 0s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x35_ */
#_x35_, #_x32_2, #_x33_0, #_x31_9 {
-webkit-animation: flickerAnimation 15s infinite;
-moz-animation: flickerAnimation 15s infinite;
-o-animation: flickerAnimation 15s infinite;
animation: flickerAnimation 15s infinite;
animation-delay: 1s;
-webkit-animation-delay: 1s;
-moz-animation-delay: 1s;
-o-animation-delay: 1s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x36_ */
#_x36_, #_x32_0, #_x32_9, #_x31_1 {
-webkit-animation: flickerAnimation 18s infinite;
-moz-animation: flickerAnimation 18s infinite;
-o-animation: flickerAnimation 18s infinite;
animation: flickerAnimation 18s infinite;
animation-delay: 1.5s;
-webkit-animation-delay: 1.5s;
-moz-animation-delay: 1.5s;
-o-animation-delay: 1.5s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x37_ */
#_x37_, #_x33_4, #_x31_2 {
-webkit-animation: flickerAnimation 6s infinite;
-moz-animation: flickerAnimation 6s infinite;
-o-animation: flickerAnimation 6s infinite;
animation: flickerAnimation 6s infinite;
animation-delay: 0.5s;
-webkit-animation-delay: 0.5s;
-moz-animation-delay: 0.5s;
-o-animation-delay: 0.5s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x38_ */
#_x38_, #_x32_6, #_x31_6 {
-webkit-animation: flickerAnimation 10s infinite;
-moz-animation: flickerAnimation 10s infinite;
-o-animation: flickerAnimation 10s infinite;
animation: flickerAnimation 10s infinite;
animation-delay: 0.2s;
-webkit-animation-delay: 0.2s;
-moz-animation-delay: 0.2s;
-o-animation-delay: 0.2s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x39_ */
#_x39_, #_x33_3, #_x31_4 {
-webkit-animation: flickerAnimation 25s infinite;
-moz-animation: flickerAnimation 25s infinite;
-o-animation: flickerAnimation 25s infinite;
animation: flickerAnimation 25s infinite;
animation-delay: 0.8s;
-webkit-animation-delay: 0.8s;
-moz-animation-delay: 0.8s;
-o-animation-delay: 0.8s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x31_0 */
#_x31_0, #_x32_1, #_x31_8 {
-webkit-animation: flickerAnimation 30s infinite;
-moz-animation: flickerAnimation 30s infinite;
-o-animation: flickerAnimation 30s infinite;
animation: flickerAnimation 30s infinite;
animation-delay: 2s;
-webkit-animation-delay: 2s;
-moz-animation-delay: 2s;
-o-animation-delay: 2s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
```
```html
<body>
<svg version="1.1" id="Logo" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 500 500" enable-background="new 0 0 500 500" xml:space="preserve">
<g transform="translate(243.35 194.85)">
<g id="Circleelement">
<g transform="translate(-243.35 -194.85)">
<circle id="_x31_" fill="#000000" stroke-miterlimit="10" cx="242.5" cy="81.5" r="11.1"> </circle>
<circle id="_x32_" fill="#000000" stroke-miterlimit="10" cx="277.1" cy="87" r="10.8"/>
<circle id="_x33_" fill="#000000" stroke-miterlimit="10" cx="307.5" cy="102" r="10.5"/>
<circle id="_x34_" fill="#000000" stroke-miterlimit="10" cx="332.1" cy="124.9" r="10.2"/>
<circle id="_x35_" fill="#000000" stroke-miterlimit="10" cx="349.1" cy="154.2" r="9.9"/>
<circle id="_x36_" fill="#000000" stroke-miterlimit="10" cx="357" cy="188.1" r="9.6"/>
<circle id="_x37_" fill="#000000" stroke-miterlimit="10" cx="354.3" cy="223.4" r="9.4"/>
<circle id="_x38_" fill="#000000" stroke-miterlimit="10" cx="341.7" cy="255.1" r="9.1"/>
<circle id="_x39_" fill="#000000" stroke-miterlimit="10" cx="320.7" cy="281.4" r="8.8"/>
<circle id="_x31_0" fill="#000000" stroke-miterlimit="10" cx="293.1" cy="300.6" r="8.5"/>
<circle id="_x31_1" fill="#000000" stroke-miterlimit="10" cx="260.3" cy="311.1" r="8.2"/>
<circle id="_x31_2" fill="#000000" stroke-miterlimit="10" cx="224.7" cy="311.3" r="7.9"/>
<circle id="_x31_3" fill="#000000" stroke-miterlimit="10" cx="191.8" cy="301.2" r="7.6"/>
<circle id="_x31_4" fill="#000000" stroke-miterlimit="10" cx="164" cy="282.3" r="7.3"/>
<circle id="_x31_5" fill="#000000" stroke-miterlimit="10" cx="142.7" cy="256.3" r="7"/>
<circle id="_x31_6" fill="#000000" stroke-miterlimit="10" cx="129.7" cy="224.7" r="6.8"/>
<circle id="_x31_7" fill="#000000" stroke-miterlimit="10" cx="126.6" cy="189.4" r="6.5"/>
<circle id="_x31_8" fill="#000000" stroke-miterlimit="10" cx="134" cy="155.5" r="6.2"/>
<circle id="_x31_9" fill="#000000" stroke-miterlimit="10" cx="150.7" cy="126.1" r="5.9"/>
<circle id="_x32_0" fill="#000000" stroke-miterlimit="10" cx="174.9" cy="102.9" r="5.6"/>
<circle id="_x32_1" fill="#000000" stroke-miterlimit="10" cx="205.2" cy="87.5" r="5.3"/>
<circle id="_x32_2" fill="#000000" stroke-miterlimit="10" cx="242.6" cy="123.6" r="10.4"/>
<circle id="_x32_3" fill="#000000" stroke-miterlimit="10" cx="282.5" cy="136.5" r="9.7"/>
<circle id="_x32_4" fill="#000000" stroke-miterlimit="10" cx="308.8" cy="168" r="9.1"/>
<circle id="_x32_5" fill="#000000" stroke-miterlimit="10" cx="314" cy="210.3" r="8.4"/>
<circle id="_x32_6" fill="#000000" stroke-miterlimit="10" cx="261.1" cy="269.4" r="7.1"/>
<circle id="_x32_7" fill="#000000" stroke-miterlimit="10" cx="218.3" cy="268.8" r="6.5"/>
<circle id="_x32_8" fill="#000000" stroke-miterlimit="10" cx="184.1" cy="246.1" r="5.8"/>
<circle id="_x32_9" fill="#000000" stroke-miterlimit="10" cx="167.1" cy="208.3" r="5.2"/>
<circle id="_x33_0" fill="#000000" stroke-miterlimit="10" cx="200.5" cy="135.4" r="3.9"/>
<circle id="_x33_1" fill="#000000" stroke-miterlimit="10" cx="242.2" cy="164.1" r="5.4"/>
<circle id="_x33_2" fill="#000000" stroke-miterlimit="10" cx="271.9" cy="181.8" r="4.8"/>
<circle id="_x33_3" fill="#000000" stroke-miterlimit="10" cx="271.5" cy="216.9" r="4.1"/>
<circle id="_x33_4" fill="#000000" stroke-miterlimit="10" cx="241.3" cy="233.9" r="3.5"/>
<circle id="_x33_5" fill="#000000" stroke-miterlimit="10" cx="211.4" cy="216.5" r="2.8"/>
<circle id="_x33_6" fill="#000000" stroke-miterlimit="10" cx="211.4" cy="181.4" r="2.2"/>
</g>
</g>
</g>
<g id="Name">
<text transform="matrix(1 0 0 1 44 439.7)" font-family="'Gotham-Book'" font-size="54">S O M E T E X T</text>
</g>
</svg>
</body>
``` | You need to set a `transform-origin`
```
#Circleelement {
transform-origin:center;
}
```
[**Jsfiddle Demo**](https://jsfiddle.net/1pe2c837/3/)
[**CSS-Tricks Article**](https://css-tricks.com/svg-animation-on-css-transforms/)
**Note: The 'origin' base point for SVG can be different between browsers. The above example works in Chrome but may not in FF. There are a number of questions in SO relating to this point.** |
30,268,311 | I have a svg image that contains a circle group and a text group. The circle group consists of multiple dots. This Circle group should rotate around its circle center, but it keeps rotating around the svg's top left corner. To solve this issue I have searched everywhere, but I was not able to change the rotation center of that circle without placing the circle group at a totally wrong position.
So my question is: How can I define the rotation center of a svg image group without changing the groups position?
This is the code I'm using: <https://jsfiddle.net/1pe2c837/1/>
```css
svg {
width: 50%;
}
/* Rotate around the circle center */
#Circleelement {
-webkit-animation-name: rotate;
-webkit-animation-duration: 2s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
-moz-animation-name: rotate;
-moz-animation-duration: 2s;
-moz-animation-iteration-count: infinite;
-moz-animation-timing-function: linear;
animation-name: rotate;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
@-webkit-keyframes rotate {
from {-webkit-transform: rotate(0deg);}
to {-webkit-transform: rotate(360deg);}
}
@-moz-keyframes rotate {
from {-moz-transform: rotate(0deg);}
to {-moz-transform: rotate(360deg);}
}
@keyframes rotate {
from {transform: rotate(0deg);}
to {transform: rotate(360deg);}
}
/* _x31_ */
#_x31_, #_x32_7, #_x33_1, #_x31_3 {
-webkit-animation: flickerAnimation 3s infinite;
-moz-animation: flickerAnimation 3s infinite;
-o-animation: flickerAnimation 3s infinite;
animation: flickerAnimation 3s infinite;
animation-delay: 0s;
-webkit-animation-delay: 0s;
-moz-animation-delay: 0s;
-o-animation-delay: 0s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x32_ */
#_x32_, #_x32_8, #_x32_3, #_x31_0 {
animation: flickerAnimation 9s infinite;
-webkit-animation: flickerAnimation 9s infinite;
-moz-animation: flickerAnimation 9s infinite;
-o-animation: flickerAnimation 9s infinite;
animation-delay: 0.5s;
-webkit-animation-delay: 0.5s;
-moz-animation-delay: 0.5s;
-o-animation-delay: 0.5s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x3_ */
#_x33_, #_x33_2, #_x32_5, #_x31_7 {
-webkit-animation: flickerAnimation 13s infinite;
-moz-animation: flickerAnimation 13s infinite;
-o-animation: flickerAnimation 13s infinite;
animation: flickerAnimation 13s infinite;
animation-delay: 0.75s;
-webkit-animation-delay: 0.75s;
-moz-animation-delay: 0.75s;
-o-animation-delay: 0.75s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x34_ */
#_x34_, #_x32_4, #_x33_6, #_x33_5, #_x31_5 {
-webkit-animation: flickerAnimation 23s infinite;
-moz-animation: flickerAnimation 23s infinite;
-o-animation: flickerAnimation 23s infinite;
animation: flickerAnimation 23s infinite;
animation-delay: 0s;
-webkit-animation-delay: 0s;
-moz-animation-delay: 0s;
-o-animation-delay: 0s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x35_ */
#_x35_, #_x32_2, #_x33_0, #_x31_9 {
-webkit-animation: flickerAnimation 15s infinite;
-moz-animation: flickerAnimation 15s infinite;
-o-animation: flickerAnimation 15s infinite;
animation: flickerAnimation 15s infinite;
animation-delay: 1s;
-webkit-animation-delay: 1s;
-moz-animation-delay: 1s;
-o-animation-delay: 1s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x36_ */
#_x36_, #_x32_0, #_x32_9, #_x31_1 {
-webkit-animation: flickerAnimation 18s infinite;
-moz-animation: flickerAnimation 18s infinite;
-o-animation: flickerAnimation 18s infinite;
animation: flickerAnimation 18s infinite;
animation-delay: 1.5s;
-webkit-animation-delay: 1.5s;
-moz-animation-delay: 1.5s;
-o-animation-delay: 1.5s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x37_ */
#_x37_, #_x33_4, #_x31_2 {
-webkit-animation: flickerAnimation 6s infinite;
-moz-animation: flickerAnimation 6s infinite;
-o-animation: flickerAnimation 6s infinite;
animation: flickerAnimation 6s infinite;
animation-delay: 0.5s;
-webkit-animation-delay: 0.5s;
-moz-animation-delay: 0.5s;
-o-animation-delay: 0.5s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x38_ */
#_x38_, #_x32_6, #_x31_6 {
-webkit-animation: flickerAnimation 10s infinite;
-moz-animation: flickerAnimation 10s infinite;
-o-animation: flickerAnimation 10s infinite;
animation: flickerAnimation 10s infinite;
animation-delay: 0.2s;
-webkit-animation-delay: 0.2s;
-moz-animation-delay: 0.2s;
-o-animation-delay: 0.2s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x39_ */
#_x39_, #_x33_3, #_x31_4 {
-webkit-animation: flickerAnimation 25s infinite;
-moz-animation: flickerAnimation 25s infinite;
-o-animation: flickerAnimation 25s infinite;
animation: flickerAnimation 25s infinite;
animation-delay: 0.8s;
-webkit-animation-delay: 0.8s;
-moz-animation-delay: 0.8s;
-o-animation-delay: 0.8s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x31_0 */
#_x31_0, #_x32_1, #_x31_8 {
-webkit-animation: flickerAnimation 30s infinite;
-moz-animation: flickerAnimation 30s infinite;
-o-animation: flickerAnimation 30s infinite;
animation: flickerAnimation 30s infinite;
animation-delay: 2s;
-webkit-animation-delay: 2s;
-moz-animation-delay: 2s;
-o-animation-delay: 2s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
```
```html
<body>
<svg version="1.1" id="Logo" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 500 500" enable-background="new 0 0 500 500" xml:space="preserve">
<g id="Circleelement" transform="translate(150 170) rotate(45) translate(-150 -170)">
<circle id="_x31_" fill="#000000" stroke-miterlimit="10" cx="242.5" cy="81.5" r="11.1"> </circle>
<circle id="_x32_" fill="#000000" stroke-miterlimit="10" cx="277.1" cy="87" r="10.8"/>
<circle id="_x33_" fill="#000000" stroke-miterlimit="10" cx="307.5" cy="102" r="10.5"/>
<circle id="_x34_" fill="#000000" stroke-miterlimit="10" cx="332.1" cy="124.9" r="10.2"/>
<circle id="_x35_" fill="#000000" stroke-miterlimit="10" cx="349.1" cy="154.2" r="9.9"/>
<circle id="_x36_" fill="#000000" stroke-miterlimit="10" cx="357" cy="188.1" r="9.6"/>
<circle id="_x37_" fill="#000000" stroke-miterlimit="10" cx="354.3" cy="223.4" r="9.4"/>
<circle id="_x38_" fill="#000000" stroke-miterlimit="10" cx="341.7" cy="255.1" r="9.1"/>
<circle id="_x39_" fill="#000000" stroke-miterlimit="10" cx="320.7" cy="281.4" r="8.8"/>
<circle id="_x31_0" fill="#000000" stroke-miterlimit="10" cx="293.1" cy="300.6" r="8.5"/>
<circle id="_x31_1" fill="#000000" stroke-miterlimit="10" cx="260.3" cy="311.1" r="8.2"/>
<circle id="_x31_2" fill="#000000" stroke-miterlimit="10" cx="224.7" cy="311.3" r="7.9"/>
<circle id="_x31_3" fill="#000000" stroke-miterlimit="10" cx="191.8" cy="301.2" r="7.6"/>
<circle id="_x31_4" fill="#000000" stroke-miterlimit="10" cx="164" cy="282.3" r="7.3"/>
<circle id="_x31_5" fill="#000000" stroke-miterlimit="10" cx="142.7" cy="256.3" r="7"/>
<circle id="_x31_6" fill="#000000" stroke-miterlimit="10" cx="129.7" cy="224.7" r="6.8"/>
<circle id="_x31_7" fill="#000000" stroke-miterlimit="10" cx="126.6" cy="189.4" r="6.5"/>
<circle id="_x31_8" fill="#000000" stroke-miterlimit="10" cx="134" cy="155.5" r="6.2"/>
<circle id="_x31_9" fill="#000000" stroke-miterlimit="10" cx="150.7" cy="126.1" r="5.9"/>
<circle id="_x32_0" fill="#000000" stroke-miterlimit="10" cx="174.9" cy="102.9" r="5.6"/>
<circle id="_x32_1" fill="#000000" stroke-miterlimit="10" cx="205.2" cy="87.5" r="5.3"/>
<circle id="_x32_2" fill="#000000" stroke-miterlimit="10" cx="242.6" cy="123.6" r="10.4"/>
<circle id="_x32_3" fill="#000000" stroke-miterlimit="10" cx="282.5" cy="136.5" r="9.7"/>
<circle id="_x32_4" fill="#000000" stroke-miterlimit="10" cx="308.8" cy="168" r="9.1"/>
<circle id="_x32_5" fill="#000000" stroke-miterlimit="10" cx="314" cy="210.3" r="8.4"/>
<circle id="_x32_6" fill="#000000" stroke-miterlimit="10" cx="261.1" cy="269.4" r="7.1"/>
<circle id="_x32_7" fill="#000000" stroke-miterlimit="10" cx="218.3" cy="268.8" r="6.5"/>
<circle id="_x32_8" fill="#000000" stroke-miterlimit="10" cx="184.1" cy="246.1" r="5.8"/>
<circle id="_x32_9" fill="#000000" stroke-miterlimit="10" cx="167.1" cy="208.3" r="5.2"/>
<circle id="_x33_0" fill="#000000" stroke-miterlimit="10" cx="200.5" cy="135.4" r="3.9"/>
<circle id="_x33_1" fill="#000000" stroke-miterlimit="10" cx="242.2" cy="164.1" r="5.4"/>
<circle id="_x33_2" fill="#000000" stroke-miterlimit="10" cx="271.9" cy="181.8" r="4.8"/>
<circle id="_x33_3" fill="#000000" stroke-miterlimit="10" cx="271.5" cy="216.9" r="4.1"/>
<circle id="_x33_4" fill="#000000" stroke-miterlimit="10" cx="241.3" cy="233.9" r="3.5"/>
<circle id="_x33_5" fill="#000000" stroke-miterlimit="10" cx="211.4" cy="216.5" r="2.8"/>
<circle id="_x33_6" fill="#000000" stroke-miterlimit="10" cx="211.4" cy="181.4" r="2.2"/>
</g>
<g id="Name">
<text transform="matrix(1 0 0 1 44 439.7)" font-family="'Gotham-Book'" font-size="54">S O M E T E X T</text>
</g>
</svg>
</body>
``` | 2015/05/15 | [
"https://Stackoverflow.com/questions/30268311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4905300/"
] | You can also work around any browser problems with `transform-origin` by using nested groups.
```
<g transform="translate(243.35 194.85)">
<g id="Circleelement">
<g transform="translate(-243.35 -194.85)">
```
That way the CSS rotation is working on a group that it thinks is centred on the origin. So the element stays in place.
```css
svg {
width: 50%;
}
/* Rotate around the circle center */
#Circleelement {
-webkit-animation-name: rotate;
-webkit-animation-duration: 2s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
-moz-animation-name: rotate;
-moz-animation-duration: 2s;
-moz-animation-iteration-count: infinite;
-moz-animation-timing-function: linear;
animation-name: rotate;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
@-webkit-keyframes rotate {
from {-webkit-transform: rotate(0deg);}
to {-webkit-transform: rotate(360deg);}
}
@-moz-keyframes rotate {
from {-moz-transform: rotate(0deg);}
to {-moz-transform: rotate(360deg);}
}
@keyframes rotate {
from {transform: rotate(0deg);}
to {transform: rotate(360deg);}
}
/* _x31_ */
#_x31_, #_x32_7, #_x33_1, #_x31_3 {
-webkit-animation: flickerAnimation 3s infinite;
-moz-animation: flickerAnimation 3s infinite;
-o-animation: flickerAnimation 3s infinite;
animation: flickerAnimation 3s infinite;
animation-delay: 0s;
-webkit-animation-delay: 0s;
-moz-animation-delay: 0s;
-o-animation-delay: 0s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x32_ */
#_x32_, #_x32_8, #_x32_3, #_x31_0 {
animation: flickerAnimation 9s infinite;
-webkit-animation: flickerAnimation 9s infinite;
-moz-animation: flickerAnimation 9s infinite;
-o-animation: flickerAnimation 9s infinite;
animation-delay: 0.5s;
-webkit-animation-delay: 0.5s;
-moz-animation-delay: 0.5s;
-o-animation-delay: 0.5s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x3_ */
#_x33_, #_x33_2, #_x32_5, #_x31_7 {
-webkit-animation: flickerAnimation 13s infinite;
-moz-animation: flickerAnimation 13s infinite;
-o-animation: flickerAnimation 13s infinite;
animation: flickerAnimation 13s infinite;
animation-delay: 0.75s;
-webkit-animation-delay: 0.75s;
-moz-animation-delay: 0.75s;
-o-animation-delay: 0.75s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x34_ */
#_x34_, #_x32_4, #_x33_6, #_x33_5, #_x31_5 {
-webkit-animation: flickerAnimation 23s infinite;
-moz-animation: flickerAnimation 23s infinite;
-o-animation: flickerAnimation 23s infinite;
animation: flickerAnimation 23s infinite;
animation-delay: 0s;
-webkit-animation-delay: 0s;
-moz-animation-delay: 0s;
-o-animation-delay: 0s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x35_ */
#_x35_, #_x32_2, #_x33_0, #_x31_9 {
-webkit-animation: flickerAnimation 15s infinite;
-moz-animation: flickerAnimation 15s infinite;
-o-animation: flickerAnimation 15s infinite;
animation: flickerAnimation 15s infinite;
animation-delay: 1s;
-webkit-animation-delay: 1s;
-moz-animation-delay: 1s;
-o-animation-delay: 1s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x36_ */
#_x36_, #_x32_0, #_x32_9, #_x31_1 {
-webkit-animation: flickerAnimation 18s infinite;
-moz-animation: flickerAnimation 18s infinite;
-o-animation: flickerAnimation 18s infinite;
animation: flickerAnimation 18s infinite;
animation-delay: 1.5s;
-webkit-animation-delay: 1.5s;
-moz-animation-delay: 1.5s;
-o-animation-delay: 1.5s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x37_ */
#_x37_, #_x33_4, #_x31_2 {
-webkit-animation: flickerAnimation 6s infinite;
-moz-animation: flickerAnimation 6s infinite;
-o-animation: flickerAnimation 6s infinite;
animation: flickerAnimation 6s infinite;
animation-delay: 0.5s;
-webkit-animation-delay: 0.5s;
-moz-animation-delay: 0.5s;
-o-animation-delay: 0.5s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x38_ */
#_x38_, #_x32_6, #_x31_6 {
-webkit-animation: flickerAnimation 10s infinite;
-moz-animation: flickerAnimation 10s infinite;
-o-animation: flickerAnimation 10s infinite;
animation: flickerAnimation 10s infinite;
animation-delay: 0.2s;
-webkit-animation-delay: 0.2s;
-moz-animation-delay: 0.2s;
-o-animation-delay: 0.2s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x39_ */
#_x39_, #_x33_3, #_x31_4 {
-webkit-animation: flickerAnimation 25s infinite;
-moz-animation: flickerAnimation 25s infinite;
-o-animation: flickerAnimation 25s infinite;
animation: flickerAnimation 25s infinite;
animation-delay: 0.8s;
-webkit-animation-delay: 0.8s;
-moz-animation-delay: 0.8s;
-o-animation-delay: 0.8s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
/* _x31_0 */
#_x31_0, #_x32_1, #_x31_8 {
-webkit-animation: flickerAnimation 30s infinite;
-moz-animation: flickerAnimation 30s infinite;
-o-animation: flickerAnimation 30s infinite;
animation: flickerAnimation 30s infinite;
animation-delay: 2s;
-webkit-animation-delay: 2s;
-moz-animation-delay: 2s;
-o-animation-delay: 2s;
}
@keyframes flickerAnimation {
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-o-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-moz-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
@-webkit-keyframes flickerAnimation{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
```
```html
<body>
<svg version="1.1" id="Logo" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 500 500" enable-background="new 0 0 500 500" xml:space="preserve">
<g transform="translate(243.35 194.85)">
<g id="Circleelement">
<g transform="translate(-243.35 -194.85)">
<circle id="_x31_" fill="#000000" stroke-miterlimit="10" cx="242.5" cy="81.5" r="11.1"> </circle>
<circle id="_x32_" fill="#000000" stroke-miterlimit="10" cx="277.1" cy="87" r="10.8"/>
<circle id="_x33_" fill="#000000" stroke-miterlimit="10" cx="307.5" cy="102" r="10.5"/>
<circle id="_x34_" fill="#000000" stroke-miterlimit="10" cx="332.1" cy="124.9" r="10.2"/>
<circle id="_x35_" fill="#000000" stroke-miterlimit="10" cx="349.1" cy="154.2" r="9.9"/>
<circle id="_x36_" fill="#000000" stroke-miterlimit="10" cx="357" cy="188.1" r="9.6"/>
<circle id="_x37_" fill="#000000" stroke-miterlimit="10" cx="354.3" cy="223.4" r="9.4"/>
<circle id="_x38_" fill="#000000" stroke-miterlimit="10" cx="341.7" cy="255.1" r="9.1"/>
<circle id="_x39_" fill="#000000" stroke-miterlimit="10" cx="320.7" cy="281.4" r="8.8"/>
<circle id="_x31_0" fill="#000000" stroke-miterlimit="10" cx="293.1" cy="300.6" r="8.5"/>
<circle id="_x31_1" fill="#000000" stroke-miterlimit="10" cx="260.3" cy="311.1" r="8.2"/>
<circle id="_x31_2" fill="#000000" stroke-miterlimit="10" cx="224.7" cy="311.3" r="7.9"/>
<circle id="_x31_3" fill="#000000" stroke-miterlimit="10" cx="191.8" cy="301.2" r="7.6"/>
<circle id="_x31_4" fill="#000000" stroke-miterlimit="10" cx="164" cy="282.3" r="7.3"/>
<circle id="_x31_5" fill="#000000" stroke-miterlimit="10" cx="142.7" cy="256.3" r="7"/>
<circle id="_x31_6" fill="#000000" stroke-miterlimit="10" cx="129.7" cy="224.7" r="6.8"/>
<circle id="_x31_7" fill="#000000" stroke-miterlimit="10" cx="126.6" cy="189.4" r="6.5"/>
<circle id="_x31_8" fill="#000000" stroke-miterlimit="10" cx="134" cy="155.5" r="6.2"/>
<circle id="_x31_9" fill="#000000" stroke-miterlimit="10" cx="150.7" cy="126.1" r="5.9"/>
<circle id="_x32_0" fill="#000000" stroke-miterlimit="10" cx="174.9" cy="102.9" r="5.6"/>
<circle id="_x32_1" fill="#000000" stroke-miterlimit="10" cx="205.2" cy="87.5" r="5.3"/>
<circle id="_x32_2" fill="#000000" stroke-miterlimit="10" cx="242.6" cy="123.6" r="10.4"/>
<circle id="_x32_3" fill="#000000" stroke-miterlimit="10" cx="282.5" cy="136.5" r="9.7"/>
<circle id="_x32_4" fill="#000000" stroke-miterlimit="10" cx="308.8" cy="168" r="9.1"/>
<circle id="_x32_5" fill="#000000" stroke-miterlimit="10" cx="314" cy="210.3" r="8.4"/>
<circle id="_x32_6" fill="#000000" stroke-miterlimit="10" cx="261.1" cy="269.4" r="7.1"/>
<circle id="_x32_7" fill="#000000" stroke-miterlimit="10" cx="218.3" cy="268.8" r="6.5"/>
<circle id="_x32_8" fill="#000000" stroke-miterlimit="10" cx="184.1" cy="246.1" r="5.8"/>
<circle id="_x32_9" fill="#000000" stroke-miterlimit="10" cx="167.1" cy="208.3" r="5.2"/>
<circle id="_x33_0" fill="#000000" stroke-miterlimit="10" cx="200.5" cy="135.4" r="3.9"/>
<circle id="_x33_1" fill="#000000" stroke-miterlimit="10" cx="242.2" cy="164.1" r="5.4"/>
<circle id="_x33_2" fill="#000000" stroke-miterlimit="10" cx="271.9" cy="181.8" r="4.8"/>
<circle id="_x33_3" fill="#000000" stroke-miterlimit="10" cx="271.5" cy="216.9" r="4.1"/>
<circle id="_x33_4" fill="#000000" stroke-miterlimit="10" cx="241.3" cy="233.9" r="3.5"/>
<circle id="_x33_5" fill="#000000" stroke-miterlimit="10" cx="211.4" cy="216.5" r="2.8"/>
<circle id="_x33_6" fill="#000000" stroke-miterlimit="10" cx="211.4" cy="181.4" r="2.2"/>
</g>
</g>
</g>
<g id="Name">
<text transform="matrix(1 0 0 1 44 439.7)" font-family="'Gotham-Book'" font-size="54">S O M E T E X T</text>
</g>
</svg>
</body>
``` | Just use `transform-box: fill-box;` on that element, or on all elements. |
66,142,980 | I'm installing SQL Server on Linux Ubuntu 18.04, according to the tutorial <https://learn.microsoft.com/en-us/sql/linux/quickstart-install-connect-ubuntu?view=sql-server-ver15>, however when executing the first command
```
wget -qO- https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
```
I get the following error
```
gpg: no valid OpenPGP data found.
```
I've done several researches about the error, installed ca-certificates, installed all the gpg packages but I still can't solve the problem, can someone direct me to a solution? | 2021/02/10 | [
"https://Stackoverflow.com/questions/66142980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12770514/"
] | `[B@5024d44` tells you you have a byte array, and tells you **nothing whatsoever** about what is in it. You *cannot* convert that back to anything meaningful.
To convert a byte array to a `String` reversibly, use [`Base64`](https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html). | If you have a string `[B@5024d44`, you can convert it to a `byte[]` array, and then convert this array back to a string. These two strings would be equal, but the array wouldn't be equal to the string, and also the contents of the array wouldn't be equal to the string:
```java
String str = "[B@5024d44";
byte[] arr = str.getBytes(StandardCharsets.UTF_8);
String str1 = new String(arr, StandardCharsets.UTF_8);
// strings are equal
System.out.println(str.equals(str1)); // true
// string representation of the array
System.out.println(arr); // [B@5451c3a8
// contents of the array
System.out.println(Arrays.toString(arr));
// [91, 66, 64, 53, 48, 50, 52, 100, 52, 52]
```
---
See also: [How can I convert a string into a GZIP Base64 string?](https://stackoverflow.com/a/66409602/15309136) |
7,516,262 | I am going off of this tutorial: <http://www.dotnetperls.com/sqlclient> . Instead of adding a data source and a having visual studio compile my connecting string - I want to do it myself. The reason being is that the database will not always be the same and I want this application to be able to use different databases depending on which I point it to.
So how can I manually create the connection string? I am using SQL Server 2005. | 2011/09/22 | [
"https://Stackoverflow.com/questions/7516262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/959309/"
] | Step 1: Go to [connectionstrings.com](http://connectionstrings.com/) and find the proper format for your database.
Step 2: Plug in the appropriate values to the connection string.
Step 3: Pass that string to the constructor of `SqlConnection`.
I would also suggest storing your connection string in your app.config/web.config file. You can then modify them easily if needed. The proper format can be found at [MSDN - connectionStrings element](http://msdn.microsoft.com/en-us/library/bf7sd233.aspx). You then change your code to:
```
SqlConnection sqlConn = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnStringName"].ConnectionString);
``` | I don't see where the connection string is **"compiled"**.
In the code
```
SqlConnection con = new SqlConnection(
ConsoleApplication1.Properties.Settings.Default.masterConnectionString)
```
`ConsoleApplication1.Properties.Settings.Default.masterConnectionString` is a field and it can be replaced with any other appropriate string. |
7,516,262 | I am going off of this tutorial: <http://www.dotnetperls.com/sqlclient> . Instead of adding a data source and a having visual studio compile my connecting string - I want to do it myself. The reason being is that the database will not always be the same and I want this application to be able to use different databases depending on which I point it to.
So how can I manually create the connection string? I am using SQL Server 2005. | 2011/09/22 | [
"https://Stackoverflow.com/questions/7516262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/959309/"
] | Step 1: Go to [connectionstrings.com](http://connectionstrings.com/) and find the proper format for your database.
Step 2: Plug in the appropriate values to the connection string.
Step 3: Pass that string to the constructor of `SqlConnection`.
I would also suggest storing your connection string in your app.config/web.config file. You can then modify them easily if needed. The proper format can be found at [MSDN - connectionStrings element](http://msdn.microsoft.com/en-us/library/bf7sd233.aspx). You then change your code to:
```
SqlConnection sqlConn = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnStringName"].ConnectionString);
``` | for SQL Server format of the connection string is
"Data Source = server\_address; Initial Catalog = database\_name; User ID = UserId; Password = *\**\*;"
save this connection string in a string variable and use with connection object.
either way you can add in web.config file.
```
<ConnectionString>
<add name = "name_of_connecctionString" ConnectionString = "Data Source = server_address; Initial Catalog = database_name; User ID = UserId; Password = ****;" ProviderName = "system.Data.SqlClient"/>
</ConnectionString>
```
you can change the provider as needed by you.
then in code behind file access this particular connection string using configuration manager. |
20,606,346 | I had a condition written like
```
IF(LEN(@strData) > 3 OR @strData > '255') BEGIN
// Some Condition
END
```
This is written in a sp which i come across written by someone.
First Condition is clear if LEN > 3 its coming true for that condition.
But `> '255'` what does it mean ?
I passed random values like
```
@strData = 'add' Result true
@strData = 'a' Result true
@strData = '12hhd' Result false
```
I didn't understand what way it behaves.
That query is not commented why fellow developer writes that line.
In SQL String Comparison how it will work..
Please some make me clear.
**UPDATE :**
I need that same condition in C# for some purpose | 2013/12/16 | [
"https://Stackoverflow.com/questions/20606346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2404117/"
] | In SQL Server a string comparison is done in alphabetical order. That is "allan" is greater than "alan" because alphabetically "alan" comes before "allan". So, numbers are treated the same when doing string comparison, they are treated in alphabetical order...so, '2' is greater than '12'...surprising, huh? Well, alphabetical string comparisons are done from left to right hence '2' is greater than '12'.
Now, in C#, there's absolutely no difference it behaves exactly the same as sql. To reinforce any possible doubts you might have...you can easily test it....
SQL
```
if '2' > '12'
select '2 > 12';
else
select '2 < 12';
```
C# Console App
```
if ("2".CompareTo("12") < 0 )
Console.WriteLine("2 is less than 12");
else if ("2".CompareTo("12") > 0)
Console.WriteLine("2 is greater than 12");
else
Console.WriteLine("2 is equal to 12");
```
Hope it makes sense for you | Its a simple comaprision between two strings.
An SQL string comparision works like so:
```
Compare 'a' with '255' for '>'
if length(a) < length(b)
pad a with spaces to be same length as b;
for x = 0 to length(a)
if a(x) < b(x) return false;
if a(x) > b(x) return true;
return false;
```
In the case of your " 'a' > '255' "
the ASCII/utf-8 letter 'a' is greater than the character '2' so it returns true on the first character comparision, |
40,438,676 | Given a list, how can I get all combinations between two non-consecutive items?
For example, for input `[1, 2, 3, 4, 5]` how can I get the output `[(1,3), (1,4), (1,5), (2,4), (2,5), (3,5)]`?
I'm not interested in `(1,2)`, `(2,3)`, `(3,4)` or `(4,5)` because they are consecutive (i.e. next to each other) in the list, but everything else I'm interested.
What's the most idiomatic way to do this in Python? | 2016/11/05 | [
"https://Stackoverflow.com/questions/40438676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902414/"
] | Here is a fairly "idiomatic" way not using any modules, which is more efficient than some other implementations since every trip through the loop is used--no rejected possibilities.
```
r = [1, 2, 3, 4, 5]
c = [(r[i], r[j]) for i in range(len(r)-2) for j in range(i+2, len(r))]
print(c)
```
This gives
```
[(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5)]
```
It is not completely idiomatic, since it loops on indices rather than values, but your restriction regarding the positions in the list rather than the values makes that fairly necessary. If you want a generator rather than a list, replace the outer brackets with parentheses. | If you are interested in the combinations with non-consecutive numbers from the list:
```
from itertools import combinations
lst = [1, 2, 3, 4, 5]
list(filter(lambda x: lst.index(x[1]) - lst.index(x[0]) > 1, combinations(lst,2)))
[(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5)]
```
This compares the indices of the two numbers in a given combination and makes sure that the difference of their indices is greater than 1.
I hope it helps. |
40,438,676 | Given a list, how can I get all combinations between two non-consecutive items?
For example, for input `[1, 2, 3, 4, 5]` how can I get the output `[(1,3), (1,4), (1,5), (2,4), (2,5), (3,5)]`?
I'm not interested in `(1,2)`, `(2,3)`, `(3,4)` or `(4,5)` because they are consecutive (i.e. next to each other) in the list, but everything else I'm interested.
What's the most idiomatic way to do this in Python? | 2016/11/05 | [
"https://Stackoverflow.com/questions/40438676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902414/"
] | A simple list comprehension:
```
>>> lst = [1, 2, 3, 4, 5]
>>> [(a, b) for i, a in enumerate(lst) for b in lst[i+2:]]
[(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5)]
``` | Here is a fairly "idiomatic" way not using any modules, which is more efficient than some other implementations since every trip through the loop is used--no rejected possibilities.
```
r = [1, 2, 3, 4, 5]
c = [(r[i], r[j]) for i in range(len(r)-2) for j in range(i+2, len(r))]
print(c)
```
This gives
```
[(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5)]
```
It is not completely idiomatic, since it loops on indices rather than values, but your restriction regarding the positions in the list rather than the values makes that fairly necessary. If you want a generator rather than a list, replace the outer brackets with parentheses. |
40,438,676 | Given a list, how can I get all combinations between two non-consecutive items?
For example, for input `[1, 2, 3, 4, 5]` how can I get the output `[(1,3), (1,4), (1,5), (2,4), (2,5), (3,5)]`?
I'm not interested in `(1,2)`, `(2,3)`, `(3,4)` or `(4,5)` because they are consecutive (i.e. next to each other) in the list, but everything else I'm interested.
What's the most idiomatic way to do this in Python? | 2016/11/05 | [
"https://Stackoverflow.com/questions/40438676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902414/"
] | Here is a fairly "idiomatic" way not using any modules, which is more efficient than some other implementations since every trip through the loop is used--no rejected possibilities.
```
r = [1, 2, 3, 4, 5]
c = [(r[i], r[j]) for i in range(len(r)-2) for j in range(i+2, len(r))]
print(c)
```
This gives
```
[(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5)]
```
It is not completely idiomatic, since it loops on indices rather than values, but your restriction regarding the positions in the list rather than the values makes that fairly necessary. If you want a generator rather than a list, replace the outer brackets with parentheses. | Here's a generalized solution for r-length combinations avoiding consecutive elements. It gets all index [combinations](https://docs.python.org/3.6/library/itertools.html#itertools.combinations) for an appropriately shorter list and then spreads out each combination's indexes. For example for r=3, any combination (x,y,z) turns into used indexes x+0, y+1, z+2.
```
from itertools import combinations
def non_consecutive_combinations(lst, r):
return [tuple(lst[j+i] for i, j in enumerate(combi))
for combi in combinations(range(len(lst)-r+1), r)]
```
Demo for r=2:
```
>>> non_consecutive_combinations([1, 2, 3, 4, 5], 2)
[(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5)]
```
Demo for r=3:
```
>>> non_consecutive_combinations([1, 2, 3, 4, 5, 6, 7], 3)
[(1, 3, 5), (1, 3, 6), (1, 3, 7), (1, 4, 6), (1, 4, 7), (1, 5, 7), (2, 4, 6), (2, 4, 7), (2, 5, 7), (3, 5, 7)]
```
A simplified version just for pairs:
```
>>> [(lst[i], lst[j+1]) for i, j in combinations(range(len(lst)-1), 2)]
[(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5)]
``` |
40,438,676 | Given a list, how can I get all combinations between two non-consecutive items?
For example, for input `[1, 2, 3, 4, 5]` how can I get the output `[(1,3), (1,4), (1,5), (2,4), (2,5), (3,5)]`?
I'm not interested in `(1,2)`, `(2,3)`, `(3,4)` or `(4,5)` because they are consecutive (i.e. next to each other) in the list, but everything else I'm interested.
What's the most idiomatic way to do this in Python? | 2016/11/05 | [
"https://Stackoverflow.com/questions/40438676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902414/"
] | A simple list comprehension:
```
>>> lst = [1, 2, 3, 4, 5]
>>> [(a, b) for i, a in enumerate(lst) for b in lst[i+2:]]
[(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5)]
``` | If you are interested in the combinations with non-consecutive numbers from the list:
```
from itertools import combinations
lst = [1, 2, 3, 4, 5]
list(filter(lambda x: lst.index(x[1]) - lst.index(x[0]) > 1, combinations(lst,2)))
[(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5)]
```
This compares the indices of the two numbers in a given combination and makes sure that the difference of their indices is greater than 1.
I hope it helps. |
40,438,676 | Given a list, how can I get all combinations between two non-consecutive items?
For example, for input `[1, 2, 3, 4, 5]` how can I get the output `[(1,3), (1,4), (1,5), (2,4), (2,5), (3,5)]`?
I'm not interested in `(1,2)`, `(2,3)`, `(3,4)` or `(4,5)` because they are consecutive (i.e. next to each other) in the list, but everything else I'm interested.
What's the most idiomatic way to do this in Python? | 2016/11/05 | [
"https://Stackoverflow.com/questions/40438676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902414/"
] | A simple list comprehension:
```
>>> lst = [1, 2, 3, 4, 5]
>>> [(a, b) for i, a in enumerate(lst) for b in lst[i+2:]]
[(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5)]
``` | Here's a generalized solution for r-length combinations avoiding consecutive elements. It gets all index [combinations](https://docs.python.org/3.6/library/itertools.html#itertools.combinations) for an appropriately shorter list and then spreads out each combination's indexes. For example for r=3, any combination (x,y,z) turns into used indexes x+0, y+1, z+2.
```
from itertools import combinations
def non_consecutive_combinations(lst, r):
return [tuple(lst[j+i] for i, j in enumerate(combi))
for combi in combinations(range(len(lst)-r+1), r)]
```
Demo for r=2:
```
>>> non_consecutive_combinations([1, 2, 3, 4, 5], 2)
[(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5)]
```
Demo for r=3:
```
>>> non_consecutive_combinations([1, 2, 3, 4, 5, 6, 7], 3)
[(1, 3, 5), (1, 3, 6), (1, 3, 7), (1, 4, 6), (1, 4, 7), (1, 5, 7), (2, 4, 6), (2, 4, 7), (2, 5, 7), (3, 5, 7)]
```
A simplified version just for pairs:
```
>>> [(lst[i], lst[j+1]) for i, j in combinations(range(len(lst)-1), 2)]
[(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5)]
``` |
6,230,834 | I have a debugger log that I've written in JavaScript for a project I'm working on. The log is basically an `<aside>` tag in HTML5 that only shows when needed. I wanted to play around with the idea of being able to move the log around the screen, as it may overlap certain things (which is fine for my project). However, I can't seem to figure out how to use HTML5 to properly drag and drop the tag so that it can be placed anywhere on the screen (well, or within a `<div>` element).
After reading on HTML5's drag and drop support, I have a basic understanding of how it works, but I'm not sure where to start when it comes to allowing the div to be placed anywhere (it's z-index is a high value, so as I said, overlapping is fine).
Any suggestions?
Oh, and I'd like to try and avoid using external libraries for this project, wherever possible. I'm trying to do this in pure JavaScript/HTML5. | 2011/06/03 | [
"https://Stackoverflow.com/questions/6230834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/595521/"
] | Drag and drop doesn't move elements around, if you want the element to move when you drop it then you have to set the new position of the element in the drop event. I've [done an example](http://jsfiddle.net/robertc/kKuqH/) which works in Firefox and Chrome, here are the key points:
```
function drag_start(event) {
var style = window.getComputedStyle(event.target, null);
event.dataTransfer.setData("text/plain",
(parseInt(style.getPropertyValue("left"),10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"),10) - event.clientY));
}
```
The `dragstart` event works out the offset of the mouse pointer from the left and top of the element and passes it in the `dataTransfer`. I'm not worrying about passing the ID because there's only one draggable element on the page - no links or images - if you have any of that stuff on your page then you'll have to do a little more work here.
```
function drop(event) {
var offset = event.dataTransfer.getData("text/plain").split(',');
var dm = document.getElementById('dragme');
dm.style.left = (event.clientX + parseInt(offset[0],10)) + 'px';
dm.style.top = (event.clientY + parseInt(offset[1],10)) + 'px';
event.preventDefault();
return false;
}
```
The `drop` event unpacks the offsets and uses them to position the element relative to the mouse pointer.
The `dragover` event just needs to `preventDefault` when anything is dragged over. Again, if there is anything else draggable on the page you might need to do something more complex here:
```
function drag_over(event) {
event.preventDefault();
return false;
}
```
So bind it to the `document.body` along with the `drop` event to capture everything:
```
var dm = document.getElementById('dragme');
dm.addEventListener('dragstart',drag_start,false);
document.body.addEventListener('dragover',drag_over,false);
document.body.addEventListener('drop',drop,false);
```
If you want this to work in IE you'll need to convert the `aside` to an `a` element, and, of course, all the event binding code will be different. The drag and drop API doesn't work in Opera, or on any mobile browsers as far as I'm aware. Also, I know you said you don't want to use jQuery, but cross browser event binding and manipulating element positions are the sort of things that jQuery makes much easier. | Thanks for your answer. It works great in Chrome and Firefox. I tweaked it to work in IE.Below is the code.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="generator" content="CoffeeCup HTML Editor (www.coffeecup.com)">
<meta name="dcterms.created" content="Fri, 27 Jun 2014 21:02:23 GMT">
<meta name="description" content="">
<meta name="keywords" content="">
<title></title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
li
{
position: absolute;
left: 0;
top: 0; /* set these so Chrome doesn't return 'auto' from getComputedStyle */
width: 200px;
background: rgba(255,255,255,0.66);
border: 2px solid rgba(0,0,0,0.5);
border-radius: 4px; padding: 8px;
}
</style>
<script>
function drag_start(event) {
var style = window.getComputedStyle(event.target, null);
var str = (parseInt(style.getPropertyValue("left")) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top")) - event.clientY) + ',' + event.target.id;
event.dataTransfer.setData("Text", str);
}
function drop(event) {
var offset = event.dataTransfer.getData("Text").split(',');
var dm = document.getElementById(offset[2]);
dm.style.left = (event.clientX + parseInt(offset[0], 10)) + 'px';
dm.style.top = (event.clientY + parseInt(offset[1], 10)) + 'px';
event.preventDefault();
return false;
}
function drag_over(event) {
event.preventDefault();
return false;
}
</script>
</head>
<body ondragover="drag_over(event)" ondrop="drop(event)">
<ul>
<li id="txt1" draggable="true" ondragstart="drag_start(event)"> Drag this text </li><br>
<li id="txt2" draggable="true" ondragstart="drag_start(event)"> Drag me</li>
</ul>
<p>I never am really satisfied that I understand anything; because, understand it well as I may, my comprehension can only be an infinitesimal fraction of all I want to understand about the many connections and relations which occur to me, how the matter in question was first thought of or arrived at, etc., etc.</p>
<p>In almost every computation a great variety of arrangements for the succession of the processes is possible, and various considerations must influence the selections amongst them for the purposes of a calculating engine. One essential object is to choose that arrangement which shall tend to reduce to a minimum the time necessary for completing the calculation.</p>
<p>Many persons who are not conversant with mathematical studies imagine that because the business of [Babbage’s Analytical Engine] is to give its results in numerical notation, the nature of its processes must consequently be arithmetical and numerical, rather than algebraical and analytical. This is an error. The engine can arrange and combine its numerical quantities exactly as if they were letters or any other general symbols; and in fact it might bring out its results in algebraical notation, were provisions made accordingly.</p>
<p>The Analytical Engine has no pretensions whatever to originate anything. It can do whatever we know how to order it to perform. It can follow analysis, but it has no power of anticipating any analytical revelations or truths. Its province is to assist us in making available what we are already acquainted with.</p>
</body>
</html>
``` |
6,230,834 | I have a debugger log that I've written in JavaScript for a project I'm working on. The log is basically an `<aside>` tag in HTML5 that only shows when needed. I wanted to play around with the idea of being able to move the log around the screen, as it may overlap certain things (which is fine for my project). However, I can't seem to figure out how to use HTML5 to properly drag and drop the tag so that it can be placed anywhere on the screen (well, or within a `<div>` element).
After reading on HTML5's drag and drop support, I have a basic understanding of how it works, but I'm not sure where to start when it comes to allowing the div to be placed anywhere (it's z-index is a high value, so as I said, overlapping is fine).
Any suggestions?
Oh, and I'd like to try and avoid using external libraries for this project, wherever possible. I'm trying to do this in pure JavaScript/HTML5. | 2011/06/03 | [
"https://Stackoverflow.com/questions/6230834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/595521/"
] | Drag and drop doesn't move elements around, if you want the element to move when you drop it then you have to set the new position of the element in the drop event. I've [done an example](http://jsfiddle.net/robertc/kKuqH/) which works in Firefox and Chrome, here are the key points:
```
function drag_start(event) {
var style = window.getComputedStyle(event.target, null);
event.dataTransfer.setData("text/plain",
(parseInt(style.getPropertyValue("left"),10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"),10) - event.clientY));
}
```
The `dragstart` event works out the offset of the mouse pointer from the left and top of the element and passes it in the `dataTransfer`. I'm not worrying about passing the ID because there's only one draggable element on the page - no links or images - if you have any of that stuff on your page then you'll have to do a little more work here.
```
function drop(event) {
var offset = event.dataTransfer.getData("text/plain").split(',');
var dm = document.getElementById('dragme');
dm.style.left = (event.clientX + parseInt(offset[0],10)) + 'px';
dm.style.top = (event.clientY + parseInt(offset[1],10)) + 'px';
event.preventDefault();
return false;
}
```
The `drop` event unpacks the offsets and uses them to position the element relative to the mouse pointer.
The `dragover` event just needs to `preventDefault` when anything is dragged over. Again, if there is anything else draggable on the page you might need to do something more complex here:
```
function drag_over(event) {
event.preventDefault();
return false;
}
```
So bind it to the `document.body` along with the `drop` event to capture everything:
```
var dm = document.getElementById('dragme');
dm.addEventListener('dragstart',drag_start,false);
document.body.addEventListener('dragover',drag_over,false);
document.body.addEventListener('drop',drop,false);
```
If you want this to work in IE you'll need to convert the `aside` to an `a` element, and, of course, all the event binding code will be different. The drag and drop API doesn't work in Opera, or on any mobile browsers as far as I'm aware. Also, I know you said you don't want to use jQuery, but cross browser event binding and manipulating element positions are the sort of things that jQuery makes much easier. | I adjusted a bit *robertc*'s great answer for cases of multiple items. Here the `second`class name is just for another position.
```
<aside draggable="true" class="dragme" data-item="0">One</aside>
<aside draggable="true" class="dragme second" data-item="1">Two</aside>
```
Add the data-item attribute to the `setData`function.
```
function drag_start(event) {
var style = window.getComputedStyle(event.target, null);
event.dataTransfer.setData("text/plain", (parseInt(style.getPropertyValue("left"), 10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"), 10) - event.clientY) + ',' + event.target.getAttribute('data-item'));
}
```
Target the element that is dragged.
```
function drop(event) {
var offset = event.dataTransfer.getData("text/plain").split(',');
var dm = document.getElementsByClassName('dragme');
dm[parseInt(offset[2])].style.left = (event.clientX + parseInt(offset[0], 10)) + 'px';
dm[parseInt(offset[2])].style.top = (event.clientY + parseInt(offset[1], 10)) + 'px';
event.preventDefault();
return false;
}
```
And loop through all elements with a class `dragme`.
```
var dm = document.getElementsByClassName('dragme');
for (var i = 0; i < dm.length; i++) {
dm[i].addEventListener('dragstart', drag_start, false);
document.body.addEventListener('dragover', drag_over, false);
document.body.addEventListener('drop', drop, false);
}
```
[pen](http://codepen.io/ingvi/pen/NNjWyN?editors=0010) |
6,230,834 | I have a debugger log that I've written in JavaScript for a project I'm working on. The log is basically an `<aside>` tag in HTML5 that only shows when needed. I wanted to play around with the idea of being able to move the log around the screen, as it may overlap certain things (which is fine for my project). However, I can't seem to figure out how to use HTML5 to properly drag and drop the tag so that it can be placed anywhere on the screen (well, or within a `<div>` element).
After reading on HTML5's drag and drop support, I have a basic understanding of how it works, but I'm not sure where to start when it comes to allowing the div to be placed anywhere (it's z-index is a high value, so as I said, overlapping is fine).
Any suggestions?
Oh, and I'd like to try and avoid using external libraries for this project, wherever possible. I'm trying to do this in pure JavaScript/HTML5. | 2011/06/03 | [
"https://Stackoverflow.com/questions/6230834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/595521/"
] | Thanks for your answer. It works great in Chrome and Firefox. I tweaked it to work in IE.Below is the code.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="generator" content="CoffeeCup HTML Editor (www.coffeecup.com)">
<meta name="dcterms.created" content="Fri, 27 Jun 2014 21:02:23 GMT">
<meta name="description" content="">
<meta name="keywords" content="">
<title></title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
li
{
position: absolute;
left: 0;
top: 0; /* set these so Chrome doesn't return 'auto' from getComputedStyle */
width: 200px;
background: rgba(255,255,255,0.66);
border: 2px solid rgba(0,0,0,0.5);
border-radius: 4px; padding: 8px;
}
</style>
<script>
function drag_start(event) {
var style = window.getComputedStyle(event.target, null);
var str = (parseInt(style.getPropertyValue("left")) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top")) - event.clientY) + ',' + event.target.id;
event.dataTransfer.setData("Text", str);
}
function drop(event) {
var offset = event.dataTransfer.getData("Text").split(',');
var dm = document.getElementById(offset[2]);
dm.style.left = (event.clientX + parseInt(offset[0], 10)) + 'px';
dm.style.top = (event.clientY + parseInt(offset[1], 10)) + 'px';
event.preventDefault();
return false;
}
function drag_over(event) {
event.preventDefault();
return false;
}
</script>
</head>
<body ondragover="drag_over(event)" ondrop="drop(event)">
<ul>
<li id="txt1" draggable="true" ondragstart="drag_start(event)"> Drag this text </li><br>
<li id="txt2" draggable="true" ondragstart="drag_start(event)"> Drag me</li>
</ul>
<p>I never am really satisfied that I understand anything; because, understand it well as I may, my comprehension can only be an infinitesimal fraction of all I want to understand about the many connections and relations which occur to me, how the matter in question was first thought of or arrived at, etc., etc.</p>
<p>In almost every computation a great variety of arrangements for the succession of the processes is possible, and various considerations must influence the selections amongst them for the purposes of a calculating engine. One essential object is to choose that arrangement which shall tend to reduce to a minimum the time necessary for completing the calculation.</p>
<p>Many persons who are not conversant with mathematical studies imagine that because the business of [Babbage’s Analytical Engine] is to give its results in numerical notation, the nature of its processes must consequently be arithmetical and numerical, rather than algebraical and analytical. This is an error. The engine can arrange and combine its numerical quantities exactly as if they were letters or any other general symbols; and in fact it might bring out its results in algebraical notation, were provisions made accordingly.</p>
<p>The Analytical Engine has no pretensions whatever to originate anything. It can do whatever we know how to order it to perform. It can follow analysis, but it has no power of anticipating any analytical revelations or truths. Its province is to assist us in making available what we are already acquainted with.</p>
</body>
</html>
``` | I adjusted a bit *robertc*'s great answer for cases of multiple items. Here the `second`class name is just for another position.
```
<aside draggable="true" class="dragme" data-item="0">One</aside>
<aside draggable="true" class="dragme second" data-item="1">Two</aside>
```
Add the data-item attribute to the `setData`function.
```
function drag_start(event) {
var style = window.getComputedStyle(event.target, null);
event.dataTransfer.setData("text/plain", (parseInt(style.getPropertyValue("left"), 10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"), 10) - event.clientY) + ',' + event.target.getAttribute('data-item'));
}
```
Target the element that is dragged.
```
function drop(event) {
var offset = event.dataTransfer.getData("text/plain").split(',');
var dm = document.getElementsByClassName('dragme');
dm[parseInt(offset[2])].style.left = (event.clientX + parseInt(offset[0], 10)) + 'px';
dm[parseInt(offset[2])].style.top = (event.clientY + parseInt(offset[1], 10)) + 'px';
event.preventDefault();
return false;
}
```
And loop through all elements with a class `dragme`.
```
var dm = document.getElementsByClassName('dragme');
for (var i = 0; i < dm.length; i++) {
dm[i].addEventListener('dragstart', drag_start, false);
document.body.addEventListener('dragover', drag_over, false);
document.body.addEventListener('drop', drop, false);
}
```
[pen](http://codepen.io/ingvi/pen/NNjWyN?editors=0010) |
57,274,205 | Using the Java Instant class, how can I round up to the nearest second? I don't care if it is 1 millisecond, 15 milliseconds, or 999 milliseconds, all should round up to the next second with 0 milliseconds.
I basically want,
```
Instant myInstant = ...
myInstant.truncatedTo(ChronoUnit.SECONDS);
```
but in the opposite direction. | 2019/07/30 | [
"https://Stackoverflow.com/questions/57274205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3502664/"
] | You can cover the corner case by using `.getNano` to make sure the time is not exactly even on the second and then add the extra second using `.plusSeconds()` when there is a value to truncate.
```
Instant myInstant = Instant.now();
if (myInstant.getNano() > 0) //Checks for any nanoseconds for the current second (this will almost always be true)
{
myInstant = myInstant.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1);
}
/* else //Rare case where nanoseconds are exactly 0
{
myInstant = myInstant;
} */
```
I left in the `else` statement just to demonstrate no operations need to be done if it is exactly 0 nanoseconds, because there is no reason to truncate nothing.
**EDIT:** If you want to check if the time is at least 1 millisecond over a second in order to round up, instead of 1 nanosecond you can then compare it to 1000000 nanoseconds but leave the `else` statement in to truncate the nanoseconds:
```
Instant myInstant = Instant.now();
if (myInstant.getNano() > 1000000) //Nano to milliseconds
{
myInstant = myInstant.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1);
}
else
{
myInstant = myInstant.truncatedTo(ChronoUnit.SECONDS); //Must truncate the nanoseconds off since we are comparing to milliseconds now.
}
``` | You can use the [lambda functional programming](https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html) streams approach to make this a one liner.
Add a second and truncate. To cover the corner case of being exactly on a second, check the truncated to the original, and only add a second if they differ:
```
Instant myRoundedUpInstant = Optional.of(myInstant.truncatedTo(ChronoUnit.SECONDS))
.filter(myInstant::equals)
.orElse(myInstant.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1));
```
See this [code run line at IdeOne.com](https://ideone.com/OYpCwu).
>
> Instant.toString(): 2019-07-30T20:06:33.456424Z
>
>
> myRoundedUpInstant(): 2019-07-30T20:06:34Z
>
>
>
…and…
>
> myInstant.toString(): 2019-07-30T20:05:20Z
>
>
> myRoundedUpInstant(): 2019-07-30T20:05:20Z
>
>
>
Or alternatively, with a slightly different approach:
```
Instant myRoundedUpInstant = Optional.of(myInstant)
.filter(t -> t.getNano() != 0)
.map(t -> t.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1))
.orElse(myInstant);
```
See this [code run live at IdeOne.com](https://ideone.com/9V0I2v).
>
> myInstant.toString(): 2019-07-30T20:09:07.415043Z
>
>
> myRoundedUpInstant(): 2019-07-30T20:09:08Z
>
>
>
…and…
>
> myInstant.toString(): 2019-07-30T19:44:06Z
>
>
> myRoundedUpInstant(): 2019-07-30T19:44:06Z
>
>
>
Above is of course in Java 8 land. I'll leave it as an exercise to the reader to split that out into the more traditional if/else if [`Optional`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Optional.html) isn't your thing :-) |