date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/14
| 464 | 1,621 |
<issue_start>username_0: ```
public class Parent
{
public virtual int Id{ get; set; }
public virtual ICollection Children { get; set; }
public Parent()
{
Children = new List();
}
}
public class Child
{
public virtual int Id{ get; set; }
public virtual string Name { get; set; }
}
```
Mapping:
```
public ParentMap()
{
Map(x => x.Number).Not.Nullable();
HasMany(x => x.Children)
.Cascade.None()
.KeyColumn("ParentId")
.ExtraLazyLoad()
.AsSet();
}
```
Sql script generated:
```
ALTER TABLE [dbo].[Child] WITH CHECK ADD CONSTRAINT [FKFCFBAA864983AA6A] FOREIGN KEY([ParentId])
REFERENCES [dbo].[Parent] ([Id])
GO
ALTER TABLE [dbo].[Child] CHECK CONSTRAINT [FKFCFBAA864983AA6A]
GO
```
How to change the Foreign Key format of `[FKFCFBAA864983AA6A]` to `[FK_ChildTableName_ParentTableName]`?<issue_comment>username_1: If you do not have a `settings.gradle` file create one and add the following line
```
include 'klint'
```
Upvotes: -1 <issue_comment>username_2: The `buildscript` block is evaluated at the beginning and determines which plugins and tasks are available for use in the rest of the build script.
For my experience what you are trying to do (the `buildscript` block into an `apply` script) isn’t supported.
Upvotes: 2 [selected_answer]<issue_comment>username_3: Based on my experience, you should have a copy of the buildscript code block in both base build.gradle file and your external build file.
I don't like the design like this, but that's the only way to achieve our goal currently. You can have a try.
Upvotes: 0
|
2018/03/14
| 636 | 1,853 |
<issue_start>username_0: If I have a number like -7 stored in a variable how can I modify a date in php by this amount. Here's what I have so far;
```
php
$the_date = '16 Mar 2018';
$test_sum = '-7';
$date = $the_date;
$date = strtotime($date);
$date = strtotime($test_sum, $date);
echo date('d M Y', $date);
?
```
But this just output's the initial date value.<issue_comment>username_1: If you want to subtract days, you can simply use `'-7 days'`. If you don't specify the unit `strtotime()` probably doesn't subtracts days.
```
$the_date = '16 Mar 2018';
$test_sum = -7;
$date = strtotime(sprintf("%d days", $test_sum), strtotime($the_date));
echo date('d M Y', $date);
```
Upvotes: 0 <issue_comment>username_2: strtotime accepts "-7 day" as argument.
I think this may work:
```
$the_date = '16 Mar 2018';
$test_sum = '-7';
$date = strtotime($the_date);
$date = strtotime("$test_sum day", $date);
echo date('d M Y', $date);
```
Upvotes: 1 <issue_comment>username_3: Running:
```
date('d M Y', strtotime('16 Mar 2018 -7 days'))
```
would produce:
```
09 Mar 2018
```
Upvotes: 1 [selected_answer]<issue_comment>username_4: Please try with the following code :
```
$the_date = '16-Mar-2018';
$test_sum = '-7';
echo date('Y-m-d', strtotime($the_date. $test_sum.' days'));
```
Upvotes: 0 <issue_comment>username_5: What you need to use is `strtotime()` what this function does is it gets the string containing an English date format and try to convert it into a Unix timestamp formate which is the number of seconds since 1 of January 1970 00:00:00.
This code should work for you:
```
date('d M Y', strtotime($the_date. $test_sum . ' days'));
```
This makes this `16 Mar 2018` to this `09 Mar 2018`
Hope that this helps.
More about [strtotime](http://php.net/manual/en/function.strtotime.php)
Upvotes: 0
|
2018/03/14
| 657 | 1,920 |
<issue_start>username_0: how to make this image in bootstrap 3....
i will can view this image in mobile view in to three seperate rows and desktop in to one row.
in mobile view each row contains one part of image..
please help me..
```



```
[](https://i.stack.imgur.com/C8TpK.jpg)
this is a psd imge file....<issue_comment>username_1: If you want to subtract days, you can simply use `'-7 days'`. If you don't specify the unit `strtotime()` probably doesn't subtracts days.
```
$the_date = '16 Mar 2018';
$test_sum = -7;
$date = strtotime(sprintf("%d days", $test_sum), strtotime($the_date));
echo date('d M Y', $date);
```
Upvotes: 0 <issue_comment>username_2: strtotime accepts "-7 day" as argument.
I think this may work:
```
$the_date = '16 Mar 2018';
$test_sum = '-7';
$date = strtotime($the_date);
$date = strtotime("$test_sum day", $date);
echo date('d M Y', $date);
```
Upvotes: 1 <issue_comment>username_3: Running:
```
date('d M Y', strtotime('16 Mar 2018 -7 days'))
```
would produce:
```
09 Mar 2018
```
Upvotes: 1 [selected_answer]<issue_comment>username_4: Please try with the following code :
```
$the_date = '16-Mar-2018';
$test_sum = '-7';
echo date('Y-m-d', strtotime($the_date. $test_sum.' days'));
```
Upvotes: 0 <issue_comment>username_5: What you need to use is `strtotime()` what this function does is it gets the string containing an English date format and try to convert it into a Unix timestamp formate which is the number of seconds since 1 of January 1970 00:00:00.
This code should work for you:
```
date('d M Y', strtotime($the_date. $test_sum . ' days'));
```
This makes this `16 Mar 2018` to this `09 Mar 2018`
Hope that this helps.
More about [strtotime](http://php.net/manual/en/function.strtotime.php)
Upvotes: 0
|
2018/03/14
| 1,239 | 5,585 |
<issue_start>username_0: I have a page with a repeater inside a webpart zone to display rotating content (in a carousel). Content for the carousel comes from the /Carousel/ folder, which is a child of the page itself.
What I want to do but don't know how is to set the visibility of the webpart zone based on the presence of the /Carousel/ folder: if the /Carousel/ folder is there -> show the webpart zone/repeater, if not -> hide it. Thanks!<issue_comment>username_1: Since you want to hide the repeater just set the "No data behavior" property of the repeater to hide if nothing is found.
[](https://i.stack.imgur.com/7yU6k.png)
Upvotes: 2 <issue_comment>username_2: I've run into this same thing many times, so i actually built a macro specifically for this type of stuff (since as you've commented, the visibility is on the webpart zone and not the repeater).
Here's the macro method
```
[MacroMethod(typeof(bool), "Finds if at least 1 child exists under the given node for navigation purposes",1 )]
[MacroMethodParam(0, "int", typeof(int), "The Node ID")]
[MacroMethodParam(1, "Text", typeof(string), "A list of valid page types, comma, semi-colon, or bar seperated")]
[MacroMethodParam(2, "bool", typeof(bool), "Include Unpuglished pages (false by default)")]
[MacroMethodParam(3, "bool", typeof(bool), "Include Documents Hidden from Navigation (false by default)")]
public static object NodeHasNavigationChildren(EvaluationContext context, params object[] parameters)
{
switch (parameters.Length)
{
case 1:
return HBS_Gen_Module.GeneralHelpers.NodeHasNavigationChildren(ValidationHelper.GetInteger(parameters[0], -1));
case 2:
return HBS_Gen_Module.GeneralHelpers.NodeHasNavigationChildren(ValidationHelper.GetInteger(parameters[0], -1), ValidationHelper.GetString(parameters[1], ""));
case 3:
return HBS_Gen_Module.GeneralHelpers.NodeHasNavigationChildren(ValidationHelper.GetInteger(parameters[0], -1), ValidationHelper.GetString(parameters[1], ""), ValidationHelper.GetBoolean(parameters[2], false));
case 4:
return HBS_Gen_Module.GeneralHelpers.NodeHasNavigationChildren(ValidationHelper.GetInteger(parameters[0], -1), ValidationHelper.GetString(parameters[1], ""), ValidationHelper.GetBoolean(parameters[2], false), ValidationHelper.GetBoolean(parameters[3], false));
default:
case 0:
throw new NotSupportedException();
}
}
```
And here's the actual method it calls:
```
///
/// Checks if there exists a Node that should be displayed in navigation, this is more advanced than the "NodeHasChildren" which only checks for published children, and doesn't have page type and DocumentHiddenInNavigation checks
///
/// The Node ID
/// Semi-colon, bar, or comma seperated list of class names
/// If unpublished should be included (default false)
/// If Documents hidden from navigation should be included (default false)
/// If there exists at least 1 child that fits
public static bool NodeHasNavigationChildren(int NodeID, string PageTypes = "", bool IncludeUnpublished = false, bool IncludeHiddenNavigationDocuments = false)
{
return CacheHelper.Cache(cs => NodeHasNavigationChildrenCache(cs, NodeID, PageTypes, IncludeUnpublished, IncludeHiddenNavigationDocuments), new CacheSettings(1440, new string[] { "NodeHasNavigationChildren", NodeID.ToString(), PageTypes, IncludeUnpublished.ToString(), IncludeHiddenNavigationDocuments.ToString() }));
}
private static bool NodeHasNavigationChildrenCache(CacheSettings cs, int NodeID, string PageTypes = "", bool IncludeUnpublished = true, bool IncludeHiddenNavigationDocuments = false)
{
var ChildQuery = DocumentHelper.GetDocuments().WhereEquals("NodeParentID", NodeID).Columns("NodeID").TopN(1);
if (IncludeUnpublished)
{
ChildQuery.Published(false);
}
if (IncludeHiddenNavigationDocuments)
{
ChildQuery.Where("DocumentMenuItemHideInNavigation = 0 or DocumentMenuItemHideInNavigation = 1");
}
else
{
ChildQuery.WhereEquals("DocumentMenuItemHideInNavigation", false);
}
if (!string.IsNullOrWhiteSpace(PageTypes))
{
ChildQuery.WhereIn("ClassName", PageTypes.Split(";|,".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
}
if(cs.Cached)
{
TreeNode ParentNode = DocumentHelper.GetDocuments().WhereEquals("NodeID", NodeID).Published(false).FirstObject;
if(ParentNode != null) {
cs.CacheDependency = CacheHelper.GetCacheDependency("node|"+SiteContext.CurrentSiteName+"|" + ParentNode.NodeAliasPath + "|childnodes");
}
}
return ChildQuery.Count > 0;
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: You don't have to implement any custom macro method. You can simply leverage Kentico's default methods like **Exists** in this case:
```
{% CurrentDocument.Children.Exists("DocumentName==\"Carousel\"") %}
```
Upvotes: 1
|
2018/03/14
| 1,308 | 5,764 |
<issue_start>username_0: I have used laravel before when it was 5.4 and I could easily connect to database, Now I want to work in a new project. try to connect to database and get this error.
```
Illuminate\Database\QueryException : SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from information_schema.tables where table_schema = todo and table_name = migrations)
```
I have tried every single trick I have found on stackoverflow. NONE worked.
Why is this happening? this is my connection.
```
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=todo
DB_USERNAME=root
DB_PASSWORD=''
```<issue_comment>username_1: Since you want to hide the repeater just set the "No data behavior" property of the repeater to hide if nothing is found.
[](https://i.stack.imgur.com/7yU6k.png)
Upvotes: 2 <issue_comment>username_2: I've run into this same thing many times, so i actually built a macro specifically for this type of stuff (since as you've commented, the visibility is on the webpart zone and not the repeater).
Here's the macro method
```
[MacroMethod(typeof(bool), "Finds if at least 1 child exists under the given node for navigation purposes",1 )]
[MacroMethodParam(0, "int", typeof(int), "The Node ID")]
[MacroMethodParam(1, "Text", typeof(string), "A list of valid page types, comma, semi-colon, or bar seperated")]
[MacroMethodParam(2, "bool", typeof(bool), "Include Unpuglished pages (false by default)")]
[MacroMethodParam(3, "bool", typeof(bool), "Include Documents Hidden from Navigation (false by default)")]
public static object NodeHasNavigationChildren(EvaluationContext context, params object[] parameters)
{
switch (parameters.Length)
{
case 1:
return HBS_Gen_Module.GeneralHelpers.NodeHasNavigationChildren(ValidationHelper.GetInteger(parameters[0], -1));
case 2:
return HBS_Gen_Module.GeneralHelpers.NodeHasNavigationChildren(ValidationHelper.GetInteger(parameters[0], -1), ValidationHelper.GetString(parameters[1], ""));
case 3:
return HBS_Gen_Module.GeneralHelpers.NodeHasNavigationChildren(ValidationHelper.GetInteger(parameters[0], -1), ValidationHelper.GetString(parameters[1], ""), ValidationHelper.GetBoolean(parameters[2], false));
case 4:
return HBS_Gen_Module.GeneralHelpers.NodeHasNavigationChildren(ValidationHelper.GetInteger(parameters[0], -1), ValidationHelper.GetString(parameters[1], ""), ValidationHelper.GetBoolean(parameters[2], false), ValidationHelper.GetBoolean(parameters[3], false));
default:
case 0:
throw new NotSupportedException();
}
}
```
And here's the actual method it calls:
```
///
/// Checks if there exists a Node that should be displayed in navigation, this is more advanced than the "NodeHasChildren" which only checks for published children, and doesn't have page type and DocumentHiddenInNavigation checks
///
/// The Node ID
/// Semi-colon, bar, or comma seperated list of class names
/// If unpublished should be included (default false)
/// If Documents hidden from navigation should be included (default false)
/// If there exists at least 1 child that fits
public static bool NodeHasNavigationChildren(int NodeID, string PageTypes = "", bool IncludeUnpublished = false, bool IncludeHiddenNavigationDocuments = false)
{
return CacheHelper.Cache(cs => NodeHasNavigationChildrenCache(cs, NodeID, PageTypes, IncludeUnpublished, IncludeHiddenNavigationDocuments), new CacheSettings(1440, new string[] { "NodeHasNavigationChildren", NodeID.ToString(), PageTypes, IncludeUnpublished.ToString(), IncludeHiddenNavigationDocuments.ToString() }));
}
private static bool NodeHasNavigationChildrenCache(CacheSettings cs, int NodeID, string PageTypes = "", bool IncludeUnpublished = true, bool IncludeHiddenNavigationDocuments = false)
{
var ChildQuery = DocumentHelper.GetDocuments().WhereEquals("NodeParentID", NodeID).Columns("NodeID").TopN(1);
if (IncludeUnpublished)
{
ChildQuery.Published(false);
}
if (IncludeHiddenNavigationDocuments)
{
ChildQuery.Where("DocumentMenuItemHideInNavigation = 0 or DocumentMenuItemHideInNavigation = 1");
}
else
{
ChildQuery.WhereEquals("DocumentMenuItemHideInNavigation", false);
}
if (!string.IsNullOrWhiteSpace(PageTypes))
{
ChildQuery.WhereIn("ClassName", PageTypes.Split(";|,".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
}
if(cs.Cached)
{
TreeNode ParentNode = DocumentHelper.GetDocuments().WhereEquals("NodeID", NodeID).Published(false).FirstObject;
if(ParentNode != null) {
cs.CacheDependency = CacheHelper.GetCacheDependency("node|"+SiteContext.CurrentSiteName+"|" + ParentNode.NodeAliasPath + "|childnodes");
}
}
return ChildQuery.Count > 0;
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: You don't have to implement any custom macro method. You can simply leverage Kentico's default methods like **Exists** in this case:
```
{% CurrentDocument.Children.Exists("DocumentName==\"Carousel\"") %}
```
Upvotes: 1
|
2018/03/14
| 753 | 2,935 |
<issue_start>username_0: I have an existing fragment in xml format as below
```
```
Now I have activity class where in oncreateview I have below code -
```
View rootView = inflater.inflate(R.layout.fragment_above_fragmentView, container, false);
LinearLayuot llayout = (LinearLayout) rootView.findViewById(R.id.phoneLinearLyout);
```
And I am trying to TextView in linearlayout Fragment\_above\_fragmentView (as mentioned in the first XML posted) dynamically with following code .
```
for (int i=0;i<2(variable here);i++)
{
contactDisplay = (TextView) rootView.findViewById(R.id.contanctNumberValue);
contactDisplay.setTypeface(typeface);
contactDisplay.setText(dataModel.getTelNo());
//contactDisplay.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
llayout.addView(contactDisplay);
//phoneLinearLyout.updateViewLayout(contactDisplay,);
}
```
But, facing an error as Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first and application gets crashed.<issue_comment>username_1: you just have to removeAllViews before adding view to layout :
```
llayout.removeAllViews(); //add this
for (int i=0;i<2(variable here);i++)
{
contactDisplay = (TextView) rootView.findViewById(R.id.contanctNumberValue);
contactDisplay.setTypeface(typeface);
contactDisplay.setText(dataModel.getTelNo());
//contactDisplay.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
llayout.addView(contactDisplay);
//phoneLinearLyout.updateViewLayout(contactDisplay,);
}
```
Upvotes: 0 <issue_comment>username_2: for (int i=0;i<2(variable here);i++)
{
```
contactDisplay = (TextView) rootView.findViewById(R.id.contanctNumberValue);
contactDisplay.setTypeface(typeface);
```
if(contactDisplay.getParent()!=null)
((ViewGroup)tv.getParent()).removeView(contactDisplay);
```
contactDisplay.setText(dataModel.getTelNo());
//contactDisplay.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
llayout.addView(contactDisplay);
//phoneLinearLyout.updateViewLayout(contactDisplay,);
}
```
Upvotes: 0 <issue_comment>username_3: You should create a new `TextView` and add into llayout.
```js
for (int i=0;i<2(variable here);i++)
{
TextView contactDisplay = new TextView(getApplicationContext());
contactDisplay.setTypeface(typeface);
contactDisplay.setText(dataModel.getTelNo());
llayout.addView(contactDisplay);
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_4: Created textview each time rather than pointing to the same one which is already used.
Upvotes: 0
|
2018/03/14
| 682 | 2,550 |
<issue_start>username_0: I'm going to integrate a slf4j implementation (framework in company based on logback) into spring boot 2.0.
In my progress I found the default logback dependency is conflict to my own dependency. Excluded `spring-boot-starter-logging` module in this way:
```
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-logging
```
the conflicting error disappeared but it seems like spring boot use my library as the slf4j logging implementation just the way before, nothing in my custom functions works.
I'm wondering if there is a way I can replace the logging system with my code to make it work but no references about this are found in spring.io website.<issue_comment>username_1: To disable Spring Boot's LoggingSystem, which defaults to LogbackLoggingSystem, you need to set the following system property
```
-Dorg.springframework.boot.logging.LoggingSystem=none
```
This is in <https://docs.spring.io/spring-boot/docs/current/reference/html/howto-logging.html> and <https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html> for reference.
Upvotes: 2 <issue_comment>username_2: The error
```
Exception in thread "main" java.lang.StackOverflowError
at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:936)
```
generated by call-loop with log4j-sl4j-impl and log4j-to-sl4j.
You can resolve excluding log4j-to-slf4j:
```
configurations {
all*.exclude group: 'org.apache.logging.log4j', module: 'log4j-to-slf4j'
}
```
Upvotes: 0 <issue_comment>username_3: **Remove login default dependency in the Spring-boot-starter-web project**
```
dependency>
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-logging
org.springframework.boot
spring-boot-starter-log4j2
```
we need to place in the classpath a file named like one of the following properties file and restart the project
1. log4j2-spring.xml
2. log4j2.xml
Upvotes: 2 <issue_comment>username_4: You have given only a portion of your pom.xml file. The problem may be that, there may be a transitive dependency to logback from some other dependency. So you have to make the same exclusion in that dependency too as in the case of spring-boot-starter. Now in order to know which all dependencies have this transitivity, you can print the dependency tree of your pom.xml file. For that go to the folder that contains pom.xml. Open command prompt.
And type **mvn dependency: tree** .
Upvotes: 0
|
2018/03/14
| 742 | 2,482 |
<issue_start>username_0: I have an Excel sheet like this
```
Listener_name Listener IP Listener Service
server1 12.xx.xx.xx java
server2 12.xx.xx.xx java
server3 127.0.0.1 oracle
```
and I want to print all values for Listener `IP` column.
My current Python code looks like this:
```
book = openpyxl.load_workbook('report-201808March0709AM522986.xlsx')
sheet = book.active
a1 = sheet['J1']
a2 = sheet['J2']
a3 = sheet['J3']
print(a1.value)
print(a2.value)
print(a3.value)
```
but it's only 3 columns of values and I have more than 200 values. Is there any way we can print all values using a loop?<issue_comment>username_1: To disable Spring Boot's LoggingSystem, which defaults to LogbackLoggingSystem, you need to set the following system property
```
-Dorg.springframework.boot.logging.LoggingSystem=none
```
This is in <https://docs.spring.io/spring-boot/docs/current/reference/html/howto-logging.html> and <https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html> for reference.
Upvotes: 2 <issue_comment>username_2: The error
```
Exception in thread "main" java.lang.StackOverflowError
at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:936)
```
generated by call-loop with log4j-sl4j-impl and log4j-to-sl4j.
You can resolve excluding log4j-to-slf4j:
```
configurations {
all*.exclude group: 'org.apache.logging.log4j', module: 'log4j-to-slf4j'
}
```
Upvotes: 0 <issue_comment>username_3: **Remove login default dependency in the Spring-boot-starter-web project**
```
dependency>
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-logging
org.springframework.boot
spring-boot-starter-log4j2
```
we need to place in the classpath a file named like one of the following properties file and restart the project
1. log4j2-spring.xml
2. log4j2.xml
Upvotes: 2 <issue_comment>username_4: You have given only a portion of your pom.xml file. The problem may be that, there may be a transitive dependency to logback from some other dependency. So you have to make the same exclusion in that dependency too as in the case of spring-boot-starter. Now in order to know which all dependencies have this transitivity, you can print the dependency tree of your pom.xml file. For that go to the folder that contains pom.xml. Open command prompt.
And type **mvn dependency: tree** .
Upvotes: 0
|
2018/03/14
| 602 | 2,217 |
<issue_start>username_0: The animation does not work and the completion block is called right away. If I comment the code inside the completion block, everything runs as it should.
```
[UIView animateWithDuration:0.3 animations:^{
self.waitingAnchorAcceptView.alpha = 0;
} completion:^(BOOL finished) {
[self.waitingAnchorAcceptView removeFromSuperview];
}];
```<issue_comment>username_1: To disable Spring Boot's LoggingSystem, which defaults to LogbackLoggingSystem, you need to set the following system property
```
-Dorg.springframework.boot.logging.LoggingSystem=none
```
This is in <https://docs.spring.io/spring-boot/docs/current/reference/html/howto-logging.html> and <https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html> for reference.
Upvotes: 2 <issue_comment>username_2: The error
```
Exception in thread "main" java.lang.StackOverflowError
at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:936)
```
generated by call-loop with log4j-sl4j-impl and log4j-to-sl4j.
You can resolve excluding log4j-to-slf4j:
```
configurations {
all*.exclude group: 'org.apache.logging.log4j', module: 'log4j-to-slf4j'
}
```
Upvotes: 0 <issue_comment>username_3: **Remove login default dependency in the Spring-boot-starter-web project**
```
dependency>
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-logging
org.springframework.boot
spring-boot-starter-log4j2
```
we need to place in the classpath a file named like one of the following properties file and restart the project
1. log4j2-spring.xml
2. log4j2.xml
Upvotes: 2 <issue_comment>username_4: You have given only a portion of your pom.xml file. The problem may be that, there may be a transitive dependency to logback from some other dependency. So you have to make the same exclusion in that dependency too as in the case of spring-boot-starter. Now in order to know which all dependencies have this transitivity, you can print the dependency tree of your pom.xml file. For that go to the folder that contains pom.xml. Open command prompt.
And type **mvn dependency: tree** .
Upvotes: 0
|
2018/03/14
| 5,264 | 16,116 |
<issue_start>username_0: Would like to ask for help on my jquery. I've saw a bug regarding my drop-down button. When I open a drop-down button, it opens with a negative symbol as sign of dropdown menu but when I click another drop-down button, it also open with the same symbol but my previous doesn't reset to its normal form with positive symbol.
Here's a screenshot of what I meant.
[](https://i.stack.imgur.com/n9mOJ.png)
Here'y my Codes:
```js
$(document).ready(function() {
$(".dropdown-toggle").click(function(e) {
e.preventDefault();
$('.dropdown-menu').not($(this).next('.dropdown-menu')).fadeOut()
$(this).next('.dropdown-menu').fadeToggle().toggleClass('isOpen');
if ($('.dropdown-menu').hasClass('isOpen')) {
$(this).html("-");
$(this).siblings('a').css("color", "#f37727");
} else {
$(this).html("+");
$(this).siblings('a').css("color", "#000");
}
});
});
```
```html
* [Dogs](/collections/dogs)
+ [Dog Beds & Bedding](/collections/dog-beds-and-bedding)
-
- [Soft Dog Beds](/collections/soft-dog-beds)
- [Mattress Dog Beds](/collections/mattress-dog-beds)
- [Plastic Dog Beds and Cushions](/collections/plastic-dog-beds-and-cushions)
- [3 Peaks](/collections/3-peaks)
- [Luxury Dog Beds](/collections/luxury-dog-beds)
- [Dog Blankets](/collections/dog-blankets)
- [Specific Dog Beds](/collections/specific-dog-beds)
+ [Dog Coats & Clothes](/collections/dog-coats-and-clothes)
-
- [Dog Heating and Cooling Beds](/collections/dog-heating-and-cooling-beds)
- [Dog Cooling and Calming](/collections/dog-cooling-and-calming)
- [Dog Knitwear](/collections/dog-knitwear)
- [Dog Rainwear](/collections/dog-rainwear)
- [Dog Reflective Coats](/collections/dog-reflective-coats)
- [Dog Warmwear](/collections/dog-warmwear)
- [Small Dog Coats](/collections/small-dog-coats)
+ [Dog Collars and Leads](/collections/dog-collars)
+
- [Dog Collars](/collections/dog-collars)
- [Dog Leads](/collections/dog-leads)
- [Dog Extending Leads](/collections/dog-extending-leads)
- [Dog Tags & Accessories](/collections/dog-tags-accessories)
+ [Dog Flea Control & Wormers](/collections/dog-flea-control-and-wormers)
+
- [Dog Flea Treatment](/collections/dog-flea-treatment)
- [Dog Wormers](/collections/dog-wormers)
+ [Dog Grooming](/collections/dog-grooming)
+
- [Dog Clippers and Scissors](/collections/dog-clippers-and-scissors)
- [Dog Nail Clippers](/collections/dog-nail-clippers)
- [Dog Shampoo & Conditioners](/collections/dog-shampoo-conditioners)
- [Dog Brushes & Combs](/collections/dog-brushes-combs)
- [Dog Sprays & Hygiene Products](/collections/dog-sprays-hygiene-products)
- [Dog Towels](/collections/dog-towels)
+ [Dog Harness](/collections/dog-harness)
+
+ [Dog Health & Treatments](/collections/dog-health-and-treatments)
+
- [Dog Dental Care](/collections/dog-dental-care)
- [Dog Ear Care](/collections/dog-ear-care)
- [Dog Health Supplements](/collections/dog-health-supplements)
- [Dog Skin and Creams](/collections/dog-skin-and-creams)
+ [Dog Kennels & Flaps](/collections/dog-kennels-and-flaps)
+
- [Dog Kennels](/collections/dog-kennels)
- [Dog Pens](/collections/dog-pens)
- [Dog Flaps and Gates](/collections/dog-flaps-and-gates)
- [Dog Carriers](/collections/dog-carriers)
+ [Dog Leads](/collections/dog-leads)
+
+ [Dog Tags](/collections/dog-tags)
+
+ [Dog Toys](/collections/dog-toys)
+
- [Ball and Outdoor](/collections/ball-and-outdoor)
- [Brain Games](/collections/brain-games)
- [Dog Chews](/collections/dog-chews)
- [Dog Novelty Toys](/collections/dog-novelty-toys)
- [Dog Top Toys](/collections/dog-top-toys)
- [Toys For Puppys](/collections/toys-for-puppys)
- [Dog Soft Toys](/collections/dog-soft-toys)
- [Dog Tougher Toys](/collections/dog-tougher-toys)
+ [Dog Training](/collections/dog-training)
+
- [Dog Anti-Bark Accessories](/collections/dog-anti-bark-accessories)
- [Dog Muzzles](/collections/dog-muzzles)
- [Dog Clicker And Whistle Training](/collections/dog-clicker-and-whistle-training)
- [Dog Chewing Solutions](/collections/dog-chewing-solutions)
- [Dog Toilet Training](/collections/dog-toilet-training)
- [Dog Agility Training](/collections/dog-agility-training)
- [Other Training Solutions](/collections/other-training-solutions)
+ [Dog Travel](/collections/dog-travel)
+
+ [Puppy Products](/collections/puppy-products)
+
```<issue_comment>username_1: Try running a $.each loop on `.dropdown-menu` instead of just a singular `hasClass` check , see below code:
```
$(document).ready(function() {
$(".dropdown-toggle").click(function(e) {
e.preventDefault();
$('.dropdown-menu').not($(this).next('.dropdown-menu')).fadeOut()
$(this).next('.dropdown-menu').fadeToggle().toggleClass('isOpen');
$('.dropdown-menu').each(function(){
if($(this)..hasClass('isOpen')) {
$(this).html("-").siblings('a').css("color", "#f37727");
} else {
$(this).html("+").siblings('a').css("color", "#000");
}
});
});
});
```
Below is the newly added code:
```
$('.dropdown-menu').each(function(){
if($(this).hasClass('isOpen')) {
$(this).html("-").siblings('a').css("color", "#f37727");
} else {
$(this).html("+").siblings('a').css("color", "#000");
}
});
```
Upvotes: 0 <issue_comment>username_2: you are really near to it. but i think you just forgot this line
`if($(this).hasClass('isOpen'))`
`dropdown-menu` never have class `isOpen`. the next element is the one which have it. so the correct script is :
`if($(this).next().hasClass('isOpen'))`
here your fiddle after fixed
```js
$(document).ready(function() {
$(".dropdown-toggle").click(function(e) {
e.preventDefault();
$('.dropdown-menu').not($(this).next('.dropdown-menu')).fadeOut()
$(this).next('.dropdown-menu').fadeToggle().toggleClass('isOpen');
var parentLi = $(this).closest('li');
if ($(this).next('.dropdown-menu').hasClass('isOpen')) {
$(this).html("-");
$(this).siblings('a').css("color", "#f37727");
} else {
$(this).html("+");
$(this).siblings('a').css("color", "#000");
}
});
});
```
```html
* [Dogs](/collections/dogs)
+ [Dog Beds & Bedding](/collections/dog-beds-and-bedding)
+
- [Soft Dog Beds](/collections/soft-dog-beds)
- [Mattress Dog Beds](/collections/mattress-dog-beds)
- [Plastic Dog Beds and Cushions](/collections/plastic-dog-beds-and-cushions)
- [3 Peaks](/collections/3-peaks)
- [Luxury Dog Beds](/collections/luxury-dog-beds)
- [Dog Blankets](/collections/dog-blankets)
- [Specific Dog Beds](/collections/specific-dog-beds)
+ [Dog Coats & Clothes](/collections/dog-coats-and-clothes)
-
- [Dog Heating and Cooling Beds](/collections/dog-heating-and-cooling-beds)
- [Dog Cooling and Calming](/collections/dog-cooling-and-calming)
- [Dog Knitwear](/collections/dog-knitwear)
- [Dog Rainwear](/collections/dog-rainwear)
- [Dog Reflective Coats](/collections/dog-reflective-coats)
- [Dog Warmwear](/collections/dog-warmwear)
- [Small Dog Coats](/collections/small-dog-coats)
+ [Dog Collars and Leads](/collections/dog-collars)
+
- [Dog Collars](/collections/dog-collars)
- [Dog Leads](/collections/dog-leads)
- [Dog Extending Leads](/collections/dog-extending-leads)
- [Dog Tags & Accessories](/collections/dog-tags-accessories)
+ [Dog Flea Control & Wormers](/collections/dog-flea-control-and-wormers)
+
- [Dog Flea Treatment](/collections/dog-flea-treatment)
- [Dog Wormers](/collections/dog-wormers)
+ [Dog Grooming](/collections/dog-grooming)
+
- [Dog Clippers and Scissors](/collections/dog-clippers-and-scissors)
- [Dog Nail Clippers](/collections/dog-nail-clippers)
- [Dog Shampoo & Conditioners](/collections/dog-shampoo-conditioners)
- [Dog Brushes & Combs](/collections/dog-brushes-combs)
- [Dog Sprays & Hygiene Products](/collections/dog-sprays-hygiene-products)
- [Dog Towels](/collections/dog-towels)
+ [Dog Harness](/collections/dog-harness)
+
+ [Dog Health & Treatments](/collections/dog-health-and-treatments)
+
- [Dog Dental Care](/collections/dog-dental-care)
- [Dog Ear Care](/collections/dog-ear-care)
- [Dog Health Supplements](/collections/dog-health-supplements)
- [Dog Skin and Creams](/collections/dog-skin-and-creams)
+ [Dog Kennels & Flaps](/collections/dog-kennels-and-flaps)
+
- [Dog Kennels](/collections/dog-kennels)
- [Dog Pens](/collections/dog-pens)
- [Dog Flaps and Gates](/collections/dog-flaps-and-gates)
- [Dog Carriers](/collections/dog-carriers)
+ [Dog Leads](/collections/dog-leads)
+
+ [Dog Tags](/collections/dog-tags)
+
+ [Dog Toys](/collections/dog-toys)
+
- [Ball and Outdoor](/collections/ball-and-outdoor)
- [Brain Games](/collections/brain-games)
- [Dog Chews](/collections/dog-chews)
- [Dog Novelty Toys](/collections/dog-novelty-toys)
- [Dog Top Toys](/collections/dog-top-toys)
- [Toys For Puppys](/collections/toys-for-puppys)
- [Dog Soft Toys](/collections/dog-soft-toys)
- [Dog Tougher Toys](/collections/dog-tougher-toys)
+ [Dog Training](/collections/dog-training)
+
- [Dog Anti-Bark Accessories](/collections/dog-anti-bark-accessories)
- [Dog Muzzles](/collections/dog-muzzles)
- [Dog Clicker And Whistle Training](/collections/dog-clicker-and-whistle-training)
- [Dog Chewing Solutions](/collections/dog-chewing-solutions)
- [Dog Toilet Training](/collections/dog-toilet-training)
- [Dog Agility Training](/collections/dog-agility-training)
- [Other Training Solutions](/collections/other-training-solutions)
+ [Dog Travel](/collections/dog-travel)
+
+ [Puppy Products](/collections/puppy-products)
+
```
Upvotes: 0 <issue_comment>username_3: Make the logic is simple. Initially you want to show some menu's in open status. So you have to keep the `isOpen` class for the particular list items and keep the symbol `-` for the buttons and apply the color code for the `a`. Through CSS, try to apply the `display` properties like if the list items have the class `isOpen` then make it `display:block` othewise `display:none` like below.
```
.dropdown-menu {
display:none;
}
.dropdown-menu.isOpen {
display:block;
}
```
Now if you click some button, you have to remove the `isOpen` class from the other list items and keep this class only for the current list items. Also you have to make the button `+` for others and `-` for the current. For links you have to apply different color for the current one and keep default one for the remaining. This you can achieve using the following code.
```
$(".dropdown-toggle").click(function(e) {
e.preventDefault();
$('.dropdown-menu').not($(this).next('.dropdown-menu')).fadeOut();
$('.dropdown-menu').removeClass('isOpen');
$('.dropdown-menu').siblings('button').html("+");
$('.dropdown-menu').siblings('a').css("color", "#000");
$(this).next('.dropdown-menu').fadeToggle().addClass('isOpen');
$(this).html("-");
$(this).siblings('a').css("color", "#f37727");
});
```
**EDIT**
The above will fail in one scenario like if you click the same button again then it is showing the wrong `-` button symbol and the wrong color code of `a` tag. For fix that I am checking the current status then updating the style of the current element like below.
```js
$(document).ready(function() {
$(".dropdown-toggle").click(function(e) {
e.preventDefault();
var close = $(this).html() == "-" ? false : true;
$('.dropdown-menu').not($(this).next('.dropdown-menu')).fadeOut();
$(this).next('.dropdown-menu').fadeToggle();
$('.dropdown-menu').removeClass('isOpen');
$('.dropdown-menu').siblings('button').html("+");
$('.dropdown-menu').siblings('a').css("color", "#000");
if(close) {
$(this).html("-");
$(this).siblings('a').css("color", "#f37727");
}
});
});
```
```css
.dropdown-menu {
display:none;
}
.dropdown-menu.isOpen {
display:block;
}
```
```html
* [Dogs](/collections/dogs)
+ [Dog Beds & Bedding](/collections/dog-beds-and-bedding)
-
- [Soft Dog Beds](/collections/soft-dog-beds)
- [Mattress Dog Beds](/collections/mattress-dog-beds)
- [Plastic Dog Beds and Cushions](/collections/plastic-dog-beds-and-cushions)
- [3 Peaks](/collections/3-peaks)
- [Luxury Dog Beds](/collections/luxury-dog-beds)
- [Dog Blankets](/collections/dog-blankets)
- [Specific Dog Beds](/collections/specific-dog-beds)
+ [Dog Coats & Clothes](/collections/dog-coats-and-clothes)
-
- [Dog Heating and Cooling Beds](/collections/dog-heating-and-cooling-beds)
- [Dog Cooling and Calming](/collections/dog-cooling-and-calming)
- [Dog Knitwear](/collections/dog-knitwear)
- [Dog Rainwear](/collections/dog-rainwear)
- [Dog Reflective Coats](/collections/dog-reflective-coats)
- [Dog Warmwear](/collections/dog-warmwear)
- [Small Dog Coats](/collections/small-dog-coats)
+ [Dog Collars and Leads](/collections/dog-collars)
+
- [Dog Collars](/collections/dog-collars)
- [Dog Leads](/collections/dog-leads)
- [Dog Extending Leads](/collections/dog-extending-leads)
- [Dog Tags & Accessories](/collections/dog-tags-accessories)
+ [Dog Flea Control & Wormers](/collections/dog-flea-control-and-wormers)
+
- [Dog Flea Treatment](/collections/dog-flea-treatment)
- [Dog Wormers](/collections/dog-wormers)
+ [Dog Grooming](/collections/dog-grooming)
+
- [Dog Clippers and Scissors](/collections/dog-clippers-and-scissors)
- [Dog Nail Clippers](/collections/dog-nail-clippers)
- [Dog Shampoo & Conditioners](/collections/dog-shampoo-conditioners)
- [Dog Brushes & Combs](/collections/dog-brushes-combs)
- [Dog Sprays & Hygiene Products](/collections/dog-sprays-hygiene-products)
- [Dog Towels](/collections/dog-towels)
+ [Dog Harness](/collections/dog-harness)
+
+ [Dog Health & Treatments](/collections/dog-health-and-treatments)
-
- [Dog Dental Care](/collections/dog-dental-care)
- [Dog Ear Care](/collections/dog-ear-care)
- [Dog Health Supplements](/collections/dog-health-supplements)
- [Dog Skin and Creams](/collections/dog-skin-and-creams)
+ [Dog Kennels & Flaps](/collections/dog-kennels-and-flaps)
+
- [Dog Kennels](/collections/dog-kennels)
- [Dog Pens](/collections/dog-pens)
- [Dog Flaps and Gates](/collections/dog-flaps-and-gates)
- [Dog Carriers](/collections/dog-carriers)
+ [Dog Leads](/collections/dog-leads)
+
+ [Dog Tags](/collections/dog-tags)
+
+ [Dog Toys](/collections/dog-toys)
+
- [Ball and Outdoor](/collections/ball-and-outdoor)
- [Brain Games](/collections/brain-games)
- [Dog Chews](/collections/dog-chews)
- [Dog Novelty Toys](/collections/dog-novelty-toys)
- [Dog Top Toys](/collections/dog-top-toys)
- [Toys For Puppys](/collections/toys-for-puppys)
- [Dog Soft Toys](/collections/dog-soft-toys)
- [Dog Tougher Toys](/collections/dog-tougher-toys)
+ [Dog Training](/collections/dog-training)
+
- [Dog Anti-Bark Accessories](/collections/dog-anti-bark-accessories)
- [Dog Muzzles](/collections/dog-muzzles)
- [Dog Clicker And Whistle Training](/collections/dog-clicker-and-whistle-training)
- [Dog Chewing Solutions](/collections/dog-chewing-solutions)
- [Dog Toilet Training](/collections/dog-toilet-training)
- [Dog Agility Training](/collections/dog-agility-training)
- [Other Training Solutions](/collections/other-training-solutions)
+ [Dog Travel](/collections/dog-travel)
+
+ [Puppy Products](/collections/puppy-products)
+
```
If you are looking for the fiddle version demo, then [**Here you go.**](https://jsfiddle.net/h917zcoa/49/)
Upvotes: 2 [selected_answer]
|
2018/03/14
| 3,855 | 11,940 |
<issue_start>username_0: How could I hide the nav bar when I click the link? here is my code below. I am trying some of the codes provided here in stackoverflow but it didn't works. can you help me with my problem.
```html
[](#page-top)
*
* [About](#about)
* [What we offer](#offer)
* [What we offer](#offer1)
* [Project](#photos)
* [Blogs](#blogs)
* [Blogs](#blogs1)
* [Events](#event)
* [Contact](#contact)
```<issue_comment>username_1: Try running a $.each loop on `.dropdown-menu` instead of just a singular `hasClass` check , see below code:
```
$(document).ready(function() {
$(".dropdown-toggle").click(function(e) {
e.preventDefault();
$('.dropdown-menu').not($(this).next('.dropdown-menu')).fadeOut()
$(this).next('.dropdown-menu').fadeToggle().toggleClass('isOpen');
$('.dropdown-menu').each(function(){
if($(this)..hasClass('isOpen')) {
$(this).html("-").siblings('a').css("color", "#f37727");
} else {
$(this).html("+").siblings('a').css("color", "#000");
}
});
});
});
```
Below is the newly added code:
```
$('.dropdown-menu').each(function(){
if($(this).hasClass('isOpen')) {
$(this).html("-").siblings('a').css("color", "#f37727");
} else {
$(this).html("+").siblings('a').css("color", "#000");
}
});
```
Upvotes: 0 <issue_comment>username_2: you are really near to it. but i think you just forgot this line
`if($(this).hasClass('isOpen'))`
`dropdown-menu` never have class `isOpen`. the next element is the one which have it. so the correct script is :
`if($(this).next().hasClass('isOpen'))`
here your fiddle after fixed
```js
$(document).ready(function() {
$(".dropdown-toggle").click(function(e) {
e.preventDefault();
$('.dropdown-menu').not($(this).next('.dropdown-menu')).fadeOut()
$(this).next('.dropdown-menu').fadeToggle().toggleClass('isOpen');
var parentLi = $(this).closest('li');
if ($(this).next('.dropdown-menu').hasClass('isOpen')) {
$(this).html("-");
$(this).siblings('a').css("color", "#f37727");
} else {
$(this).html("+");
$(this).siblings('a').css("color", "#000");
}
});
});
```
```html
* [Dogs](/collections/dogs)
+ [Dog Beds & Bedding](/collections/dog-beds-and-bedding)
+
- [Soft Dog Beds](/collections/soft-dog-beds)
- [Mattress Dog Beds](/collections/mattress-dog-beds)
- [Plastic Dog Beds and Cushions](/collections/plastic-dog-beds-and-cushions)
- [3 Peaks](/collections/3-peaks)
- [Luxury Dog Beds](/collections/luxury-dog-beds)
- [Dog Blankets](/collections/dog-blankets)
- [Specific Dog Beds](/collections/specific-dog-beds)
+ [Dog Coats & Clothes](/collections/dog-coats-and-clothes)
-
- [Dog Heating and Cooling Beds](/collections/dog-heating-and-cooling-beds)
- [Dog Cooling and Calming](/collections/dog-cooling-and-calming)
- [Dog Knitwear](/collections/dog-knitwear)
- [Dog Rainwear](/collections/dog-rainwear)
- [Dog Reflective Coats](/collections/dog-reflective-coats)
- [Dog Warmwear](/collections/dog-warmwear)
- [Small Dog Coats](/collections/small-dog-coats)
+ [Dog Collars and Leads](/collections/dog-collars)
+
- [Dog Collars](/collections/dog-collars)
- [Dog Leads](/collections/dog-leads)
- [Dog Extending Leads](/collections/dog-extending-leads)
- [Dog Tags & Accessories](/collections/dog-tags-accessories)
+ [Dog Flea Control & Wormers](/collections/dog-flea-control-and-wormers)
+
- [Dog Flea Treatment](/collections/dog-flea-treatment)
- [Dog Wormers](/collections/dog-wormers)
+ [Dog Grooming](/collections/dog-grooming)
+
- [Dog Clippers and Scissors](/collections/dog-clippers-and-scissors)
- [Dog Nail Clippers](/collections/dog-nail-clippers)
- [Dog Shampoo & Conditioners](/collections/dog-shampoo-conditioners)
- [Dog Brushes & Combs](/collections/dog-brushes-combs)
- [Dog Sprays & Hygiene Products](/collections/dog-sprays-hygiene-products)
- [Dog Towels](/collections/dog-towels)
+ [Dog Harness](/collections/dog-harness)
+
+ [Dog Health & Treatments](/collections/dog-health-and-treatments)
+
- [Dog Dental Care](/collections/dog-dental-care)
- [Dog Ear Care](/collections/dog-ear-care)
- [Dog Health Supplements](/collections/dog-health-supplements)
- [Dog Skin and Creams](/collections/dog-skin-and-creams)
+ [Dog Kennels & Flaps](/collections/dog-kennels-and-flaps)
+
- [Dog Kennels](/collections/dog-kennels)
- [Dog Pens](/collections/dog-pens)
- [Dog Flaps and Gates](/collections/dog-flaps-and-gates)
- [Dog Carriers](/collections/dog-carriers)
+ [Dog Leads](/collections/dog-leads)
+
+ [Dog Tags](/collections/dog-tags)
+
+ [Dog Toys](/collections/dog-toys)
+
- [Ball and Outdoor](/collections/ball-and-outdoor)
- [Brain Games](/collections/brain-games)
- [Dog Chews](/collections/dog-chews)
- [Dog Novelty Toys](/collections/dog-novelty-toys)
- [Dog Top Toys](/collections/dog-top-toys)
- [Toys For Puppys](/collections/toys-for-puppys)
- [Dog Soft Toys](/collections/dog-soft-toys)
- [Dog Tougher Toys](/collections/dog-tougher-toys)
+ [Dog Training](/collections/dog-training)
+
- [Dog Anti-Bark Accessories](/collections/dog-anti-bark-accessories)
- [Dog Muzzles](/collections/dog-muzzles)
- [Dog Clicker And Whistle Training](/collections/dog-clicker-and-whistle-training)
- [Dog Chewing Solutions](/collections/dog-chewing-solutions)
- [Dog Toilet Training](/collections/dog-toilet-training)
- [Dog Agility Training](/collections/dog-agility-training)
- [Other Training Solutions](/collections/other-training-solutions)
+ [Dog Travel](/collections/dog-travel)
+
+ [Puppy Products](/collections/puppy-products)
+
```
Upvotes: 0 <issue_comment>username_3: Make the logic is simple. Initially you want to show some menu's in open status. So you have to keep the `isOpen` class for the particular list items and keep the symbol `-` for the buttons and apply the color code for the `a`. Through CSS, try to apply the `display` properties like if the list items have the class `isOpen` then make it `display:block` othewise `display:none` like below.
```
.dropdown-menu {
display:none;
}
.dropdown-menu.isOpen {
display:block;
}
```
Now if you click some button, you have to remove the `isOpen` class from the other list items and keep this class only for the current list items. Also you have to make the button `+` for others and `-` for the current. For links you have to apply different color for the current one and keep default one for the remaining. This you can achieve using the following code.
```
$(".dropdown-toggle").click(function(e) {
e.preventDefault();
$('.dropdown-menu').not($(this).next('.dropdown-menu')).fadeOut();
$('.dropdown-menu').removeClass('isOpen');
$('.dropdown-menu').siblings('button').html("+");
$('.dropdown-menu').siblings('a').css("color", "#000");
$(this).next('.dropdown-menu').fadeToggle().addClass('isOpen');
$(this).html("-");
$(this).siblings('a').css("color", "#f37727");
});
```
**EDIT**
The above will fail in one scenario like if you click the same button again then it is showing the wrong `-` button symbol and the wrong color code of `a` tag. For fix that I am checking the current status then updating the style of the current element like below.
```js
$(document).ready(function() {
$(".dropdown-toggle").click(function(e) {
e.preventDefault();
var close = $(this).html() == "-" ? false : true;
$('.dropdown-menu').not($(this).next('.dropdown-menu')).fadeOut();
$(this).next('.dropdown-menu').fadeToggle();
$('.dropdown-menu').removeClass('isOpen');
$('.dropdown-menu').siblings('button').html("+");
$('.dropdown-menu').siblings('a').css("color", "#000");
if(close) {
$(this).html("-");
$(this).siblings('a').css("color", "#f37727");
}
});
});
```
```css
.dropdown-menu {
display:none;
}
.dropdown-menu.isOpen {
display:block;
}
```
```html
* [Dogs](/collections/dogs)
+ [Dog Beds & Bedding](/collections/dog-beds-and-bedding)
-
- [Soft Dog Beds](/collections/soft-dog-beds)
- [Mattress Dog Beds](/collections/mattress-dog-beds)
- [Plastic Dog Beds and Cushions](/collections/plastic-dog-beds-and-cushions)
- [3 Peaks](/collections/3-peaks)
- [Luxury Dog Beds](/collections/luxury-dog-beds)
- [Dog Blankets](/collections/dog-blankets)
- [Specific Dog Beds](/collections/specific-dog-beds)
+ [Dog Coats & Clothes](/collections/dog-coats-and-clothes)
-
- [Dog Heating and Cooling Beds](/collections/dog-heating-and-cooling-beds)
- [Dog Cooling and Calming](/collections/dog-cooling-and-calming)
- [Dog Knitwear](/collections/dog-knitwear)
- [Dog Rainwear](/collections/dog-rainwear)
- [Dog Reflective Coats](/collections/dog-reflective-coats)
- [Dog Warmwear](/collections/dog-warmwear)
- [Small Dog Coats](/collections/small-dog-coats)
+ [Dog Collars and Leads](/collections/dog-collars)
+
- [Dog Collars](/collections/dog-collars)
- [Dog Leads](/collections/dog-leads)
- [Dog Extending Leads](/collections/dog-extending-leads)
- [Dog Tags & Accessories](/collections/dog-tags-accessories)
+ [Dog Flea Control & Wormers](/collections/dog-flea-control-and-wormers)
+
- [Dog Flea Treatment](/collections/dog-flea-treatment)
- [Dog Wormers](/collections/dog-wormers)
+ [Dog Grooming](/collections/dog-grooming)
+
- [Dog Clippers and Scissors](/collections/dog-clippers-and-scissors)
- [Dog Nail Clippers](/collections/dog-nail-clippers)
- [Dog Shampoo & Conditioners](/collections/dog-shampoo-conditioners)
- [Dog Brushes & Combs](/collections/dog-brushes-combs)
- [Dog Sprays & Hygiene Products](/collections/dog-sprays-hygiene-products)
- [Dog Towels](/collections/dog-towels)
+ [Dog Harness](/collections/dog-harness)
+
+ [Dog Health & Treatments](/collections/dog-health-and-treatments)
-
- [Dog Dental Care](/collections/dog-dental-care)
- [Dog Ear Care](/collections/dog-ear-care)
- [Dog Health Supplements](/collections/dog-health-supplements)
- [Dog Skin and Creams](/collections/dog-skin-and-creams)
+ [Dog Kennels & Flaps](/collections/dog-kennels-and-flaps)
+
- [Dog Kennels](/collections/dog-kennels)
- [Dog Pens](/collections/dog-pens)
- [Dog Flaps and Gates](/collections/dog-flaps-and-gates)
- [Dog Carriers](/collections/dog-carriers)
+ [Dog Leads](/collections/dog-leads)
+
+ [Dog Tags](/collections/dog-tags)
+
+ [Dog Toys](/collections/dog-toys)
+
- [Ball and Outdoor](/collections/ball-and-outdoor)
- [Brain Games](/collections/brain-games)
- [Dog Chews](/collections/dog-chews)
- [Dog Novelty Toys](/collections/dog-novelty-toys)
- [Dog Top Toys](/collections/dog-top-toys)
- [Toys For Puppys](/collections/toys-for-puppys)
- [Dog Soft Toys](/collections/dog-soft-toys)
- [Dog Tougher Toys](/collections/dog-tougher-toys)
+ [Dog Training](/collections/dog-training)
+
- [Dog Anti-Bark Accessories](/collections/dog-anti-bark-accessories)
- [Dog Muzzles](/collections/dog-muzzles)
- [Dog Clicker And Whistle Training](/collections/dog-clicker-and-whistle-training)
- [Dog Chewing Solutions](/collections/dog-chewing-solutions)
- [Dog Toilet Training](/collections/dog-toilet-training)
- [Dog Agility Training](/collections/dog-agility-training)
- [Other Training Solutions](/collections/other-training-solutions)
+ [Dog Travel](/collections/dog-travel)
+
+ [Puppy Products](/collections/puppy-products)
+
```
If you are looking for the fiddle version demo, then [**Here you go.**](https://jsfiddle.net/h917zcoa/49/)
Upvotes: 2 [selected_answer]
|
2018/03/14
| 873 | 3,005 |
<issue_start>username_0: I need to write a program that should ask two strings from user and show the common characters in this.
It must not have duplicates: even if ‘a’ is found more than once in both strings, it should be displayed only once.
My Java knowledge is very limited, so I'm not looking for efficiency but for understandability.
---
Here is what I came up with at the moment.
```
//Get String 1
System.out.print( "Enter a string: " );
string1 = sc.next();
//Get String 2
System.out.print( "Enter another string: " );
string2 = sc.next();
System.out.print ( "Common characters: " );
//Common chars
for ( a = 0 ; a < string1.length() ; a++){
for ( b = 0 ; b < string2.length() ; b++){
if ( string1.charAt(a) == string2.charAt(b) ){
System.out.print(string1.charAt(a));
}
```
Can anyone help me ?<issue_comment>username_1: I would use a `Set`. This would naturally handle the duplicate issue and has a simple `retainAll` method to do the heavy lifting for you.
```
private Set characterSet(String s) {
Set set = new HashSet<>();
// Put each character in the string into the set.
for (int i = 0; i < s.length(); i++) {
set.add(s.charAt(i));
}
return set;
}
public Set common(String a, String b) {
// Make a set out of each string.
Set aSet = characterSet(a);
Set bSet = characterSet(b);
// Work out the common characters using retainAll.
Set common = new HashSet<>(aSet);
common.retainAll(bSet);
return common;
}
public void test(String[] args) throws Exception {
System.out.println(common("abcdef", "afxyzfffaa"));
}
```
Upvotes: 1 <issue_comment>username_2: You can use `Set`
```
String str1 = "abcdefg";
String str2 = "abcaaadefg";
StringBuilder result = new StringBuilder();
Set sets = new HashSet();
for(char ch : str1.toCharArray()){//init
sets.add(ch);
}
for(char ch : str2.toCharArray()){
if(sets.contains(ch)){//str1 char contains str2 char
result.append(ch);
sets.remove(ch);//avoid duplicates
}
}
System.out.println(result.toString());
```
Upvotes: 0 <issue_comment>username_3: You can use the `chars()` stream of the input string, e.g.:
```
public class StringCharCount {
public static void main(final String[] args) {
final String s1 = args[0];
final String s2 = args[1];
s1.chars()
.distinct()
.mapToObj(ch -> String.valueOf((char) ch))
.filter(s2::contains)
.forEach(System.out::println);
}
}
```
This works with Java 8 or later.
* `chars()` creates a stream of characters from the string
* `distinct()` ensures, that each value occurs only once
* `mapToObj(...)` is required, because the `String#contains()` method requires a `String` as input. So we are converting the stream value to a `String`. Unfortunately, Java has issues with the primitive types, so the stream of `chars` is in fact a stream of `int`. So we have to cast each value to `char`.
* `forEach(...)` prints each value to `System.out`
Upvotes: 2
|
2018/03/14
| 1,307 | 4,318 |
<issue_start>username_0: I have a UL with a hover effect on its LIs. When hovering there is a red div appears on the left and when you click on the LI it toggles a class to the text inside of it. It's all ok on the desktop version but when I switch to the mobile version the first tap should activate only the hover effect. Instead of that it acticates the hover and toggle a class immediately. I want to have on mobile version the first tap activates hover and then if it's still active next taps toggle the class. Pls try the code on mobile version it's all clear there what I mean.
Thanks
```js
$('ul').on('click', 'li', function () {
$(this).toggleClass('completed');
});
$('ul').on('click', 'div', function (event) {
$(this).parent().fadeOut(250, function () {
$(this).remove();
});
//prevent event bubbling
event.stopPropagation();
});
```
```css
.container {
width: 360px;
margin: 0 auto;
border: 1px solid black;
}
ul{
list-style: none;
padding:0;
margin:0;
}
li{
width: 100%;
border: 1px solid black;
display: flex;
}
li div{
background-color:red;
width:0;
transition: 0.1s linear;
display:inline-block;
}
li:hover div{
width: 40px;
}
.completed {
color: grey;
text-decoration: line-through;
}
```
```html
Groceries
=========
* carrot
* onion
* tomato
```
**Update:** I'm almost got it, got the first toggle on the second tap, the problem is the next toggle occurs on the double tap too:
```
var isMobile = false;
var isClicked = 0;
$('ul').on('click', 'li', function () {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera
Mini/i.test(navigator.userAgent) ) {
isMobile = true;
isClicked++;
}
if(!isMobile || isClicked > 1){
$(this).toggleClass('completed');
isClicked = 0;
}
});
```<issue_comment>username_1: You should use [touchstart](http://www.hnldesign.nl/work/code/mouseover-hover-on-touch-devices-using-jquery/) event to handle touch event on mobile but don't forget to check if ontouchstart is available.
```js
$('ul').on('click', 'li', function() {
if ('ontouchstart' in document.documentElement) {
if ($(this).hasClass('hover')) {
$(this).toggleClass('completed');
}
} else {
$(this).toggleClass('completed');
}
});
$('ul').on('touchstart', 'li', function(e) {
var link = $(this); //preselect the link
if (link.hasClass('hover')) {
return true;
} else {
link.addClass("hover");
$('li').not(this).removeClass("hover");
e.preventDefault();
return false; //extra, and to make sure the function has consistent return points
}
});
$('ul').on('click', 'div', function(event) {
$(this).parent().fadeOut(250, function() {
$(this).remove();
});
//prevent event bubbling
event.stopPropagation();
});
```
```css
.container {
width: 360px;
margin: 0 auto;
border: 1px solid black;
}
ul {
list-style: none;
padding: 0;
margin: 0;
}
li {
width: 100%;
border: 1px solid black;
display: flex;
}
li div {
background-color: red;
width: 0;
transition: 0.1s linear;
display: inline-block;
}
li:hover div,
li.hover div{
width: 40px;
}
.completed {
color: grey;
text-decoration: line-through;
}
```
```html
Groceries
=========
* carrot
* onion
* tomato
```
Upvotes: 0 <issue_comment>username_2: First of all disable hover with CSS using @media queries for mobile devices.
Second create a jquery method for tap/click on that - at which you want to show red div. you can do something like this
```
$('li').on('click' , function(){
if($(window).width() <= 760){ // Enter maximum width of mobile device here for which you want to perform this action
// show red div here
}
return false;
});
```
Also keep in mind @media and $(window).width() should have same pixels/size
EDIT:
try replacing this
```
var isMobile = false;
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera
Mini/i.test(navigator.userAgent) ) {
isMobile = true;
}
$('ul').on('click', 'li', function () {
if(isMobile){
$(this).toggleClass('completed');
}
});
```
And let the other code in the click function and try again
Upvotes: 1
|
2018/03/14
| 449 | 1,752 |
<issue_start>username_0: I am trying to load my firebase console but it is not working on my laptop.It works fine on other laptops and my mobile but on my laptop it displays loading screen and then nothing.In console it shows 502 gateway error.
I have removed addblock, open console in incognito,firefox,internet explorer, reinstall chrome,change my network, login from another account but nothing works.
These are the questions I have seen to solve this but none of them actually works for me.
<https://groups.google.com/forum/#!topic/firebase-talk/xOWdvmKd7I0>
<https://groups.google.com/forum/#!topic/firebase-talk/5txW1hHXOQA>
[Firebase console and google dev console blank page issues](https://stackoverflow.com/questions/38320406/firebase-console-and-google-dev-console-blank-page-issues)
Thanks<issue_comment>username_1: I resolved it by disabling a chrome extension named CORS.
Thanks
Upvotes: 5 [selected_answer]<issue_comment>username_2: I resolved too, by disabling tampermonkey extension. This might help someone else...
Upvotes: 2 <issue_comment>username_3: Try Updating your browser to latest version. I solved this by updating Chrome to latest version available.
Upvotes: 2 <issue_comment>username_4: I updated the chrome and disabled Grammerly. It worked for me
Upvotes: 0 <issue_comment>username_5: I solved by disabling "Pop up blocker for Chrome - Poper Blocker" extension.
Upvotes: 0 <issue_comment>username_6: I have disable all ext. and then I have to changed the Internet Provider, from Broadband to Mobile Internet. It worked.
Upvotes: 0 <issue_comment>username_7: It happened to me too until I changed my internet provider
Upvotes: -1 <issue_comment>username_8: For me, the solution was disabling the Ublock
Upvotes: 0
|
2018/03/14
| 571 | 2,277 |
<issue_start>username_0: I have this:
```
@FXML
private ChoiceBox choiseData;
ObservableList choiseUserList = FXCollections.observableArrayList();
ObservableList userList = FXCollections.observableArrayList();
AdminSQL sql = new AdminSQL();
userList = sql.getAllUser();
for (User u : userList)
choiseUserList.add(u.getUserLogin());
choiseData.setItems(choiseUserList);
```
I do not like the two list and the loop. I wonder if you can only download users' logins directly from the userList list and place them ChoiseBox
Class User:
```
private IntegerProperty userLp;
private StringProperty userLogin;
private StringProperty userRule;
```<issue_comment>username_1: **Using Java 8 Streams**
```
choiseData.getItems().addAll(userList.stream().map(User::getUserLogin()));
```
Upvotes: 0 <issue_comment>username_2: Most probably, you *don't want* to have the ChoiceBox items as a list that's mapped once (somehow) from the real items because doing so comes with a handful of disadvantages:
* the two lists can get easily out off sync: when the users change or any its properties, the ChoiceBox is not updated
* when listening to f.i. selection changes in the ChoiceBox, the listener doesn't have the complete information about the user (from the selectedItem) but just one of its property values - if it wants to act on the user, it would have to look it up the info somewhere else, thus introducing (unwanted) coupling
* you are fighting the winds of fx, which has dedicated support to configure visual representations of any data object - in the case of a ChoiceBox you'd need a StringConverter
Example code snippet:
```
ChoiceBox choiceBox = new ChoiceBox<>(getUsers());
// from your snippet, AdminSQL already returns the list as
// an ObservableList, so you can set it directly as provided
// new ChoiceBox<>(sql.getAllUsers());
StringConverter converter = new StringConverter<>() {
@Override
public String toString(User user) {
return user != null ? user.getUserLogin() : "";
}
@Override
public User fromString(String userLogin) {
// should never happen, choicebox is not editable
throw new UnsupportedOperationException("back conversion not supported from " + userLogin);
}
};
choiceBox.setConverter(converter);
```
Upvotes: 2 [selected_answer]
|
2018/03/14
| 896 | 3,033 |
<issue_start>username_0: I was wondering if someone might be able to help me with this one.
We are receiving this error in our error logs:
>
> [13-Mar-2018 16:42:40 UTC] PHP Deprecated: preg\_replace(): The /e
> modifier is deprecated, use preg\_replace\_callback instead in
> public\_html/check\_requirements.php on line 58
>
>
>
Line 58 of check\_requirements.php is:
```
$string = preg_replace('~ *([0-9]+);~e', 'chr(\\1)', $string);
```
I'm afraid we just host the web site for someone else and the error appears to have occurred due to a recent PHP upgrade.
Does anyone know how I can alter line 58 of the code to fix the problem?
Many thanks for your help
James
---
15/03/2018
Thanks Eydamos. I've replaced the line in the code with your suggestion
```
$string = preg_replace_callback(
'~ *([0-9]+);~',
function ($matches) {
return chr($matches[1]);
},
$string
);
```
Unfortunately I then loaded the site again and checked the error log and it came up with the following:
[15-Mar-2018 09:02:09 UTC] PHP Deprecated: preg\_replace(): The /e modifier is deprecated, use preg\_replace\_callback instead in public\_html/check\_requirements.php on line 57
Line 57 was:
```
$string = preg_replace('~ *([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
```
It looks like your first suggestions fixed that issue but then another one has become apparent. I'm not sure what I should do with this one either. Would you mind taking a look for me? If it helps, I can paste the entire code.
I really appreciate your help with this one. It's totally out of my area of expertise - just something that we've inherited from an old site we've taken over the hosting of.<issue_comment>username_1: This is an easy fix you just have to convert the second parameter into a function. Like this:
```
$string = preg_replace_callback(
'~ *([0-9]+);~',
function ($matches) {
return chr($matches[1]);
},
$string
);
```
Beside you can archive the same result way easier:
```
$string = html_entity_decode($string);
```
The second one is just as easy as the first one:
```
$string = preg_replace_callback(
'~ *([0-9a-f]+);~i',
function ($matches) {
return chr(hexdec($matches[1]));
},
$string
);
```
Basically you just have to make three steps:
1. Remove the character 'e' after the delimiter (in your case the '~' is the delimiter)
2. Convert the second parameter to a function. You just have to return what was in the second parameter but without quotes so the functions like chr will be called
3. In the function replace \\1, \\2, ... with $matches[1], $matches[2] and so on
Upvotes: 3 [selected_answer]<issue_comment>username_2: according to PHP documentation <http://php.net/manual/en/reference.pcre.pattern.modifiers.php>
the 'e' modifier is deprecated from version 5.5.0 and is removed from PHP 7 , so if you are considering upgrade to PHP 7 you should replace your code to something similar to the documentation or an answer like @username_1 provided
Upvotes: -1
|
2018/03/14
| 4,986 | 21,751 |
<issue_start>username_0: so I have an if-else function where it will check what is supposed to be in a form, so when I submit the form the function in the controller does the if-else function. So its something like, if there is no value in a hidden input field then it will redirect the user back to the form, but when it does that, all the values for the other text input go missing and a user has to key in all over again. I don't want that to happen. Instead, I want all the other text input to remain. How can I do that?
my blade:
```html
{{csrf\_field()}}
[Back]({{action('Web\TravelController@index')}})
Book a trip
[Multi-city]({{action('Web\TravelController@multiCity')}})
One-way
Return
@if(request()->user()->hasRole('PA'))
Request as
{{$user->name}}
@foreach($user->bosses as $boss)
{{$boss->name}}
@endforeach
@else
@endif
Mode of Transport
Select a transport type
@foreach($transports as $transport)
{{$transport->name}}
@endforeach
From
To
Departure Date
Return Date
Selected Dates
Official
Non-Official
From
To
Accommodation
Yes
No
Travel Description
{{-- --}}
Travel Preferences
Add Passengers
SAVE
SUBMIT
From
To
#### Summary
##### Travel Type
Return
##### Travel Route
##### Departure Date
##### Return Date
```
and my function is:
```js
public function store(Request $request)
{
$user = Auth::user();
$today = date('Y-m-d');
$inputs = $request->all();
$inputTravel_data = $request->input('travel_data');
if($request->has('is_return_trip'))
{
$travelTitle = $inputTravel_data['from'].' - '.$inputTravel_data['to'];
$multiCity = 0;
$is_return_trip = $inputs['is_return_trip'];
}else{
$count = count($inputs['travelLeg']);
$title = $inputTravel_data['from'][0];
for ($i = 1; $i < $count; $i++)
{
$title .= ' - ' . $inputTravel_data['from'][$i];
}
$travelTitle = $title. ' - ' .$inputTravel_data['to'][$count-1];
$multiCity = 1;
$is_return_trip = 0;
}
if(!$inputTravel_data['from_country']){
return redirect()->back();
}else{
if(array_key_exists('id', $inputs) && $inputs['id'])
{
$travel = Travel::where('id',$this->decode($inputs['id']))->first();
if(!$travel)
return $this->error('message','No travel found for this user');
$travel->update([
'status' => $inputs['status'],
'title' => $travelTitle,
'is_multicity' => $multiCity,
'is_return_trip' => $is_return_trip,
'company_id' => $user->company_id,
'submitted_by_pa' => $inputs['user_id'] != Auth::user()->id ? 0 : 1,
'pa_id' => $inputs['user_id'] != Auth::user()->id ? $inputs['pa_id'] : null,
]);
if($inputs['status'] == 'SB' && $inputs['user_id'] == Auth::user()->id){
foreach($travel->travel_data()->where('removed',0)->get() as $t) {
$t->update(['removed'=> 1]);
}
}elseif($inputs['status'] == 'S'){
foreach($travel->travel_data()->where('removed',0)->get() as $t) {
$t->delete();
}
}
if($request->has('is_return_trip'))
{
$travelLeg = new TravelLeg;
$travelLeg->travel_id = $travel->id;
$travelLeg->transport_type_id = $inputTravel_data['transport_type_id'];
$travelLeg->accommodation = $inputTravel_data['accommodation'];
$travelLeg->travel_region_id = $inputTravel_data['travel_region_id'];
$travelLeg->travel_purpose = TravelPurpose::find($inputTravel_data['travel_purpose_id'])->name;
$travelLeg->description = $inputTravel_data['description'];
$travelLeg->travel_prefernces = $inputTravel_data['travel_preferences'];
$travelLeg->add_passengers = $inputTravel_data['add_passengers'];
$travelLeg->from = $inputTravel_data['from'];
$travelLeg->from_state = $inputTravel_data['from_state'] ?? '';
$travelLeg->from_country = $inputTravel_data['from_country'] ?? '';
$travelLeg->to = $inputTravel_data['to'];
$travelLeg->to_state = $inputTravel_data['to_state'] ?? '';
$travelLeg->to_country = $inputTravel_data['to_country'] ?? '';
$travelLeg->departure_date = date('Y-m-d', strtotime(str_replace('/', '-', $inputTravel_data['departure_date'])));
if (!empty($inputTravel_data['return_date']))
{
$travelLeg->return_date = date('Y-m-d', strtotime(str_replace('/', '-', $inputTravel_data['return_date'])));
}
$travelLeg->title = 'Travel Leg 1';
$travelLeg->is_official_date = $inputTravel_data['is_official_date'];
$travelLeg->mode_of_transport = TransportType::find($inputTravel_data['transport_type_id'])->name;
$travelLeg->region = TravelRegion::find($inputTravel_data['travel_region_id'])->name;
$travelLeg->travel_purpose_id = $inputTravel_data['travel_purpose_id'];
$travelLeg->processed = 0;
$travelLeg->save();
if ($travelLeg->is_official_date == self::IS_OFFICIALDATE)
{
$travelLeg->official_date()->delete();
}
if ($travelLeg->is_official_date == self::IS_NOT_OFFICIALDATE)
{
$travelLeg->official_date()->delete();
for ($i = 0; $i < count($inputs['fromOfficialDate']); $i++)
{
$travelDate = new TravelDate;
$travelDate->travel_leg_id = $travelLeg->id;
$travelDate->from = date('Y-m-d', strtotime(str_replace('/', '-', $inputs['fromOfficialDate'][$i])));
$travelDate->to = date('Y-m-d', strtotime(str_replace('/', '-', $inputs['toOfficialDate'][$i])));
$travelDate->save();
}
}
}
else
{
for ($i = 0; $i < $count; $i++)
{
$travelDataFromState ='';
$temporaryIndex = $i;
if ($inputTravel_data['from_state'][$temporaryIndex] == '') {
if (($temporaryIndex-1) <= 0) {
$temporaryIndex = 0;
} else {
$temporaryIndex = $temporaryIndex - 1;
}
$travelDataFromState = $inputTravel_data['to_state'][$temporaryIndex];
} else {
$travelDataFromState = $inputTravel_data['from_state'][$temporaryIndex] ?? '';
}
$travelDataFromCountry = '';
if ($inputTravel_data['from_country'][$temporaryIndex] == '') {
if (($temporaryIndex-1) <= 0) {
$temporaryIndex = 0;
} else {
$temporaryIndex = $temporaryIndex - 1;
}
$travelDataFromCountry = $inputTravel_data['to_country'][$temporaryIndex];
} else {
$travelDataFromCountry = $inputTravel_data['from_country'][$temporaryIndex] ?? '';
}
$travelLeg = new TravelLeg;
$travelLeg->travel_id = $travel->id;
$travelLeg->transport_type_id = $inputTravel_data['transport_type_id'][$i];
$travelLeg->accommodation = $inputTravel_data['accommodation'][$i];
$travelLeg->travel_region_id = $inputTravel_data['travel_region_id'][$i];
$travelLeg->travel_purpose = TravelPurpose::find($inputTravel_data['travel_purpose_id'][$i])->name;
$travelLeg->description = $inputTravel_data['description'][$i];
$travelLeg->travel_prefernces = $inputTravel_data['travel_preferences'][$i];
$travelLeg->add_passengers = $inputTravel_data['add_passengers'][$i];
$travelLeg->from = $inputTravel_data['from'][$i];
$travelLeg->from_state = $travelDataFromState;
$travelLeg->from_country = $travelDataFromCountry;
$travelLeg->to = $inputTravel_data['to'][$i];
$travelLeg->to_state = $inputTravel_data['to_state'][$i] ?? '';
$travelLeg->to_country = $inputTravel_data['to_country'][$i] ?? '';
$travelLeg->departure_date = date('Y-m-d', strtotime(str_replace('/', '-', $inputTravel_data['departure_date'][$i])));
$travelLeg->title = 'Travel Leg ' . $inputs['travelLeg'][$i+1];
$travelLeg->is_official_date = $inputTravel_data['is_official_date'][$i];
$travelLeg->mode_of_transport = TransportType::find($inputTravel_data['transport_type_id'][$i])->name;
$travelLeg->region = TravelRegion::find($inputTravel_data['travel_region_id'][$i])->name;
$travelLeg->travel_purpose_id = $inputTravel_data['travel_purpose_id'][$i];
$travelLeg->processed = 0;
$travelLeg->save();
if ($travelLeg->is_official_date == self::IS_OFFICIALDATE)
{
$travelLeg->official_date()->delete();
}
if ($travelLeg->is_official_date == self::IS_NOT_OFFICIALDATE)
{
$travelLeg->official_date()->delete();
$dates = $inputs['OfficialDate'][$inputs['travelLeg'][$i+1]];
for ($j = 0; $j < count($dates['from']); $j++)
{
$fromODate = new TravelDate;
$fromODate->travel_leg_id = $travelLeg->id;
$fromODate->from = date('Y-m-d', strtotime(str_replace('/', '-', $dates['from'][$j])));
$fromODate->to = date('Y-m-d', strtotime(str_replace('/', '-', $dates['to'][$j])));
$fromODate->save();
}
}
}
}
}
else {
if($user->id != $inputs['user_id']){
$user = User::find($inputs['user_id']);
}
$travel = $user->travels()->create([
'status' => $inputs['status'],
'title' => $travelTitle,
'is_multicity' => $multiCity,
'is_return_trip' => $is_return_trip,
'company_id' => $user->company_id,
'submitted_by_pa' => $inputs['user_id'] != Auth::user()->id ? 0 : 1,
'pa_id' => $inputs['user_id'] != Auth::user()->id ? $inputs['pa_id'] : null,
]);
$this->generateRef($travel);
if($request->has('is_return_trip'))
{
$travelLeg = new TravelLeg;
$travelLeg->travel_id = $travel->id;
$travelLeg->transport_type_id = $inputTravel_data['transport_type_id'];
$travelLeg->accommodation = $inputTravel_data['accommodation'];
$travelLeg->travel_region_id = $inputTravel_data['travel_region_id'];
$travelLeg->travel_purpose = TravelPurpose::find($inputTravel_data['travel_purpose_id'])->name;
$travelLeg->description = $inputTravel_data['description'];
$travelLeg->travel_prefernces = $inputTravel_data['travel_preferences'];
$travelLeg->add_passengers = $inputTravel_data['add_passengers'];
$travelLeg->from = $inputTravel_data['from'];
$travelLeg->from_state = $inputTravel_data['from_state'] ?? '';
$travelLeg->from_country = $inputTravel_data['from_country'] ?? '';
$travelLeg->to = $inputTravel_data['to'];
$travelLeg->to_state = $inputTravel_data['to_state'] ?? '';
$travelLeg->to_country = $inputTravel_data['to_country'] ?? '';
$travelLeg->departure_date = date('Y-m-d', strtotime(str_replace('/', '-', $inputTravel_data['departure_date'])));
if (!empty($inputTravel_data['return_date']))
{
$travelLeg->return_date = date('Y-m-d', strtotime(str_replace('/', '-', $inputTravel_data['return_date'])));
}
$travelLeg->title = 'Travel Leg 1';
$travelLeg->is_official_date = $inputTravel_data['is_official_date'];
$travelLeg->mode_of_transport = TransportType::find($inputTravel_data['transport_type_id'])->name;
$travelLeg->region = TravelRegion::find($inputTravel_data['travel_region_id'])->name;
$travelLeg->travel_purpose_id = $inputTravel_data['travel_purpose_id'];
$travelLeg->processed = 0;
$travelLeg->save();
if ($travelLeg->is_official_date == self::IS_NOT_OFFICIALDATE)
{
for ($i = 0; $i < count($inputs['fromOfficialDate']); $i++)
{
$travelDate = new TravelDate;
$travelDate->travel_leg_id = $travelLeg->id;
$travelDate->from = date('Y-m-d', strtotime(str_replace('/', '-', $inputs['fromOfficialDate'][$i])));
$travelDate->to =date('Y-m-d', strtotime(str_replace('/', '-', $inputs['toOfficialDate'][$i])));
$travelDate->save();
}
}
}
else
{
for ($i = 0; $i < $count; $i++)
{
$travelDataFromState ='';
$temporaryIndex = $i;
if ($inputTravel_data['from_state'][$temporaryIndex] == '') {
if (($temporaryIndex-1) <= 0) {
$temporaryIndex = 0;
} else {
$temporaryIndex = $temporaryIndex - 1;
}
$travelDataFromState = $inputTravel_data['to_state'][$temporaryIndex];
} else {
$travelDataFromState = $inputTravel_data['from_state'][$temporaryIndex] ?? '';
}
$travelDataFromCountry = '';
if ($inputTravel_data['from_country'][$temporaryIndex] == '') {
if (($temporaryIndex-1) <= 0) {
$temporaryIndex = 0;
} else {
$temporaryIndex = $temporaryIndex - 1;
}
$travelDataFromCountry = $inputTravel_data['to_country'][$temporaryIndex];
} else {
$travelDataFromCountry = $inputTravel_data['from_country'][$temporaryIndex] ?? '';
}
$travelLeg = new TravelLeg;
$travelLeg->travel_id = $travel->id;
$travelLeg->transport_type_id = $inputTravel_data['transport_type_id'][$i];
$travelLeg->accommodation = $inputTravel_data['accommodation'][$i];
$travelLeg->travel_region_id = $inputTravel_data['travel_region_id'][$i];
$travelLeg->travel_purpose = TravelPurpose::find($inputTravel_data['travel_purpose_id'][$i])->name;
$travelLeg->description = $inputTravel_data['description'][$i];
$travelLeg->travel_prefernces = $inputTravel_data['travel_preferences'][$i];
$travelLeg->add_passengers = $inputTravel_data['add_passengers'][$i];
$travelLeg->from = $inputTravel_data['from'][$i];
$travelLeg->from_state = $travelDataFromState;
$travelLeg->from_country = $travelDataFromCountry;
$travelLeg->to = $inputTravel_data['to'][$i];
$travelLeg->to_state = $inputTravel_data['to_state'][$i] ?? '';
$travelLeg->to_country = $inputTravel_data['to_country'][$i] ?? '';
$travelLeg->departure_date = date('Y-m-d', strtotime( str_replace('/', '-', $inputTravel_data['departure_date'][$i])));
$travelLeg->title = 'Travel Leg ' . $inputs['travelLeg'][$i+1];
$travelLeg->is_official_date = $inputTravel_data['is_official_date'][$i];
$travelLeg->mode_of_transport = TransportType::find($inputTravel_data['transport_type_id'][$i])->name;
$travelLeg->region = TravelRegion::find($inputTravel_data['travel_region_id'][$i])->name;
$travelLeg->travel_purpose_id = $inputTravel_data['travel_purpose_id'][$i];
$travelLeg->processed = 0;
$travelLeg->save();
if ($travelLeg->is_official_date == self::IS_NOT_OFFICIALDATE)
{
$dates = $inputs['OfficialDate'][$inputs['travelLeg'][$i+1]];
for ($j = 0; $j < count($dates['from']); $j++)
{
$fromODate = new TravelDate;
$fromODate->travel_leg_id = $travelLeg->id;
$fromODate->from = date('Y-m-d', strtotime(str_replace('/', '-', $dates['from'][$j])));
$fromODate->to = date('Y-m-d', strtotime(str_replace('/', '-', $dates['to'][$j])));
$fromODate->save();
}
}
}
}
}
if($inputs['status'] == 'SB')
{
$pivotT = \DB::table('travel_approver_inboxes')
->where('travel_id', $travel->id)
->where('removed',0)
->get();
foreach($pivotT as $p) {
$travel->approver()
->newPivotStatement()
->where('id', $p->id)->update(['removed'=> 1]);
}
(new TravelApprover($travel))->assign();
$travel->update(['submitted_date' => $today,'remark'=> null]);
$travel->fresh();
// (new Notification)->addNotification($travel,'travel');
// dd($travel->approver->last());
}
return redirect(action('Web\TravelController@index'));
}
}
```
so as you can the main redirect is here:
```php
if(!$inputTravel_data['from_country']){
return redirect()->back();
```<issue_comment>username_1: This is an easy fix you just have to convert the second parameter into a function. Like this:
```
$string = preg_replace_callback(
'~ *([0-9]+);~',
function ($matches) {
return chr($matches[1]);
},
$string
);
```
Beside you can archive the same result way easier:
```
$string = html_entity_decode($string);
```
The second one is just as easy as the first one:
```
$string = preg_replace_callback(
'~ *([0-9a-f]+);~i',
function ($matches) {
return chr(hexdec($matches[1]));
},
$string
);
```
Basically you just have to make three steps:
1. Remove the character 'e' after the delimiter (in your case the '~' is the delimiter)
2. Convert the second parameter to a function. You just have to return what was in the second parameter but without quotes so the functions like chr will be called
3. In the function replace \\1, \\2, ... with $matches[1], $matches[2] and so on
Upvotes: 3 [selected_answer]<issue_comment>username_2: according to PHP documentation <http://php.net/manual/en/reference.pcre.pattern.modifiers.php>
the 'e' modifier is deprecated from version 5.5.0 and is removed from PHP 7 , so if you are considering upgrade to PHP 7 you should replace your code to something similar to the documentation or an answer like @username_1 provided
Upvotes: -1
|
2018/03/14
| 680 | 2,488 |
<issue_start>username_0: In angular4 i get below error. Kindly solve anyone. Thanks in advance.
**new-cmp-component.ts:**:
```
import { Component, OnInit } from '@angular/core'; // here angular/core is imported .
@Component({
selector: 'app-new-cmp',
templateUrl: './new-cmp.component.html',
styleUrls: ['./new-cmp.component.css']
})
export class NewCmpComponent implements OnInit {
constructor() {
newcomponent: 'Entered in new component created';
}
ngOnInit() {
}
}
```
**Error:**
ERROR: in src/app/new-cmp/new-cmp.component.ts<11,8>: error TS7028: unused label.<issue_comment>username_1: My guess is that you are using TSLint. The error occurs because you declared a variable (without using `const` or `let` or `var` before it), and never use it. It is also declared in the wrong way. It should not be `newcomponent: 'Entered in new component created'`, but rather (If it is a constant) declare it as
```
const newcomponent = 'Entered in new component created';
```
Note that you are using colon (:) instead of equals (=) when declaring it. If you use colon, you should specify a type (e.g. `const myLabel:string;`)
Upvotes: 2 <issue_comment>username_2: You should first declare the variable, then use it.
```
import { Component, OnInit } from '@angular/core'; // here angular/core is imported .
@Component({
selector: 'app-new-cmp',
templateUrl: './new-cmp.component.html',
styleUrls: ['./new-cmp.component.css']
})
export class NewCmpComponent implements OnInit {
const newcomponent = 'Entered in new component created';
public newcomponent2: string;
constructor() {
this.newcomponent2 = 'Entered in new component created';
}
ngOnInit() {
}
}
```
Upvotes: 1 <issue_comment>username_3: Now, I declare the variable "newcomponent" out side of constructor method.
This is working fine now.
```
import { Component, OnInit } from '@angular/core'; // here angular/core is imported .
@Component({
selector: 'app-new-cmp',
templateUrl: './new-cmp.component.html',
styleUrls: ['./new-cmp.component.css']
})
export class NewCmpComponent implements OnInit {
**newcomponent: 'Entered in new component created';**
constructor() {
}
ngOnInit() {
}
}
```
Upvotes: 0 <issue_comment>username_4: I was having same error at declaration line:
```
declarations:[AddFlightPage]
```
I just declared it with let and it worked.
```
let declarations:[AddFlightPage]
```
Upvotes: 0
|
2018/03/14
| 988 | 3,529 |
<issue_start>username_0: I have an apex application where i need to send a notification mail to all the employees on the 5th of every month. So just for the sake of testing i am trying to send a mail in every 30 seconds. I created a job scheduler on a procedure to do the same. Here is the PLSQL code for it.
```
create or replace procedure send_notification_employee as
cursor c_employee is select * from EMPLOYEE;
r_employee c_employee%ROWTYPE;
begin
open c_employee;
loop
fetch c_employee into r_employee;
exit when c_employee%NOTFOUND;
APEX_MAIL.SEND(
p_to => r_employee.EMPLOYEE_EMAIL,
p_from => '<EMAIL>',
p_subj => 'Reminder : Meeting',
p_body => '');
end loop;
close c\_employee;
end;
/
begin
DBMS\_SCHEDULER.CREATE\_JOB(
job\_name => 'send\_notification',
job\_type => 'stored\_procedure',
job\_action => 'send\_notification\_employee',
start\_date => NULL,
repeat\_interval => 'FREQ=SECONDLY;INTERVAL=30',
end\_date => NULL);
end;
/
begin
DBMS\_SCHEDULER.enable(
name => 'send\_notification');
end;
/
```
I guess the code is correct. The only thing i am not sure of is to how to run this scheduler on the apex oracle application. Should i just execute these statements on the SQL Commands or is there any other way to do it?
Also i tried to execute the same statements in the SQL Commands tab but i don't receive any mails as such. Is there any issue with my code? Thanks in advance.<issue_comment>username_1: These queries could be handy (To check if you have the correct set up):
Check if `util_smtp` is installed:
```
select * from dba_objects where object_name like 'UTL_SMTP%'
```
Check privileges:
```
select grantee , table_name , privilege from dba_tab_privs where table_name = 'UTL_SMTP'
```
Check open network hosts, ports:
```
select acl , host , lower_port , upper_port from DBA_NETWORK_ACLS;
```
Check network privileges:
```
select acl , principal , privilege , is_grant from DBA_NETWORK_ACL_PRIVILEGES
```
Upvotes: 0 <issue_comment>username_2: You need to set the security group if sending the mail from the database rather than from APEX directly. You should also use push\_queue at the end of the procedure to clear out the table of unsent mail.
```
create or replace procedure send_notification_employee as
cursor c_employee is select * from EMPLOYEE;
r_employee c_employee%ROWTYPE;
l_workspace number;
begin
-- Get a valid workspace ID
SELECT MAX(workspace_id) INTO l_workspace FROM apex_applications WHERE application_id = ;
-- Set Workspace
wwv\_flow\_api.set\_security\_group\_id(l\_workspace);
open c\_employee;
loop
fetch c\_employee into r\_employee;
exit when c\_employee%NOTFOUND;
APEX\_MAIL.SEND(
p\_to => r\_employee.EMPLOYEE\_EMAIL,
p\_from => '<EMAIL>',
p\_subj => 'Reminder : Meeting',
p\_body => '');
end loop;
close c\_employee;
-- Finally force send
APEX\_MAIL.PUSH\_QUEUE;
end;
```
Re. how to execute - it depends on what you want to do. If you just want to run it on the 5th of every month just setup a scheduled job in the db to do it, as you have above. If you want to run on an adhoc basis just create a job in an APEX after submit process that calls the procedure and executes through the database.
As an aside, if you plan to create many mail procedures you may wish to create a helper procedure to get the workspace id / send the mail, and just call it from your other mail procedures.
Upvotes: 2 [selected_answer]
|
2018/03/14
| 688 | 2,428 |
<issue_start>username_0: I'm looking for a regex that checks for a pattern that starts with only 1 opening curly bracket and any number of closing brackets so:
```
"something{word_or_not}}}}}}}"
#should return true.
"something{{word_or_not}}}}}}}}"
#should return false.
```
This is how far I've gotten `"\{\w*\}\}+"` except not that far since this returns `true` for the second example.<issue_comment>username_1: These queries could be handy (To check if you have the correct set up):
Check if `util_smtp` is installed:
```
select * from dba_objects where object_name like 'UTL_SMTP%'
```
Check privileges:
```
select grantee , table_name , privilege from dba_tab_privs where table_name = 'UTL_SMTP'
```
Check open network hosts, ports:
```
select acl , host , lower_port , upper_port from DBA_NETWORK_ACLS;
```
Check network privileges:
```
select acl , principal , privilege , is_grant from DBA_NETWORK_ACL_PRIVILEGES
```
Upvotes: 0 <issue_comment>username_2: You need to set the security group if sending the mail from the database rather than from APEX directly. You should also use push\_queue at the end of the procedure to clear out the table of unsent mail.
```
create or replace procedure send_notification_employee as
cursor c_employee is select * from EMPLOYEE;
r_employee c_employee%ROWTYPE;
l_workspace number;
begin
-- Get a valid workspace ID
SELECT MAX(workspace_id) INTO l_workspace FROM apex_applications WHERE application_id = ;
-- Set Workspace
wwv\_flow\_api.set\_security\_group\_id(l\_workspace);
open c\_employee;
loop
fetch c\_employee into r\_employee;
exit when c\_employee%NOTFOUND;
APEX\_MAIL.SEND(
p\_to => r\_employee.EMPLOYEE\_EMAIL,
p\_from => '<EMAIL>',
p\_subj => 'Reminder : Meeting',
p\_body => '');
end loop;
close c\_employee;
-- Finally force send
APEX\_MAIL.PUSH\_QUEUE;
end;
```
Re. how to execute - it depends on what you want to do. If you just want to run it on the 5th of every month just setup a scheduled job in the db to do it, as you have above. If you want to run on an adhoc basis just create a job in an APEX after submit process that calls the procedure and executes through the database.
As an aside, if you plan to create many mail procedures you may wish to create a helper procedure to get the workspace id / send the mail, and just call it from your other mail procedures.
Upvotes: 2 [selected_answer]
|
2018/03/14
| 1,086 | 3,168 |
<issue_start>username_0: I have 3 select box, and I want this equation.
( (Select2 - Select1) \* 40000 ) + Select3
But it doesn't work very well :(
Here's my code HTML / Jquery.
```
1
2
3
4
5
1
2
3
4
5
10000
20000
30000
40000
50000
```
**Jquery**
```
$(document).ready(function() {
$('select').on('change', function() {
$('#total').text(
( ($('select[name=select2]').val() - $('select[name=select1]').val() ) * 40000 )
+ $('select[name=select3]').val()
);
});
```<issue_comment>username_1: ```js
$('select').on('change', function() {
var res = (parseInt($('select[name=select2]').val()) -
parseInt($('select[name=select1]').val())) *
40000
parseInt($('select[name=select3]').val());
$('#total').html(
res
);
});
```
```html
1
2
3
4
5
1
2
3
4
5
10000
20000
30000
40000
50000
```
You need parseInt (or parseFloat) to get mathematical result, like
```
parseInt(('select[name=select2]').val())
```
Upvotes: 1 <issue_comment>username_2: It should use the parseInt method, as you are addition and subtraction, which are commonly interpreted as concatenation operator rather than addition.
```
( parseInt($('select[name=select2]').val()) - parseInt($('select[name=select1]').val()) ) * 40000 ) + parseInt($('select[name=select3]').val())
```
Upvotes: 0 <issue_comment>username_3: You can use parseInt() function
```
$(document).ready(function() {
$('select').on('change', function() {
$('#total').text(
( parseInt(($('select[name="select2"]').val()) - parseInt($('select[name="select1"]').val()) ) * 40000 )
+ parseInt($('select[name="select3"]').val())
);
});
});
```
Don't forget to change value in value attributes
```
1
2
3
4
5
1
2
3
4
5
10000
20000
30000
40000
50000
Total: 0
```
Upvotes: 2 [selected_answer]<issue_comment>username_4: All ur `option` values are 1 .Change that to get desired o/p
```js
$(document).ready(function() {
$('select').on('change', function() {
var a=parseInt( $('select[name=select1]').val());
var b=parseInt( $('select[name=select2]').val());
var c=parseInt( $('select[name=select3]').val());
var total=((b-a)*4000)+c;
$('#total').text(total);
});
});
```
```html
1
2
3
4
5
1
2
3
4
5
10000
20000
30000
40000
50000
```
Upvotes: 1 <issue_comment>username_5: You seem to have forgotten to change the `value` attribute that `.val()` is tied to. Additionally, I made a function to make getting the value from the name and converting it to an int easier. And I added `.trigger('change')`, so we can see the results on page load.
```js
function valByNameToInt(name) {
return parseInt($('select[name="' + name + '"]').val());
}
$('select').on('change', function() {
$('#total').text(
(valByNameToInt('select1') - valByNameToInt('select2')) * 40000 + valByNameToInt('select3')
);
}).trigger('change');
```
```html
1
2
3
4
5
1
2
3
4
5
10000
20000
30000
40000
50000
```
Upvotes: 2
|
2018/03/14
| 1,255 | 3,751 |
<issue_start>username_0: I have a MutableList with generic with Int, like MutableList.
I wonder how to use kotlin call java method remove(int position) and remove(Integer object) correctly?
```
public void remove(int position) {
if (this.list != null && this.list.size() > position) {
this.list.remove(position);
notifyDataSetChanged();
}
}
public void remove(T t) {
if (t != null && this.list != null && !this.list.isEmpty()) {
boolean removed = false;
try {
removed = this.list.remove(t);
} catch (Exception e) {
e.printStackTrace();
}
if (removed) {
notifyDataSetChanged();
}
}
}
```<issue_comment>username_1: There are overall 4 methods for removing items in [`kotlin.collections.MutableList`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-mutable-list/index.html) as of Kotlin 1.2.30:
* `remove` - used to remove element once. Calls to this method are compiled to calls to the Java method `List.remove(Object o)`.
* `removeAt` - used to remove at a certain position. Calls to this method are compiled to calls to the Java method `List.remove(int index)`.
* `removeAll` - used to remove a collection, each element multiple times
* `removeIf` - remove using a predicate, each element multiple times
Below is an example of how you can use each method. In the comments you can find what each method would print to the console and a brief explanation of what it does:
```
fun main(args: Array) {
val l: MutableList = mutableListOf(1, 2, 3, 3, 4, 5, 6, 7, 1, 1, 1)
println(l.remove(1)) // true
println(l) // [2, 3, 3, 4, 5, 6, 7, 1, 1, 1] - removes first element and stops
println(l.removeAt(0)) // 2 - removes exactly on a specific position
println(l) // [3, 3, 4, 5, 6, 7, 1, 1, 1]
try {
println(l.removeAt(10000))
} catch(e: IndexOutOfBoundsException) {
println(e) // java.lang.IndexOutOfBoundsException: Index: 10000, Size: 9
}
println(l.removeAll(listOf(3, 4, 5))) // true
println(l) // [6, 7, 1, 1, 1] - removes elements in list multiple times, 3 removed multiple times
println(l.removeIf { it == 1 }) // true
println(l) // [6, 7] - all ones removed
}
```
...
```
true
[2, 3, 3, 4, 5, 6, 7, 1, 1, 1]
2
[3, 3, 4, 5, 6, 7, 1, 1, 1]
java.lang.IndexOutOfBoundsException: Index: 10000, Size: 9
true
[6, 7, 1, 1, 1]
true
[6, 7]
```
Upvotes: 2 <issue_comment>username_2: Seems that other answers just give alternatives of `remove(int position)` but they didn't answer the question directly (according to the edit).
So you can use this code:
```
val list = mutableListOf("ah!", "I", "died!")
(list as java.util.List).remove(1)
println(list)
```
Result:
```
[ah!, died!]
```
That's it! You've successfully invoked `remove(int position)` from Java.
This will raise some warnings, just ignore them.
[Try it online!](https://tio.run/##NYzBCsIwEETv/YptTglIwLsKHgXBg1@w0lRXN6mkm4CI3x7TiHMYmGHePCZhCqWMKcA@RnxtzhIpXHfWIwVt4N1BVUYGpllgCz4JXtgdaz<KEY> "Kotlin – Try It Online")
Upvotes: 0 <issue_comment>username_3: Finally i find the answer in [Kotlin doc](https://kotlinlang.org/docs/reference/basic-types.html) by myself. Kotlin will box generics
int to Integer if you declare the variable as Int?, because only an Object can be null.You can use the tool in android studio which can show the kotlin bytecode to find out that.
If we call java method like the question image:
```
val a:Int = 0
remove(a) // will call java method remove(int position)
val a:Int? = 0
remove(a) // will call java method remove(T t) to remove object
```
the result is different! If have better choice, we should avoid use like that.
Upvotes: 1
|
2018/03/14
| 723 | 2,430 |
<issue_start>username_0: I am facing below issue while running my build:
```
C:/Test.cpp: In member function '........':
C:/Test.cpp:291:50: error: 'round_one' may be used uninitialized in this function [-Werror=maybe-uninitialized]
```
I tried to grep for string **maybe-uninitialized** in my whole source code but I could not find one. I was expecting some declaration like below:
```
set_source_files_properties(ROOT_DIR/Test.cpp PROPERTIES COMPILE_FLAGS "-Wno-maybe-uninitialized -Wno-misleading-indentation" )
```
or
```
SET(GCC_COVERAGE_COMPILE_FLAGS "-Wno-maybe-uninitialized")
add_definitions(${GCC_COVERAGE_COMPILE_FLAGS})
```
But I could not find any - please let me know how Compiler flags are set in CMAKE utility?<issue_comment>username_1: The warning `-Wmaybe-uninitialized` is one of those that are enabled
by [`-Wall`](https://gcc.gnu.org/onlinedocs/gcc-7.3.0/gcc/Warning-Options.html#Warning-Options).
`-Wall` is always specified by proficient programmers. Warnings will be converted
to errors by [`-Werror`](https://gcc.gnu.org/onlinedocs/gcc-7.3.0/gcc/Warning-Options.html#Warning-Options), so the flags `-Wall -Werror` will produce `-Werror=maybe-uninitialized`,
as per your diagnostic, if a potentially uninitialized variable is detected.
You will very likely find `-Wall ... -Werror` in the specified compiler flags in the relevant `CMakeLists.txt`
Upvotes: 3 [selected_answer]<issue_comment>username_2: One way is setting the add compiler flag for the project:
```
cmake_minimum_required(VERSION 2.8)
# Project
project(008-compile-flags-01)
# Add compile flag
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DHELLO_WORLD" CACHE STRING "Hello World Define." FORCE)
# Executable source files
set(executable_SOURCES src/main.cpp)
# Executable
add_executable(executable ${executable_SOURCES})
```
Other way is setting compiler flag for the target:
```
cmake_minimum_required(VERSION 3.2)
# Project
project(008-compile-flags-03)
# Executable source files
set(executable_SOURCES src/main.cpp)
# Executable
add_executable(executable ${executable_SOURCES})
# Add compile flag
target_compile_options(executable PRIVATE -DHELLO_WORLD)
```
Other way is using **target\_compile\_features**. I haven't used this before. Please see:
* <https://cmake.org/cmake/help/latest/command/target_compile_features.html>
* <https://cmake.org/cmake/help/latest/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.html>
Upvotes: 1
|
2018/03/14
| 1,766 | 3,556 |
<issue_start>username_0: I am trying to merge the data from two worsheets in in one workbook.
I have succesfully queried the data into two diffrent recordsets like so:
```
SELECT F1,F5,F12,F13,F37,F38 FROM [KAP$] WHERE F8 LIKE 'klima'
```
and
```
SELECT F1, F2, F3, F4, F5, F6, F7, F8 FROM [Klima$A3:H899] WHERE F1 IS NOT NULL
```
Unfortunatly I have not found a way to "merge" the two recordsets.
However I noticed that the better way to archieve this would be to just query the two sheets at once using a left join. However I just can't get the syntax right. My last try was this:
```
SELECT
[KAP$].F1,
[KAP$].F5,
[KAP$].F12,
[KAP$].F13,
[KAP$].F37,
[KAP$].F38,
[Klima$].F1,
[Klima$].F2,
[Klima$].F3,
[Klima$].F4,
[Klima$].F5,
[Klima$].F6,
[Klima$].F7,
[Klima$].F8
FROM [KAP$] WHERE [KAP$].F8 LIKE 'Klima' LEFT JOIN [Klima$A3:H899] ON [KAP$].F1=[Klima$].F1
```
But as I have noticed there is more than one thing wrong with it... Any help is apreciated, I have been looking for a proper excel vba adodb guide for hours without success....
Thank you!
Edit: Here is some sample data:
KAP:
```
ID1 Info1 Info2 KAPinfo1 KAPinfo2 KAPinfo3
ID2 Info1 Info2 KAPinfo1 KAPinfo2 KAPinfo3
ID3 Info1 Info2 KAPinfo1 KAPinfo2 KAPinfo3
ID4 Info1 Info2 KAPinfo1 KAPinfo2 KAPinfo3
ID5 Info1 Info2 KAPinfo1 KAPinfo2 KAPinfo3
ID6 Info1 Info2 KAPinfo1 KAPinfo2 KAPinfo3
```
Klima:
```
ID1 Info1 Info2 Klima3 Klima4 Klima5 Klima6 Klima7 Klima8
ID2 Info1 Info2 Klima3 Klima4 Klima5 Klima6 Klima7 Klima8
ID3 Info1 Info2 Klima3 Klima4 Klima5 Klima6 Klima7 Klima8
ID6 Info1 - - Klima3 Klima4 Klima5 Klima6 Klima7 Klima8
```
The merged tables should look like this:
```
ID1 Info1 Info2 Klima3 Klima4 Klima5 Klima6 Klima7 Klima8 KAPinfo1 KAPinfo2 KAPinfo3
ID2 Info1 Info2 Klima3 Klima4 Klima5 Klima6 Klima7 Klima8 KAPinfo1 KAPinfo2 KAPinfo3
ID3 Info1 Info2 Klima3 Klima4 Klima5 Klima6 Klima7 Klima8 KAPinfo1 KAPinfo2 KAPinfo3
ID4 Info1 Info2 - - - - - - - - - - - - - - - - KAPinfo1 KAPinfo2 KAPinfo3
ID5 Info1 Info2 - - - - - - - - - - - - - - - - KAPinfo1 KAPinfo2 KAPinfo3
ID6 Info1 Info2 Klima3 Klima4 Klima5 Klima6 Klima7 Klima8 KAPinfo1 KAPinfo2 KAPinfo3
```
Basically I want to overwrite the columns Info1 and Info2 in the right table (Klima) with the information from the left table (KAP) while keeping extra columns in the right table (Klima)<issue_comment>username_1: if you need a left join the sintax for join should be :
```
SELECT
[KAP$].F1,
[KAP$].F5,
[KAP$].F12,
[KAP$].F13,
[KAP$].F37,
[KAP$].F38,
[Klima$A3:H899].F1,
[Klima$A3:H899].F2,
[Klima$A3:H899].F3,
[Klima$A3:H899].F4,
[Klima$A3:H899].F5,
[Klima$A3:H899].F6,
[Klima$A3:H899].F7,
[Klima$A3:H899].F8
FROM [KAP$]
LEFT JOIN [Klima$A3:H899] ON ([KAP$].F1=[Klima$A3:H899].F1)
WHERE [KAP$].F8 LIKE 'Klima%'
```
*assuming that [Klima$A3:H899] is a valid table or equivalent*
Upvotes: 2 <issue_comment>username_2: Try this query:
```
SELECT [KAP$].F1,
[KAP$].F5,
[KAP$].F12,
[KAP$].F13,
[KAP$].F37,
[KAP$].F38,
[Klima$].F1,
[Klima$].F2,
[Klima$].F3,
[Klima$].F4,
[Klima$].F5,
[Klima$].F6,
[Klima$].F7,
[Klima$].F8
FROM
(SELECT F1,F5,F12,F13,F37,F38 FROM [KAP$] WHERE F8 LIKE 'klima') AS [KAP$]
LEFT JOIN
(SELECT F1, F2, F3, F4, F5, F6, F7, F8 FROM [Klima$A3:H899] WHERE F1 IS NOT NULL) AS [Klima$]
ON [KAP$].F1 = [Klima$].F1
```
Upvotes: 1
|
2018/03/14
| 636 | 1,367 |
<issue_start>username_0: I used the following command to replace all dates with another date string in a file using sed.
```
time sed -rn 's/\d{4}-\d{2}-\d{2}/2018-03-14/gp' date.txt
```
date.txt,
>
> (245176,1129,'CLEARED',to\_date('1996-09-10','YYYY-MM-DD'),35097600,'Y','Y','N',to\_date('1996-09-10','YYYY-MM-DD'),'Y',null,1121,null,null,null,null,1435,null,to\_date('1996-09-30','YYYY-MM-DD'),null,-1,35097600,null,1117,to\_date('1997-03-25','YYYY-MM-DD'),null,null,null,to\_date('1997-03-25','YYYY-MM-DD'),-1,-1,to\_date('1997-03-25','YYYY-MM-DD'),-1,1117,null,'ARRERGW',null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,204,null,null,null,null,null,null,null,null,null,null,null,null,null);
>
>
>
Pattern = "\d{4}-\d{2}-\d{2}"
Replace String = "2018-03-14"
But the above command is not working for me.. What did I wrong??<issue_comment>username_1: Specify range of digits as a character class `[0-9]`:
```
sed -En 's/[0-9]{4}-[0-9]{2}-[0-9]{2}/2018-03-14/gp' date.txt
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can also use `ssed` (super sed) if you want to use `perl` regex:
```
$ echo '2011-03-02' | ssed -Rn 's/\d{4}-\d{2}-\d{2}/2018-03-14/gp'
2018-03-14
```
It is less portable but more powerful, so you have to chose as always between flexibility or features/performances.
Upvotes: 1
|
2018/03/14
| 106 | 403 |
<issue_start>username_0: I am running Ubuntu 17.10.
I want to discover which version of Jupyter Notebook I am running using terminal commands.<issue_comment>username_1: On your terminal -
`jupyter --version`
Upvotes: 1 <issue_comment>username_2: According to the [Jupyter documentation](https://github.com/jupyterlab/jupyterlab) it is
```
jupyter notebook --version
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 157 | 598 |
<issue_start>username_0: I am quite new to C++ programming. So I just wanted to know if the memory allocation to structs is static or dynamic? This is the code that I basically have.
```
struct student {
double average;
struct subjects sub[course_numbers];
};
struct subjects {
char name;
int crn;
int credits;
};
```<issue_comment>username_1: On your terminal -
`jupyter --version`
Upvotes: 1 <issue_comment>username_2: According to the [Jupyter documentation](https://github.com/jupyterlab/jupyterlab) it is
```
jupyter notebook --version
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 455 | 1,375 |
<issue_start>username_0: I'm trying to set the Node version for an Azure Function as per the documentation, but it seems to be stuck on version v6.11.2
I've tried setting this Application Setting:
```
WEBSITE_NODE_DEFAULT_VERSION
```
To be 8.1.4
I've also tried added this to be package.json:
```
"engines":{"node":"8.1.4"}
```
Does anyone have any ideas?<issue_comment>username_1: I just verified your steps. I created a new function app (consumption plan, windows based) and set the
```
WEBSITE_NODE_DEFAULT_VERSION
```
to be 8.1.4:
[](https://i.stack.imgur.com/7E6UE.png)
and then opened Kudu to run "node -v" to check the result
[](https://i.stack.imgur.com/Z5ca0.png)
The runtime version this app is using is:
[](https://i.stack.imgur.com/Quebe.png)
Upvotes: 3 <issue_comment>username_2: You need to set your Function App to v2 (currently in preview):
[](https://i.stack.imgur.com/lVcPP.png)
v1 is locked to `6.11.2` as per [this link](https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node#node-version-and-package-management).
Upvotes: 3 [selected_answer]
|
2018/03/14
| 289 | 940 |
<issue_start>username_0: How to access function's parameter in another function that invoke it, here's what I mean
```
function one(a){
b();
}
function b(){
//'a' is the parameter of function one
if(a>0){
//do some stuff
}
}
//the parameter 'a' of function one goes here to catch an event
element.addEventListener('wheel', one);
```
Can I access function one parameter in function b?<issue_comment>username_1: Pass the parameter into b as well
```
function one(a){
b(a);
}
function b(a){
//'a' is the parameter of function one
if(a>0){
//do some stuff
}
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You have to pass `a` to function `b` as follows.
```
function one(a){
b(a);
}
function b(a){
//'a' is the parameter of function one
if(a>0){
//do some stuff
}
}
//the parameter 'a' of function one goes here to catch an event
element.addEventListener('wheel', one);
```
Upvotes: 1
|
2018/03/14
| 1,728 | 6,465 |
<issue_start>username_0: I am using recyclerview in kotlin and I am new to kotlin. I have used `button.setOnClickListner` method inside this. I want to call a method which is in my `mainActivity`. How should I do it
**I want to call below method which is in `mainActivity`**
```
fun sendOrder() {
Log.e("TAG", "SendOrder: " )
}
```
**my adapter is below**
```
class CustomAdapterJob(val jobList: ArrayList): RecyclerView.Adapter(){
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
val jobData :JobData = jobList[position]
holder?.textViewId?.text = jobData.id
holder?.textViewArea?.text = jobData.area
holder?.textViewCarType?.text = jobData.carType
holder?.textViewCarName?.text = jobData.carName
holder?. textViewDutyHours?.text = jobData.dutyHours
holder?.textViewWeeklyOff?.text = jobData.weeklyOff
holder?.textViewDriverAge?.text = jobData.driverAge
holder?.textViewDriverExperience?.text = jobData.drivingExperience
holder?.textViewOutstationDays?.text = jobData.outstationDays
holder?.textViewDutyDetails?.text = jobData.dutyDetails
holder?.button?.text =jobData.submit
if(jobData.submit == "true"){
holder?.button?.setVisibility(View.GONE);
}
holder?.button?.setOnClickListener( View.OnClickListener (){
Log.d("TAG", "job list position : ${jobList[position].id}")
var id = jobList[position].id
val p = Pattern.compile("-?\\d+")
val m = p.matcher(id)
while (m.find()) {
System.out.println(m.group())
sendOrder()
}
});
//To change body of created functions use File | Settings | File Templates.
}
override fun getItemCount(): Int {
return jobList.size//To change body of created functions use File | Settings | File Templates.
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
val v=LayoutInflater.from(parent?.context).inflate(R.layout.job\_card,parent,false)
return ViewHolder(v)
//To change body of created functions use File | Settings | File Templates.
}
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
val textViewId = itemView.findViewById(R.id.job\_id)
val textViewArea = itemView.findViewById(R.id.area)
val textViewCarType = itemView.findViewById(R.id.car\_type)
val textViewCarName = itemView.findViewById(R.id.car\_name)
val textViewDutyHours = itemView.findViewById(R.id.duty\_hours)
val textViewWeeklyOff = itemView.findViewById(R.id.weekly\_off)
val textViewDriverAge = itemView.findViewById(R.id.driver\_age)
val textViewDriverExperience = itemView.findViewById(R.id.driving\_experience)
val textViewOutstationDays = itemView.findViewById(R.id.outstation\_days)
val textViewDutyDetails = itemView.findViewById(R.id.duty\_details)
val button = itemView.findViewById(R.id.apply\_job)
}}
```
now how i have to call sendOrder() method in kotline<issue_comment>username_1: The easiest solution would be to your activity as parameter to your recycler view. Then you could easaly call that function. But obviously this is not a very good aproach, so you should prefer the following.
Create an interface which is implemented by your activity and called instead of the activities method. Within the implementation of the interface function you can call the activity function or whatever you like. As it is implemented by the activity itself you have full access to the whole activity context.
A short example how this could be implemented is already answered [here](https://stackoverflow.com/a/12142530/3883569)
Upvotes: 0 <issue_comment>username_2: First you need to create a context:
```
private val context: Context
```
Then add this context, along with other variables you might have, to your adapter constructor:
```
class Adapter(..., context: Context)
```
Inside you while loop:
```
while (m.find()) {
System.out.println(m.group)
if (context is MainActivity)
{
(context as MainActivity).SendOrder()
}
}
```
Apologies for any syntax error, etc. My Kotlin is still a little rough.
Upvotes: 0 <issue_comment>username_3: you can do like this:
```
holder?.button?.setOnClickListener( View.OnClickListener (){
Log.d("TAG", "job list position : ${jobList[position].id}")
var id = jobList[position].id
val p = Pattern.compile("-?\\d+")
val m = p.matcher(id)
while (m.find()) {
System.out.println(m.group())
mySendOrder()
}
});
public void mySendOrder(){
}
```
and then in main activity:
```
yourCustomAdapter = new YourCustomAdapter(){
public void mySendOrder(){
sendOrder();
}
}
```
Upvotes: 0 <issue_comment>username_4: In case if you don't need Context or Activity object in your adapter. You can pass callback as parameters. May be something like this
```
class MyAdapter(private val sendOrder: () -> Unit = {}) : BaseAdapter() {
fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
sendOrder()
}
}
```
Then implement callback in Activity
```
fun onCreate(...) {
recyclerView.adapter = MyAdapter() {
// Do something
}
}
```
Upvotes: 0 <issue_comment>username_5: Its better you create a listener and pass it to the adapter.
**Interface**
```
interface ActivityInteractor {
fun onInteraction(data: Any?)
}
```
**Implement the interface in your activity**
```
class MainActivity : Activity(), ActivityInteractor {
override fun onCreate(savedInstance : Bundle) {
CustomAdapterJob(jobList, this)
}
override fun onInteraction(data: Any?) {
// you can do any activity related tasks here
sendOrder()
}
}
```
**Accept the listener in your adapter**
```
class CustomAdapterJob(val jobList: ArrayList, val activityInteractor: ActivityInteractor) : RecyclerView.Adapter() {
holder?.button?.setOnClickListener( View.OnClickListener () {
Log.d("TAG", "job list position : ${jobList[position].id}")
var id = jobList[position].id
val p = Pattern.compile("-?\\d+")
val m = p.matcher(id)
while (m.find()) {
System.out.println(m.group())
//sendOrder()
activityInteractor.onInteraction(jobList[position].id)
}
});
}
```
Instead of creating the new interface you can implement onClickListener in the activity and can pass it as a parameter to the adapter class. In the adapter, you can set this onClick listener to your button.
Use kotlin data binding concept to avoid those boilerplate codes like findViewById. please check this [link](https://medium.com/@jencisov/androids-data-binding-with-kotlin-df94a24ffc0f)
Upvotes: 2
|
2018/03/14
| 420 | 1,150 |
<issue_start>username_0: With regex - replace, I am trying to format a number like this:
The leading number should be separated by a +. Moreover, the last number should be separated by a + as well. The more tricky part is, that adjacent 1s to the + to the middle part should be removed, without touching the first and the last number, e.g.,
011023040 -> 0+02304+0
111023920443 -> 1+02392044+3
13242311 -> 1+32423+1
I almost achieved this with the following regex:
```
'^([0-9]{1})([1]+)?([0-9*)(0-9]{1}$'
```
And replace this with
```
'\1+\3+\4'
```
However, I have a problem with the last example, as this returns:
```
1+324231+1
```
However, the one before the second + should be removed.
Can anyone help me with this problem?<issue_comment>username_1: I managed to group the numbers in the following way
```
^(\d)(1*)(\d+)(\d)$
```
by using multiline and global flags.
The replacement should look like `\1+\3+\4`
Upvotes: 0 <issue_comment>username_2: You have to use a non-greedy quantifier:
```
^([0-9])1*([0-9]*?)1*([0-9])$
^^
```
[Live demo](https://regex101.com/r/dHPHMH/1)
Upvotes: 3 [selected_answer]
|
2018/03/14
| 840 | 3,129 |
<issue_start>username_0: I'm trying to initialise a value in dictionary as follow,
```
var og:image: String
```
But after `og:` it tries to assign the type considering `og` as the variable to site\_name, which is obviously wrong.
>
> Is there a way to assign `og:image` as variable to `String` type using
> special or escape characters?
>
>
>
In [reference](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#//apple_ref/swift/grammar/decimal-digits) to this, apple does not provide any meaningful explanations to variable naming conventions in such a situation.
Edit-1:
Here is code snippet to clarify dictionary `usage` is in JSON parsing data structure,
```
struct Metadata: Decodable{
var metatags : [enclosedTags]
}
struct enclosedTags: Decodable{
var image: String
var title: String
var description: String
var og:site_name: String
}
```<issue_comment>username_1: You cannot use : (colon). But if you really want:
```
var ogCOLONimage: String
```
Joking apart. You could use a Dictionary or something like that:
```
var images: [String: String] = ["og:image" : "your string"]
```
Now you can access your `og:image` data with `images["og:image"]`.
Upvotes: 1 <issue_comment>username_2: Swift allow you to use almost any character when naming variables. You can even use Unicode characters.
However, there are a few restrictions:
>
> Constant and variable names can’t contain whitespace characters, mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters. Nor can they begin with a number, although numbers may be included elsewhere within the name.
>
>
>
Said that, it is not possible to use `:` in the name of a variable. However, you can use a Unicode character similar to that symbol. Depending on what you want it for, this may be a valid solution.
Here you have a list of the Unicode characters similar to `:` that can be used in the name of a variable:
* `︓`
* `﹕`
* `:`
(<https://www.compart.com/en/unicode/based/U+003A>)
Based on the example you provided it would be this:
```
struct Metadata: Decodable{
var metatags : [enclosedTags]
}
struct enclosedTags: Decodable{
var image: String
var title: String
var description: String
var og:site_name: String
}
```
Upvotes: 0 <issue_comment>username_3: Turns out swift has it's own feature in terms of naming specificity of variables in structs i.e. `CodingKeys`, so in terms for me the below naming convention worked,
```
struct Metadata: Decodable{
var metatags: [enclosedTags]
}
struct enclosedTags: Decodable{
let image: String
let title: String
let description: String
let siteName: String
private enum CodingKeys : String, CodingKey{
case image = "og:image", title = "og:title", description = "og:description", siteName = "og:site_name"
}
```
This was rightfully pointed out by `@hamish` in comments (Thanks mate!)
Upvotes: 1 [selected_answer]
|
2018/03/14
| 441 | 1,558 |
<issue_start>username_0: I made this for i can fix navbar on site when i scroll page
How i can improve this code, can reduce it somehow?
```
// some code...
var menu_offset_top_default = $('.main_menu').offset().top;
$(window).scroll(function() {
var menu_offset_top = $('.main_menu').offset().top;
if ($(window).scrollTop() >= menu_offset_top) {
$('.main_menu').addClass('fixed-top');
}
if ($(window).scrollTop() < menu_offset_top_default || $(window).scrollTop() <= 0) {
$('.main_menu').removeClass('fixed-top');
}
});
```<issue_comment>username_1: You can just do it as follows with simple if-else block.
```
$(window).scroll(function() {
if ($(window).scrollTop() >= $('.main_menu').offset().top) {
$('.main_menu').addClass('fixed-top');
}
else {
$('.main_menu').removeClass('fixed-top');
}
});
```
Upvotes: 0 <issue_comment>username_2: You could use css `position: sticky` instead and get remove the jquery code
>
> A stickily positioned element is an element whose computed position
> value is sticky. It's treated as relatively positioned until its
> containing block crosses a specified threshold (such as setting top to
> value other than auto) within its flow root (or the container it
> scrolls within), at which point it is treated as "stuck" until meeting
> the opposite edge of its containing block. [Source](https://developer.mozilla.org/en-US/docs/Web/CSS/position).
>
>
>
An example:
<https://codepen.io/simevidas/pen/JbdJRZ>
Upvotes: 2 [selected_answer]
|
2018/03/14
| 1,088 | 4,586 |
<issue_start>username_0: In Nexus 3 backup procedure has changed.
In Nexus 2 recommended was to run a OS scheduled task / cron job to rsync some directories to a backup location.
In Nexus 3 the recommended way seems to be to create to schedule a predefined Nexus Task *Export configuration & metadata for backup Task*. And then also create a cron job to backup what gets exported with this task.
Is it still possible in Nexus 3 to do a old style backup? Shutdown the server and backup certain directories? And then for restore just put everything back? Will that work?
Or use a command line to run this task?
The way this is done in Nexus 3 does not seem to be thought through very well. You need to do a lot more to do what could be done with a single cron job in Nexus 2:
1. Create a scheduled task to export data.
2. Create a cron job to backup exported data.
3. Make sure that scheduled task runs and finished before the cron job.
See for example <https://help.sonatype.com/display/NXRM3/Restore+Exported+Databases>
See also [Nexus Repository 3 backup](https://stackoverflow.com/questions/48331434/nexus-repository-3-backup)<issue_comment>username_1: If you back up the entire data (sonatype-work) directory this should work as you wish. However, since the data directory is large and has many moving parts, it is safer to use the task, otherwise you may get copies of things in motion which could then corrupt and your backup would not work. The copy of the work directory as far as I know is only recommended for servers that are down, which isn't an option for many bigger companies.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Copying the entire folder did not work for me and resulted in orientdb problems. Last year I started to create [N3DR](https://github.com/username_2/n3dr). Version 3.5.0 has just been released.
Upvotes: 1 <issue_comment>username_3: <https://help.sonatype.com/plugins/servlet/mobile?contentId=5412146#content/view/5412146>
In case link becomes bad etc. (From Oct 20, 2017)
---
Nexus Repository stores data in blob stores and keeps some metadata and configuration information separately in databases. You must back up the blob stores and metadata databases together. Your backup strategy should involve backing up both your databases and blob stores together to a new location in order to keep the data intact.
Complete the steps below to perform a backup:
**Blob Store Backup**
You must back up the filesystem or object store containing the blobs separately from Nexus Repository.
* For File blob stores, back up the directory storing the blobs.
+ For a typical configuration, this will be $data-dir/blobs.
* For S3 blob stores, you can use bucket versioning as an alternative to backups. You can also mirror the bucket to another S3 bucket instead.
For cloud-based storage providers (S3, Azure, etc.), refer to their documentation about storage backup options.
**Node ID Backup**
Each Nexus Repository instance is associated with a distinct ID. You must back up this ID so that blob storage metrics (the size and count of blobs on disk) and Nexus Firewall reports will function in the event of a restore / moving Nexus Repository from one server to another. The files to back up to preserve the node ID are located in the following location (also see Directories):
`$data-dir/keystores/node/`
To use this backup, place these files in the same location before starting Nexus Repository.
**Database Backup**
The databases that you export have pointers to blob stores that contain components and assets potentially across multiple repositories. If you don’t back them up together, the component metadata can point to non-existent blob stores. So, your backup strategy should involve backing up both your databases and blob stores together to a new location in order to keep the data intact.
Here’s a common scenario for backing up custom configurations in tandem with the database export task:
1. Configure the appropriate backup task to export databases:
* Use the Admin - Export databases for backup task for OrientDB databases
* Use the Admin - Backup H2 Database task for H2 databases PRO
3. Run the task to export the databases to the configured folder.
4. Back up custom configurations in your installation and data directories at the same time you run the export task.
5. Back up all blob stores.
Store all backed up configurations and exported data together.
Write access to databases is temporarily suspended until a backup is complete. It’s advised to schedule backup tasks during off-hours.
Upvotes: 0
|
2018/03/14
| 548 | 2,304 |
<issue_start>username_0: There is a ListBox that its ItemsSource is bind to a collection,
we need always selected first item when binding is changed, for example at first ListBox has 3 items, second item is selected from ListBox by user, after that binding is changed and ListBox has 1 items, but second item is selected yet.( and also second item is emty but is not hidden)
```
```
Can anyone help that how can resolve this issue?<issue_comment>username_1: first make an event for change binding and set the index in the change\_event funciton
```
private void AddEventHandler()
{
myListBox.BindingContextChanged += new EventHandler(BindingContext_Changed);
}
private void BindingContext_Changed(object sender, EventArgs e)
{
myListBox.SelectedIndex = 0;
}
```
Upvotes: -1 <issue_comment>username_2: Firstly do you have any specific reason to add ListBoxItem in xaml itself.
If not please use observable collection to binding to Itemsource property of your listbox.
Also bind the selected item property of your ListBox to the property from your viewmodel.
Once your collection is changed set binded selected item property of your viewmodel to first item.
Also set,
IsSynchronizedWithCurrentItem="True" on your listbox in xaml.
This should work !
Upvotes: -1 <issue_comment>username_3: You are adding items inside the xaml statically. Please create a collection property in your view model, bind it to the items source and bind the SelectedItem property of the listbox in the view model like this:
```
```
Whenever the ItemCollection property is set, the view model could also set its SelectedItem property:
```
public class Item { ... }
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private IEnumerable itemCollection;
public IEnumerable ItemCollection
{
get { return itemCollection; }
set
{
itemCollection = value;
PropertyChanged?.Invoke(this,
new PropertyChangedEventArgs(nameof(ItemCollection)));
SelectedItem = itemCollection.FirstOrDefault(); // here
}
}
private Item selectedItem;
public Item SelectedItem
{
get { return selectedItem; }
set
{
selectedItem = value;
PropertyChanged?.Invoke(this,
new PropertyChangedEventArgs(nameof(SelectedItem)));
}
}
}
```
Upvotes: 0
|
2018/03/14
| 650 | 2,151 |
<issue_start>username_0: I have many to many connect with between user - cityarea.
I have also area which connect cityarea (One cityarea can connect only one area).
I have this database structure:
**users**
* id
* username
* password
**cityareas**
* id
* name
* area\_id
**cityarea\_user**
* id
* cityarea\_id
* user\_id
**areas**
* id
* name
Next I have Models
**User**
```
public function cityareas()
{
return $this->belongsToMany('App\Cityarea');
}
```
**Cityarea**
```
public function area()
{
return $this->belongsTo('App\Area');
}
public function users()
{
return $this->belongsToMany('\App\User');
}
```
**Area**
```
public function cityareas()
{
return $this->hasMany('App\Cityarea');
}
```
**QUESTION:**
How I can get all users where `areas.name = "South"` with Eloquent ?
Thanks!!<issue_comment>username_1: By using [whereHas](https://laravel.com/docs/5.6/eloquent-relationships#querying-relations), you can do:
```
$users = User::whereHas('cityareas.area', function ($query) {
$query->where('name', 'South');
})->get();
```
Upvotes: 2 <issue_comment>username_2: This is exactly what the [belongs to many](https://laravel.com/docs/5.6/eloquent-relationships#many-to-many) relationships is built for.
You simply have to do, `Cityarea::where('name', 'South')->first()->users`;
If you want to do something further with the query, e.g. sort by users created at, you can do
```
Cityarea::where('name', 'South')->first()->users()->orderBy('creaated_at', desc')->get();
```
Note that if there is no such Cityarea with name 'South', the `->first()` query above will return null and therefore will fail to fetch the users.
A more performant way to do it programmatically is to use the `whereHas` approach as discussed in the comments below.
Upvotes: -1 <issue_comment>username_3: **<NAME>** solution is perfect, but you can use `with()` method of eloquent If you also need `cityarea` collection along with users collection.
```
$users = User::with('cityareas')->whereHas('cityareas.area', function ($query) {
$query->where('name', 'South');
})->get();
```
Upvotes: 1 [selected_answer]
|
2018/03/14
| 338 | 1,521 |
<issue_start>username_0: Is there any particular time period for the app in the play store to be updated (considering the fact that the developer or the company owning the app in not bothered of the update as they are satisfied with their app). Is their any chances of the app being removed from the play store due to this.<issue_comment>username_1: There is no particular time interval between updates for play store apps. How ever some users checks for the last updated date before downloading an app and if the app was last updated a long time ago, they might not download the app, because they may think that the developer has stopped supporting the app. And there is no such app that is completely bug free. if you have one, CONGRATZZZZ... During the initial stages of your apps release, ie; when the app is in versions 1,2... you should pay close attention to your playstore dashboard to see the metrics, provides a lot of valuable information regarding your app's performance in devices and in playstore, and make changes to your app and fix bugs if there is any, and publish new updates frequently,at that time your app update interval will be very short. you See [this article](https://savvyapps.com/blog/how-often-should-you-update-your-app) for more info about app update intervals
Upvotes: 2 <issue_comment>username_2: There is no particular time for give an update to the app on play store.
Whenever you add some new features and you have completed the testing phase then you can update your app.
Upvotes: 1
|
2018/03/14
| 791 | 3,033 |
<issue_start>username_0: As the title asks. Python has a lot of special methods, `__add__`, `__len__`, `__contains__` et c. Why is there no `__max__` method that is called when doing max? Example code:
```
class A:
def __max__():
return 5
a = A()
max(a)
```
It seems like `range()` and other constructs could benefit from this. Am I missing some other effective way to do max?¨
**Addendum 1:**
As a trivial example, `max(range(1000000000))` takes a long time to run.<issue_comment>username_1: I have no authoritative answer but I can offer my thoughts on the subject.
There are several built-in functions that have no corresponding special method. For example:
* `max`
* `min`
* `sum`
* `all`
* `any`
One thing they have in common is that they are reduce-like: They iterate over an iterable and "reduce" it to one value. The point here is that these are more of a building block.
For example you often wrap the iterable in a generator (or another comprehension, or transformation like `map` or `filter`) before applying them:
```
sum(abs(val) for val in iterable) # sum of absolutes
any(val > 10 for val in iterable) # is one value over 10
max(person.age for person in iterable) # the oldest person
```
That means most of the time it wouldn't even call the `__max__` of the iterable but try to access it on the generator (which isn't implemented and cannot be implemented).
So there is simply not much of a benefit if these were implemented. And in the few cases when it makes sense to implement them it would be more obvious if you create a custom method (or property) because it highlights that it's a "shortcut" or that it's different from the "normal result".
For example these functions (`min`, etc.) have `O(n)` run-time, so if you can do better (for example if you have a sorted list you could access the `max` in `O(1)`) it might make sense to document that explicitly.
Upvotes: 2 <issue_comment>username_2: Some operations are not basic operations. Take `max` as an example, it is actually an operation based on comparison. In other words, when you get a **max** value, you are actually getting a **biggest** value.
So in this case, why should we implement a specified `max` function but not override the behave of comparison?
---
Think in another direction, what does `max` really mean? For example, when we execute `max(list)`, what are we doing?
I think we are actually checking `list`'s elements, and the `max` operation is not related to `list` itself at all.
`list` is just a container which is unnecessary in `max` operation. It is `list` or `set` or something else, it doesn't matter. What really useful is the elements inside this container.
So if we define a `__max__` action for `list`, we are actually doing another totally different operation. We are asking a container to give us advice about max value.
I think in this case, as it is a totally different operation, it should be a method of container instead of overriding built-in function's behave.
Upvotes: 1
|
2018/03/14
| 887 | 3,535 |
<issue_start>username_0: Amateur JavaScript guy here. I've written a private NodeJS module that manages our DB connection strings (Decrypt passwords & connection string construction), but due to the nature of the decrypt, the module returns a promise for the db connection string.
We are using Sails, and the config happens in the export of a variables object:
```
module.exports.variables = { dbstring: 'mongodb://user:password@host/mydb' }
```
But now with the promise, it's a little trickier to squeeze a string in here. I've tried putting the 'module.exports.variables' block, inside a '.then' block:
```
myConfigModule.getDBString('mysql-master').then( result => {
module.exports.variables = { dbstring: result }
}
```
but then the rest of the sails app fails to start up, with it trying to access variables inside 'module.exports.variables', and only gets 'undefined'. I assume because the rest of the app isn't waiting for the promise to be fulfilled.
Any suggestions?<issue_comment>username_1: I have no authoritative answer but I can offer my thoughts on the subject.
There are several built-in functions that have no corresponding special method. For example:
* `max`
* `min`
* `sum`
* `all`
* `any`
One thing they have in common is that they are reduce-like: They iterate over an iterable and "reduce" it to one value. The point here is that these are more of a building block.
For example you often wrap the iterable in a generator (or another comprehension, or transformation like `map` or `filter`) before applying them:
```
sum(abs(val) for val in iterable) # sum of absolutes
any(val > 10 for val in iterable) # is one value over 10
max(person.age for person in iterable) # the oldest person
```
That means most of the time it wouldn't even call the `__max__` of the iterable but try to access it on the generator (which isn't implemented and cannot be implemented).
So there is simply not much of a benefit if these were implemented. And in the few cases when it makes sense to implement them it would be more obvious if you create a custom method (or property) because it highlights that it's a "shortcut" or that it's different from the "normal result".
For example these functions (`min`, etc.) have `O(n)` run-time, so if you can do better (for example if you have a sorted list you could access the `max` in `O(1)`) it might make sense to document that explicitly.
Upvotes: 2 <issue_comment>username_2: Some operations are not basic operations. Take `max` as an example, it is actually an operation based on comparison. In other words, when you get a **max** value, you are actually getting a **biggest** value.
So in this case, why should we implement a specified `max` function but not override the behave of comparison?
---
Think in another direction, what does `max` really mean? For example, when we execute `max(list)`, what are we doing?
I think we are actually checking `list`'s elements, and the `max` operation is not related to `list` itself at all.
`list` is just a container which is unnecessary in `max` operation. It is `list` or `set` or something else, it doesn't matter. What really useful is the elements inside this container.
So if we define a `__max__` action for `list`, we are actually doing another totally different operation. We are asking a container to give us advice about max value.
I think in this case, as it is a totally different operation, it should be a method of container instead of overriding built-in function's behave.
Upvotes: 1
|
2018/03/14
| 849 | 3,436 |
<issue_start>username_0: In Backpack CMS framework I have created a table using migration fields like : 'parent\_id' and 'is\_active'.
I have added these fields in the crud controller using the following command:
```
$this->crud->addFields(array(
['name' => 'title',
'label' => 'Title',
'type'=>'text'],
['name' => 'parent_id',
'label' => 'Parent ID',
'type'=> 'number'],
['name' => 'is_active',
'label' => 'Is Active',
'type'=>'number']
), 'update/create/both');
```
It should work in edit mode and create mode like my other tables. It shows the defined fields in the create and update form but unfortunately they doesn't work and always return the default value or previous value in the record.
I've tried adding the field in single format but there was no use.<issue_comment>username_1: I have no authoritative answer but I can offer my thoughts on the subject.
There are several built-in functions that have no corresponding special method. For example:
* `max`
* `min`
* `sum`
* `all`
* `any`
One thing they have in common is that they are reduce-like: They iterate over an iterable and "reduce" it to one value. The point here is that these are more of a building block.
For example you often wrap the iterable in a generator (or another comprehension, or transformation like `map` or `filter`) before applying them:
```
sum(abs(val) for val in iterable) # sum of absolutes
any(val > 10 for val in iterable) # is one value over 10
max(person.age for person in iterable) # the oldest person
```
That means most of the time it wouldn't even call the `__max__` of the iterable but try to access it on the generator (which isn't implemented and cannot be implemented).
So there is simply not much of a benefit if these were implemented. And in the few cases when it makes sense to implement them it would be more obvious if you create a custom method (or property) because it highlights that it's a "shortcut" or that it's different from the "normal result".
For example these functions (`min`, etc.) have `O(n)` run-time, so if you can do better (for example if you have a sorted list you could access the `max` in `O(1)`) it might make sense to document that explicitly.
Upvotes: 2 <issue_comment>username_2: Some operations are not basic operations. Take `max` as an example, it is actually an operation based on comparison. In other words, when you get a **max** value, you are actually getting a **biggest** value.
So in this case, why should we implement a specified `max` function but not override the behave of comparison?
---
Think in another direction, what does `max` really mean? For example, when we execute `max(list)`, what are we doing?
I think we are actually checking `list`'s elements, and the `max` operation is not related to `list` itself at all.
`list` is just a container which is unnecessary in `max` operation. It is `list` or `set` or something else, it doesn't matter. What really useful is the elements inside this container.
So if we define a `__max__` action for `list`, we are actually doing another totally different operation. We are asking a container to give us advice about max value.
I think in this case, as it is a totally different operation, it should be a method of container instead of overriding built-in function's behave.
Upvotes: 1
|
2018/03/14
| 958 | 2,352 |
<issue_start>username_0: I have two table as below
```
table 1: raw
dateCol id
1 01.01.2001 00:00:00 AAPL
2 02.01.2001 00:00:00 MSFT
3 03.01.2001 00:00:00 INFY
table 2: universe
udateCol uid
1 01.01.2001 00:00:00 AAPL
2 02.01.2001 00:00:00 GOOGL
3 03.01.2001 00:00:00 INFY
```
i want to extract the count of ids from raw and count of ids from raw matching with uids in universe. So i tried the below query in Mysql:
```
select universe.udateCol, count(raw.id) as rawCount, count(universe.uid) as uniCount from universe left join raw on universe.udateCol = raw.dateCol AND raw.id = universe.uid group by universe.udateCol order by universe.udateCol;
```
using the above query, i'm getting the following output
```
udateCol rawCount uniCount
1 01.01.2001 00:00:00 1 1
2 02.01.2001 00:00:00 0 1
3 03.01.2001 00:00:00 1 1
```
But i want the output to be like:
```
udateCol rawCount uniCount
1 01.01.2001 00:00:00 1 1
2 02.01.2001 00:00:00 1 0
3 03.01.2001 00:00:00 1 1
```
If any one want to check live, then can check [here](http://rextester.com/live/VMT37437)
Edit1:
i want to get the count which exist in my raw table for each date, and count of those which are matching in universe table on the same date<issue_comment>username_1: Try this:
```
SELECT DATE(A.dateCol) dateCol, COUNT(A.id) rawCount, COUNT(B.id) uniCount
FROM raw A LEFT JOIN universe B
ON A.id=B.uid AND DATE(A.dateCol)=DATE(B.udateCol)
GROUP BY DATE(A.dateCol);
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Not an answer. Too long for a comment, and a little tired of trying to draw blood from this stone...
Consider the following:
```
drop table if exists raw;
drop table if exists universe;
create table raw(dateCol date, id VARCHAR(20),PRIMARY KEY(datecol,id));
create table universe(udateCol date, uid VARCHAR(20),PRIMARY KEY(udatecol,uid));
insert into raw values
('20010101','AAPL'),
('20010102','MSFT'),
('20010103','INFY'),
('20010104','HOG');
insert into universe values
('20010101','AAPL'),
('20010102','GOOGL'),
('20010103','INFY'),
('20010105','HOG');
```
Note: I have made assumptions about the PRIMARY KEY in each case. If this is incorrect, please clarify.
Given this data set, what should the desired result look like? Think before you answer.
Upvotes: 0
|
2018/03/14
| 539 | 2,330 |
<issue_start>username_0: I am using firebase notification. When applicationState is background it's working fine. But when app is not running / terminated func getPushNotiData(\_ notification: NSNotification) is not being call
Implementing NotificationCenter in appDelegate file to handle notification in dashView
```
func application(_ application: UIApplication, didReceiveRemoteNotification
userInfo: [AnyHashable : Any]) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue:
"getPushNotificationData"), object: nil, userInfo: userInfo)
}
```
And if app is not running / terminated Implementing NotificationCenter in didFinishLaunchingWithOptions delegate method
```
if (launchOptions != nil)
{
let userInfo = launchOptions![.remoteNotification] as? [AnyHashable: Any]
if userInfo != nil {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "getPushNotificationData"), object: nil, userInfo: userInfo)
}
}
```
Handling NotificationCenter in dashView
```
override func viewDidAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(self.getPushNotiData(_:)), name: NSNotification.Name(rawValue: "getPushNotificationData"), object: nil)
}
@objc func getPushNotiData(_ notification: NSNotification){
if let url = notification.userInfo!["url"] as? String {
let destination = storyboard?.instantiateViewController(withIdentifier: "NotificationDlsViewController") as! NotificationDlsViewController
destination.notiUrl = url
self.navigationController?.pushViewController(destination, animated: true)
}
}
```<issue_comment>username_1: If the app is not running (killed state) , you can't execute any methods or code , only if the user clicks the push notification you can receive object of it in `didFinishLaunchingWithOptions` launchingOptions and handle it ....
Upvotes: 3 [selected_answer]<issue_comment>username_2: It's probabile that when you check `launchOptions` in your `didFinishLaunchingWithOptions` your ViewController is not loaded yet so `viewDidAppear` has not been called and the ViewController is not registered in the Notification Center. Try to put some print statement and check the order of the calls when the app is launched from the notification.
Upvotes: 0
|
2018/03/14
| 451 | 1,581 |
<issue_start>username_0: I am facing an issue while comparing two images using OpenCV in Python 2.7
Here is my code:
```
import cv2
import numpy as np
img1 = cv2.imread("./spot/image1.jpg")
img2 = cv2.imread("./spot/image2.jpg")
diff = cv2.subtract(img1, img2)
result = not np.any(diff)
if result is True:
print "The images are the same"
else:
cv2.imwrite("result.jpg", difference)
print "the images are different"
```
And I am getting this error:
```
Traceback (most recent call last):
File "E:\PrgLang\Python\compareImage.py", line 7, in
diff = cv2.subtract(img1,img2)
error: OpenCV(3.4.1) C:\build\master\_winpack-bindings-win64-vc14-static\opencv\modules\core\src\arithm.cpp:659: error: (-209) The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array' in function cv::arithm\_op
```<issue_comment>username_1: If the app is not running (killed state) , you can't execute any methods or code , only if the user clicks the push notification you can receive object of it in `didFinishLaunchingWithOptions` launchingOptions and handle it ....
Upvotes: 3 [selected_answer]<issue_comment>username_2: It's probabile that when you check `launchOptions` in your `didFinishLaunchingWithOptions` your ViewController is not loaded yet so `viewDidAppear` has not been called and the ViewController is not registered in the Notification Center. Try to put some print statement and check the order of the calls when the app is launched from the notification.
Upvotes: 0
|
2018/03/14
| 408 | 1,424 |
<issue_start>username_0: Appending works fine with this method:
```
for poss in pos:
df = df.append([[poss,'1']], ignore_index=True)
```
Is this possible to write as a one-liner? This way is showing a syntax error.
```
df = df.append([[poss,'1']], ignore_index=True) for poss in pos
```<issue_comment>username_1: No, it's not. It seems like you are looking to use list comprehension syntax to single-linify multiple method calls. You can't do this.
Instead, what you can do is aggregate your list elements into a dataframe and append in one go. It is also inefficient to `df.append` within a loop versus building a dataframe from list of lists and appending just once.
```
df = df.append(pd.DataFrame(pos, columns=player_df.columns))
```
This assumes `pos` is a list of lists with columns aligned with `df`.
If you need to add an extra column "in one line", try this:
```
df = df.append(pd.DataFrame(pos, columns=player_df.columns)).assign(newcol=1)
```
Upvotes: 1 <issue_comment>username_2: I think it is possible, but I cannot test it, because I do not work with those datatypes and normal `list.append` does not return the resulting list.
```
from functools import reduce # Python3 only
df = reduce(lambda d, p: d.append([[p,'1']], ignore_index=True), pos, df)
```
Anyway, the for loop is much better. Also this is just a rewrite to one line. There might be other ways to modify your data.
Upvotes: 0
|
2018/03/14
| 363 | 1,318 |
<issue_start>username_0: I have Data of different Stocks of various dates
and each stock is stored in different Text Files (not in CSV)
How to Gather up Data in some way into a Single File<issue_comment>username_1: No, it's not. It seems like you are looking to use list comprehension syntax to single-linify multiple method calls. You can't do this.
Instead, what you can do is aggregate your list elements into a dataframe and append in one go. It is also inefficient to `df.append` within a loop versus building a dataframe from list of lists and appending just once.
```
df = df.append(pd.DataFrame(pos, columns=player_df.columns))
```
This assumes `pos` is a list of lists with columns aligned with `df`.
If you need to add an extra column "in one line", try this:
```
df = df.append(pd.DataFrame(pos, columns=player_df.columns)).assign(newcol=1)
```
Upvotes: 1 <issue_comment>username_2: I think it is possible, but I cannot test it, because I do not work with those datatypes and normal `list.append` does not return the resulting list.
```
from functools import reduce # Python3 only
df = reduce(lambda d, p: d.append([[p,'1']], ignore_index=True), pos, df)
```
Anyway, the for loop is much better. Also this is just a rewrite to one line. There might be other ways to modify your data.
Upvotes: 0
|
2018/03/14
| 4,133 | 5,896 |
<issue_start>username_0: I have a file with a number of matrices separated by a newline. I can plot any one of these matrices as a heatmap as shown in <http://gnuplot.sourceforge.net/demo/heatmaps.html>
However, now I would like to visualize all the matrices together on the same graph by plotting each matrix at increasing values of z, where each point is a coloured dot. I am trying to achieve something similar to the following question,
[Plot 3D Grid Data as Heat Map using gnuplot](https://stackoverflow.com/questions/29088260/plot-3d-grid-data-as-heat-map-using-gnuplot)
but without the cubes, as dots are sufficient.
This is the data for one matrix:
```
7.606193E-01 -2.706752E-01 1.605924E-01 9.973101E-01 6.646065E-01 -4.177295E-01 -5.101588E-01 -5.338852E-01 -9.443505E-01 6.273689E-01 4.401633E-01 9.428387E-01 -1.783963E-01 1.702644E-01 -9.304313E-01 3.995178E-01
-1.574189E-01 -3.911715E-01 -5.581077E-01 -3.719385E-02 7.144460E-01 -3.147125E-01 4.237802E-01 6.533050E-01 5.385187E-01 8.391651E-02 -5.773817E-01 1.456075E-01 6.028832E-01 5.313966E-01 3.894490E-01 7.329324E-01
8.147309E-01 -8.286917E-01 -9.708381E-01 -6.634787E-02 8.603123E-01 8.952920E-01 6.777392E-01 4.347730E-01 -9.271995E-01 8.899992E-01 5.525438E-01 -7.496139E-01 7.592094E-01 3.412833E-01 1.220876E-01 7.281239E-01
6.915789E-01 3.365000E-01 -4.771788E-01 7.674200E-01 8.059295E-01 3.545558E-01 2.764826E-01 3.801301E-01 -6.679796E-01 1.163551E-01 -5.292152E-01 -3.500514E-01 -8.614216E-01 -8.356531E-02 -8.391827E-01 7.258298E-01
1.219247E-01 5.344889E-01 8.977039E-01 -5.708083E-01 -6.809624E-01 -5.687558E-01 3.830947E-01 9.990373E-01 -6.038938E-01 9.162573E-01 -4.214753E-01 4.186414E-01 -4.224649E-01 -9.376176E-01 -1.170071E-01 3.825447E-01
-1.046988E-01 5.206562E-01 -9.832160E-01 -6.588389E-01 6.122716E-01 2.926736E-01 -8.736564E-01 9.977460E-01 8.937872E-01 -8.719974E-02 -7.742046E-01 -9.490100E-01 6.090313E-01 8.220433E-01 7.705420E-01 5.937839E-01
8.668659E-01 -5.811435E-01 -4.980876E-01 -5.458175E-02 -1.702000E-01 -9.681295E-01 -9.898823E-01 8.014537E-01 6.852101E-01 3.412942E-01 -4.313660E-01 6.886256E-01 -8.974125E-01 8.012120E-01 7.893018E-01 -1.869330E-01
-1.168977E-01 -8.988775E-01 -2.580437E-01 -8.019403E-02 4.935626E-01 3.774684E-01 5.609375E-02 8.018482E-01 -9.803250E-01 -8.223162E-01 -7.441623E-02 7.592162E-01 -3.084599E-01 2.728176E-01 -7.114622E-01 -4.335231E-01
9.071215E-01 7.551532E-01 1.640213E-02 -2.627113E-01 -1.102158E-01 -3.576760E-02 7.584369E-02 3.586933E-01 9.412469E-01 -7.919924E-01 -7.883645E-01 -4.693788E-01 -1.549372E-01 1.823575E-01 4.206510E-01 -4.489097E-01
2.449895E-01 -4.566137E-02 5.805491E-01 3.808071E-01 4.885185E-01 9.662528E-01 -9.306209E-02 2.467101E-02 2.380986E-01 -9.053143E-01 -3.499831E-01 -4.224079E-01 -2.420047E-01 1.568254E-01 -1.696076E-01 -2.344714E-01
-1.045739E-01 -2.254802E-01 -5.760012E-01 7.194423E-01 9.792110E-01 -7.514746E-01 -1.239218E-01 -3.922474E-01 -6.499553E-01 5.908898E-01 8.695512E-01 -6.576686E-01 7.101708E-01 6.389254E-01 -3.228182E-01 3.177363E-01
-7.059239E-01 -8.482834E-01 -1.630977E-01 -9.891499E-01 -5.450270E-01 -6.303106E-01 1.596098E-01 -2.695453E-01 1.340886E-01 -3.888265E-01 -4.888381E-02 1.609239E-01 3.058087E-01 7.288026E-01 9.176123E-01 2.593470E-02
-5.400585E-01 8.222967E-01 3.648388E-01 -6.635013E-01 -4.210275E-01 -2.741717E-01 1.431661E-01 -2.184412E-01 -6.006791E-01 -9.289613E-03 2.788451E-01 -2.769694E-01 -9.857075E-01 -5.143206E-01 -1.455316E-01 9.782214E-01
-7.254217E-01 -1.668047E-01 -7.403084E-01 5.606276E-01 1.713349E-01 8.025852E-01 -9.133063E-01 -3.648469E-01 9.402033E-01 -2.317766E-01 7.771178E-01 8.427679E-01 5.951350E-02 9.725678E-01 7.514953E-01 -2.132574E-02
3.962623E-01 -8.680837E-01 -6.393657E-01 7.831294E-01 -5.947012E-02 -9.781432E-01 -8.829182E-01 -9.939770E-01 7.487056E-02 -7.578757E-01 6.196460E-01 -7.909356E-01 -1.149577E-01 -2.736676E-01 2.013560E-01 5.961972E-02
7.165400E-01 -2.371667E-01 -7.857778E-01 7.715441E-01 5.449374E-01 2.804987E-02 -1.380231E-01 -5.877602E-01 3.679530E-01 3.016719E-01 -5.242305E-01 1.064826E-01 -6.910435E-02 7.062310E-01 8.472682E-02 -9.717143E-01
```<issue_comment>username_1: I am not sure if I understood correctly, but it seems that you want each matrix as a heatmap at a fixed (arbitrary) z-value.
As mentioned on the link you posted, making a plot like that one would require (at least to my knowledge) a lot of scrambling around on `gnuplot`. However, you could have a rough idea by doing:
```
set term png
set out "tmp.png"
set view 80,30
splot "tmp" matrix u 1:2:(2):3 w p pt 5 ps 0.75 pal,\
"tmp" matrix u 1:2:(1):3 w p pt 5 ps 0.75 pal,\
"tmp" matrix u 1:2:(0):3 w p pt 5 ps 0.75 pal
```
Which would give you:
[](https://i.stack.imgur.com/3pNGm.png)
Not pretty, but works. You'd have to play around with the `labels`, `tics` and `view` parameters depending on how many matrices you have. Hope it helps!
Upvotes: 3 [selected_answer]<issue_comment>username_2: You could `splot` each matrix `with image`:
```
set ztics 1
set ticslevel 0
stats "data.dat" matrix nooutput
set xrange [-0.5:STATS_size_x - 0.5]
set yrange [-0.5:STATS_size_y - 0.5]
splot for [i=1:3] "data.dat" matrix using 1:2:(i):3 with image notitle
```
[](https://i.stack.imgur.com/DFpSD.png)
Or, depending on your need, you can also `splot ... with pm3d`:
```
set view 70,23
set ztics 1
set ticslevel 0
set pm3d interpolate 5,5
set autoscale xfix
set autoscale yfix
splot for [i=1:3] "data.dat" matrix using 1:2:(i):3 with pm3d notitle
```
[](https://i.stack.imgur.com/Ntg90.png)
Upvotes: 2
|
2018/03/14
| 655 | 2,235 |
<issue_start>username_0: I am using the `permutations()` function from the `itertools` module. I have to compare two strings. The strings can be considered equal as long as one is a permutation of the other.
The documentation for `itertools.permutations()` says:
>
> `itertools.permutations(iterable[, r])`
>
>
> Return successive `r` length permutations of elements in the iterable.
>
>
> If r is not specified or is `None`, then `r` defaults to the length of the iterable and all possible full-length permutations are generated.
>
>
>
**This is my code:**
```
import itertools
mystr = []
for i in range(0, 2):
mystr.append(input())
plist = itertools.permutations(mystr[0])
for i in plist:
print(i)
if any(x == mystr[1] for x in plist):
print("Yes")
else:
print("No")
```
But generating `plist` takes too long. And when I try to print elements of `plist`, the process eventually gets killed because it is making too many permutations. But it should make only the permutations of length of the string itself.
My inputs are:
```
Dcoderplatform
patlodercDmfro
```
I am expecting the output to be `Yes`. But I get the opposite output (`No`).
How can I improve my algorithm?<issue_comment>username_1: Even if you only generate permutations that are the same length as the input string, the number of permutations can be very large. Consider the string in your example: `Dcoderplatform`. The number of permutations is the factorial of the length of the string. In this case `14!` or `87178291200` permutations. So you can expect your process to be terminated when given an input string of any significant length.
Fortunately, there's an easier way to do this. Assuming you aren't required to use the `permutations()` function, you should use the following method.
Given two strings, `str1` and `str2`, you can check if one is a permutation (an anagram) of the other like this:
```
str1 = 'Dcoderplatform'
str2 = 'patlodercDmfro'
if ''.join(sorted(str1)) == ''.join(sorted(str2)):
print('{} and {} are anagrams'.format(str1, str2))
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: I think you should compare like this:
```
if(any("".join(x)==mystr[1] for x in plist)):
```
Upvotes: -1
|
2018/03/14
| 1,291 | 4,581 |
<issue_start>username_0: In order to use the `HTTP V1 API` (not the legacy API) with PHP, the REST interface has to be used.
<https://firebase.google.com/docs/cloud-messaging/send-message#top_of_page>
I am wondering how to get the Auth 2.0 access token?
<https://firebase.google.com/docs/cloud-messaging/auth-server>
As there is no `Google API Client Library` for PHP (see examples in the link above), how can the Auth 2.0 token be received with REST calls (no need to show PHP code)?
The related question: once received this short living token, how to refresh this token? What is the workflow?
Thanks a lot!<issue_comment>username_1: There actually is a kind of "Google Api Client Library" for PHP, even two of them:
<https://github.com/google/google-api-php-client>
and
<https://github.com/GoogleCloudPlatform/google-cloud-php>
The one provides access to APIs that the other doesn't, so it's worth looking which one provides what - you will perhaps need to use both of them.
In the README of the <https://github.com/google/google-api-php-client> repository, you can find a description on how to obtain the OAuth access and refresh tokens.
Both libraries work with Guzzle underneath and provide a way to decorate your own Guzzle HTTP client with an authorization middleware so that you don't have to.
So, if one of the libraries doesn't provide support for an API you want to access, you can apply the code from the following snippet and access the API in question yourself (from [Google Api PHP Client - "Making HTTP requests directly"](https://github.com/google/google-api-php-client#making-http-requests-directly)):
```
// create the Google client
$client = new Google_Client();
/**
* Set your method for authentication. Depending on the API, This could be
* directly with an access token, API key, or (recommended) using
* Application Default Credentials.
*/
$client->useApplicationDefaultCredentials();
// returns a Guzzle HTTP Client
$httpClient = $client->authorize();
```
Shameless plug: I am maintaining a separate Admin SDK for accessing Firebase related APIs at <https://github.com/kreait/firebase-php> , and it has a FCM component, which is documented here: <https://firebase-php.readthedocs.io/en/stable/cloud-messaging.html>
Upvotes: 3 [selected_answer]<issue_comment>username_2: If you want to get the access token manually, without external libraries, you can use this code. It creates a JWT token using your private key, and requests a bearer token.
```php
function base64UrlEncode($text)
{
return str_replace(
['+', '/', '='],
['-', '_', ''],
base64_encode($text)
);
}
// Read service account details
$authConfigString = file_get_contents("path_to_your_private_key_file_downloaded_from_firebase_console.json");
// Parse service account details
$authConfig = json_decode($authConfigString);
// Read private key from service account details
$secret = openssl_get_privatekey($authConfig->private_key);
// Create the token header
$header = json_encode([
'typ' => 'JWT',
'alg' => 'RS256'
]);
// Get seconds since 1 January 1970
$time = time();
$payload = json_encode([
"iss" => $authConfig->client_email,
"scope" => "https://www.googleapis.com/auth/firebase.messaging",
"aud" => "https://oauth2.googleapis.com/token",
"exp" => $time + 3600,
"iat" => $time
]);
// Encode Header
$base64UrlHeader = base64UrlEncode($header);
// Encode Payload
$base64UrlPayload = base64UrlEncode($payload);
// Create Signature Hash
$result = openssl_sign($base64UrlHeader . "." . $base64UrlPayload, $signature, $secret, OPENSSL_ALGO_SHA256);
// Encode Signature to Base64Url String
$base64UrlSignature = base64UrlEncode($signature);
// Create JWT
$jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
//-----Request token------
$options = array('http' => array(
'method' => 'POST',
'content' => 'grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion='.$jwt,
'header' =>
"Content-Type: application/x-www-form-urlencoded"
));
$context = stream_context_create($options);
$responseText = file_get_contents("https://oauth2.googleapis.com/token", false, $context);
$response = json_decode($responseText);
```
The response has 3 fields: `access_token`, `expires_in`, and `token_type`.
You should store your token somewhere for future use, and request a new token when it expires, based on the `expires_in`. (After 1 hour).
You can also request tokens with a shorter lifetime, but the maximum lifetime of a token is 1 hour.
Upvotes: 3
|
2018/03/14
| 570 | 2,094 |
<issue_start>username_0: Im trying to create a JavaScript function that is storing some information in firebase Database each time it is called. One information that I want to store is the current Date and Time that the function has been called. I’ve create something on my own but the formation of the date and time isn’t quite how I want it to be. My source code of the function is the following:
```
function AddtoDatabase(id,title,description){
var rootRef = firebase.database().ref().child(`notifications/${id}`);
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
rootRef.push({
title:`${title}`,
description:`${description}`,
//time:`${new Date().toISOString().split('T')[0]}`
time:`${(new Date(Date.now() - tzoffset)).toISOString().slice(0, -1)}`
});
}
```
Using the source code above i get the following result from date and time: [](https://i.stack.imgur.com/OESdY.png)
How can I edit the code to get just
```
Received at:2018-03-14 09:48
```
Can anyone please help me?<issue_comment>username_1: You should use the moment library for the formatting: <https://momentjs.com/>
In particular, look at this part of the documentation: <https://momentjs.com/docs/#/displaying/>
So in your case you would do:
```
moment().format("YYYY-MM-DD hh:mm");
```
Also, a best practice is to store in your database the number of milliseconds since 1970/01/01, which you can obtain through the JavaScript getTime() method
Upvotes: 0 <issue_comment>username_2: I think that you can achieve this simply using the `Date()` object's native methods like `getFullYear()`, `getFullMonth()` etc.
Here's the code.
```
const date = new Date();
const year = date.getFullYear();
const month = date.getFullMonth() + 1 // months start from 0
const day = date.getDay()
const hour = date.getHours();
const minutes = date.getMinutes();
const time = `Received at ${year}-${month}-${day} ${hour}:${minutes}`;
```
Upvotes: 2 [selected_answer]
|
2018/03/14
| 3,146 | 12,761 |
<issue_start>username_0: Lately I've been trying to write my React components as "Pure Functions" and I've noticed that sometimes I want to have something which feels a lot like `state`. I was thinking about passing my `state` as a second parameter to my component. I can achieve this by calling my component as a normal function with two parameters, `props` and `state`.
For example:
```
// abstracted to it's own module
const useState = (Component, state = {}) => {
return class extends React.Component {
state = createState(this, state); // will traverse and update the state
render() {
const { props, state } = this;
return Component(props, state); // <-- call the Component directly
}
};
};
const Component = (props, { index, increase }) => (
Click me to increase: {index}
);
const componentState = {
index: 0,
increase: (event, state) => ({ ...state, index: state.index + 1 })
};
const StatefullComponent = useState(Component, componentState);
;
```
I have a CodeSandbox example:
[](https://codesandbox.io/s/m5xl16ll8)
My questions are:
1. Will this pattern harm performance?
* I'm no longer extending the props with state values, this might be a good thing
* I am messing with the way components are rendered by default, this might be a bad thing
2. Will this Pattern break things like `shouldComponentUpdate`? (I have a sinking feeling this is modelling the old `context` api)
3. How worried should I be that future react updates will break this code?
4. Is there a more "Reacty" way of using State in a Pure function without resorting to libraries like Redux?
5. Am I trying to solve something which should not be solved?
**Note**: I'm using `state` in this example, but it could also be a `theme`, authorisation rules or other things you might want passed into your component.
---
**EDIT 19-03-2018**: I have noticed that people seem to be confused about what I'm asking. I'm not looking for a new framework or a conversation about "why do you want to separate your concerns?". I am quite sure this pattern will clean up my code and make it more testable and "cleaner" in general. I really want to know if the React framework will in any way hinder this pattern.<issue_comment>username_1: *1- Will this pattern harm performance?*
Performance is usually not a black/white, rather it is better / worse in different scenarios. Since React already has a standard way of doing this, it it plausible that you'll be missing out on internal optimizations.
*2-Will this Pattern break things like shouldComponentUpdate? (I have a sinking feeling this is modelling the old context api)*
Yes, you should be using the class declaration if you need to write shouldComponentUpdate functions
*3- How worried should I be that future react updates will break this code?*
I think is fair to say that you should, since there are obvious and documented ways of doing the same using classes.
*4 - Is there a more "Reacty" way of using State in a Pure function without resorting to libraries like Redux?*
you could have a container component that has state and pass down callback functions to update the state
*5- Am I trying to solve something which should not be solved?*
**yes**, since there is already a mainstream and documented way of archieving what you need using the Component class. You should probably resort to functional components only for very simple or presentational components
Upvotes: 0 <issue_comment>username_2: While this question has been open I've done some painful research on the subject and I'd like to share this research with you.
**Question 1:** Performance; Calling your components as functions or even as constructor functions doesn't really make a difference. You simply get your component instead of a type.
```
// the component
const MyComponent = () => (This is my page);
console.log(MyComponent());
console.log(new MyComponent());
console.log();
console.log(React.createElement(MyComponent));
```
[Pen](https://codepen.io/anon/pen/XEpENg) (Don't forget to inspect the developer tools!)
What I've noticed is that when you call a component directly you lose a little information, for example, when I use JSX the type information is preserved:
```
React.createElement(MyComponent).type === MyComponent // <- true
MyComponent() // <- Now way to find out what constructed this...
```
This doesn't seem like a big deal because the `MyComponent()` is seen as a normal `div` so it should render correctly; but I can imagine that React might do some lookup on the type of the component and calling your function like this that might interfere with the performance.
*Haven't found anything in the documentation nor in the source code to suggest that this is the case, so I see no reason to worry about performance at this point.*
**Question 2:** Does this break `shouldComponentUpdate`; the answer is "maybe not", but not because I need to write a `class` as was suggested. The problem is that React does a shallow compare on the `props` when you use a `PureComponent` and with pure functions just expects that with the same props you get the same result. In my case, because of the second parameter it might think the component doesn't need to update but actually it should. Because of some magic in my implementation this seems to work for child components of a root component wrapped with the `useState` function.
This is as I expected the same problem as with the original implementation of the `context` api. And as such I should be able to solve it using some reactive techniques.
**Question 3:** Seeing how "just calling a component as a function" seems to be the entire idea behind react and seeing how it results in almost exactly the same component without the original type information I see no reason why this should break in the future.
**Question 4/5:** No, there is no more "Reacty" way of really solving this problem. There is how ever a more functional way. I could use a state monad and lift the entire thing up; but that would envolve a lot of work and I really can't see the benefit of doing that. Passing state as a second parameter seems, at least for now, as something which might be strange but viable and actually feasable.
**Question 5:** When I started looking around I didn't find a lot os answers to these questions, but now that I've really dug myself in I can see a few other libraries doing the same thing. For example: [recompose](https://github.com/acdlite/recompose) which calls itself "lodash for react". They seem to use this pattern of wrapping your component in a function and returning a class a lot. (Their [withState](https://github.com/acdlite/recompose/blob/master/src/packages/recompose/withState.js) implementation).
**Extra information:** My conclusion is that this pattern (because it's nothing more than a pattern) is valid and does not break any fundamental rules of React. Just to give a little bit of extra information username_1 wrote that I needed to use a `class` to do it "the React way". I fail to see how wrapping your function and returning a class with state is anything other than "using a class".
I do however realise that wrapping a function increases complexity, but not by much; function calls are really optimised and because you write for [maintainability](https://stackoverflow.com/questions/11168939/function-calls-are-expensive-vs-keep-functions-small) and optimise later.
One of my biggest fears is that when the software gets more and more complocated and we get more cross-cutting concerns to deal with, it will get harder and harder to handle every concern as a parameter. In this case it might be good to use a destructuring pattern to get the concerns which you need from a "concerns" obejct passed as the second parameter.
One last thing about this pattern. I've done a small test (Just selenium rendering a page a 100 times) and this pattern, on a small scale, is faster than using Redux. The bigger your redux state gets and the more components you connect the faster this pattern becomes. The down side is that you are now doing a bit of manual state management, this comes with a real cost in complexity. Just remember to weigh all options.
A few examples of why this state component
------------------------------------------
Applications which interact with users, require that you try to keep track of the interactions they have. These interactions can be modeled in different ways but I really like a stateful approach. This means that you 'thread' state through your application. Now in react you have a few ways of creating components. The three I want o mention are:
1. create a class and extend from `Component`
2. create a class and extend from `PureComponent`
3. create a stateless function
I really like the last option but, to be honest, it's a pain keeping your code [performant](https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56). There are a *lot* of articles our there explaining how lambda expression will create a new function every time your component is called, breaking the shallow compare of the `props` done by `PureComponent`.
To counteract this I use a pattern where I wrap my stateless component in a [HoC](https://reactjs.org/docs/higher-order-components.html) where I pass my component and my state object. This HoC does some magic and passes the state as a second parameter to the stateless function, ensuring that when the props are tested by the compare of the `PureComponent` it *should* work.
Now to make the wrapper even better I memoize the lambdas so that only a single reference to that function exists so that even if you were to test the function by reference it should still be OK.
The code I use for this is:
```
return Object.entries(_state).reduce(
(acc, entry) => {
const [key, value] = entry;
if (value instanceof Function) {
acc[key] = _.memoize(item => (...args) => {
const newState = value.apply(null, [...args, root.state, root.props]);
root.setState(newState);
});
} else {
acc[key] = value;
}
return acc;
},
{}
);
};
```
As you can see I memoize the function and call it proxying the arguments and passing in the state and the props. This works as long as you can call these functions with a unique object like so:
```
const MyComponent = useState((props, { items, setTitle }) => {
return (
{items.map(item => (
))}
);
}, state);
```
Upvotes: 1 <issue_comment>username_3: At first glanced when I checked your code I had a question:
>
> "Why do you make it so complicated? When you can simply make it with a class declaration".
>
>
>
But later when I have [splitted your code](https://codesandbox.io/s/71xr375wl1) I found it really worth to do that.
**Question 1:** Doesn't really make a difference, it is the way how HOC does the composition.
>
> I'm no longer extending the props with state values, this might be a good thing
>
>
>
Why/When might it be a good thing?
>
> I am messing with the way components are rendered by default, this might be a bad thing
>
>
>
I don't see that you break or mess the rendering by default, I think the [HOC](https://reactjs.org/docs/higher-order-components.html) pattern promotes the same philosophy, the difference you separate state from props.
**Question 2:** If a developer decide to use a stateless component then he/she should realize all “lifecycle methods” or references `ref` will be not available.
Your pattern make stateless component as “statefull” but in stateless declaration - amazing .
Like in `JSX` you write in JS an "HTML" and inside it JS code with another "HTML":
```
{list.map(text => * text
)} // I know there should be used key
```
`username_2` pattern (state-full like stateless):
```
import React from 'react'
import {useState} from './lib'
const state = {
index: 0,
increase: (event, state) => ({index: state.index + 1})
}
const Component = (props, state) => (
Click me to increase: {state.index}
)
export default useState(Component, state)
```
**Question 3:** It depends what break changes will be in coming versions.
**Question 4:** Well... I don't think the offered pattern (implemented library) can be considered as application state management but it can be used within any state management like Redux or Mobx because it deals with internal component state.
**Question 5:** No, I don't think. Your solution makes code less and clean. Functional components are good for very simple or representational components and now it can be extended with state.
Upvotes: 3 [selected_answer]
|
2018/03/14
| 853 | 2,798 |
<issue_start>username_0: I'm in the middle of a small crisis here. I need your help! I've done my research for hours but this is my last resort. Cutting to the story, I'm trying to list all the 'pages' from an active category in Wordpress.
Here are the steps I've done so far. I was able to enable categories for my pages by adding the following code to my **functions.php** file:
```
function jh_cats() {
register_taxonomy_for_object_type('post_tag', 'page');
register_taxonomy_for_object_type('category', 'page');
}
add_action( 'init', 'jh_cats' );
```
Next, I needed to make it so that the website has categories & sub-categories. The sub-categories will only show on the category page of the parent. I've added the following to my **category.php** file to get the list of all my sub-categories.
```
php
$categories = get_categories( array(
'orderby' = 'name',
'parent' => $cat,
'hide_empty' => FALSE
) );
if ($categories)
{
foreach ( $categories as $category )
{?>
- [php echo $category-name ?>](<?php echo $category->slug ?>)
php
}
} ?
```
Now, when you visit a specific sub-category (considering nothing will be assigned to the main one), I need to be able to list all the pages that is assigned that sub-category.
**What can I do next?** I have this in my **index.php** but this just lists all the **pages**. Regardless if you're in a specific category or not.
```
php
global $post;
$myposts = get\_posts( array(
'post\_type' = 'page',
'posts\_per\_page' => 5
) );
if ( $myposts ) {
foreach ( $myposts as $post ) :
setup\_postdata( $post ); ?>
* [php the\_title(); ?](<?php the_permalink(); ?>)
php the\_content(); ?
php
endforeach;
wp\_reset\_postdata();
}
?
```
Hope you can help! Thanks. :)
Credits to replies/code from others over here to help me solve some of the earlier issues.<issue_comment>username_1: Have you tried something like this, for your index.php code:
```
$myposts = get_posts( array(
'post_type' => 'page',
'taxonomy' => 'category'
) );
```
Also, I would try and avoid "get\_categories", it's best to try and use the "get\_terms" function whenever you can.
Upvotes: 0 <issue_comment>username_2: On the page you wish to filter posts, you can try using `$cat = get_the_category($post->id);` to return array. Then use a foreach or just get the first item:
```
$cat_id = $cat[0]->cat_ID;
```
Then update the WP query to show all posts using that category.
By ID:
```
$query = new WP_Query( array(
'post_type' => 'page',
'cat' => $cat_id
) );
```
By name:
```
$cat_name = get_cat_name($cat_id);
$query = new WP_Query( array( 'category_name' => $cat_name ) );
```
Source: <https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters>
Upvotes: 1
|
2018/03/14
| 732 | 3,014 |
<issue_start>username_0: Assume you are making a software that manages classes and students.
I'd assume you would have an administrator class, lesson class, and student class.
The administrator class can have various functions such as "get the list of all available lessons" or "get the list of all lessons that a student is enrolled in".
Here's the tricky part.
A lesson can have many students while a student can have many lessons.
Here are some implementations I have thought of:
1. Lesson class contains list of students and student class contains list of lessons:
Pro: Straightforward, Con: Coupled
2. Lesson class contains list of students and in order to do "get all lessons a student is enrolled in" the administrator class would first get all lessons and then filter lessons containing that student.
Pro: Not coupled, Con: Inefficient computing
3. In the administrator class, have the following fields :
* `HashMap`
* `HashMap`Pro: Not coupled, Con: Messy
None of them seem satisfying to me. Can I get some feedback on this dilemma? What is the typically accepted design pattern?<issue_comment>username_1: I wouldn't have the complete Student object inside Lesson objects and vice versa.
Lesson class contains a Set of studentIds of the subscribed students
Student class contains a Set of lessonIds in which they are subscribed to.
Your Administrator class can use these Ids to map, filter, retrieve lessons, students and their relationships.
Edit:
I have to say, that in a real life scenario where your data would be persisted for example in a relational database, you should have a table *Students*, a table *Lessons* and a table *StudentsLessons* with *studentId and lessonId as foreign keys*.
Upvotes: 1 <issue_comment>username_2: This is how I would go about it considering the fact that in future I might need to persist them in the DB.
The relationship between student and lesson is **many-to-many** and hence you need to setup bi-directional
or unidirectional relationship with these two classes.
* `Bi-directional` - List of lessons in `Student` class and vice versa
* `Unidirectional` - Either list of lessons in `Student` or list of
students in `Lesson` class
For example sake, I am setting unidirectional relationship
```
class Student {
private List lessions;
// other attributes
}
class Lesson {
// Lesson attributes
}
```
The `Administrator` class you are talking about is actually a good candidate for service class because it's providing services
such as *"get the list of all available lessons"*
For `Lesson` related queries, I'll create `LessonService`
```
class LessonService {
// Get the list of all available lessons
List findAllLessons() {...}
// Get all lessons a student is enrolled in
List findAllLessons(Student student) {...}
}
```
and finally, there would a `repository/dao` layer that will abstract underlying database.
Your repository could be a simple collection based in-memory or represent the actual database.
Upvotes: 0
|
2018/03/14
| 821 | 3,325 |
<issue_start>username_0: I have a simple exception and I don't know how to deal with it. My question is what should I do in main?
I know I should create an `Exception Class` but that's a simple example to understand how should the exceptions be treated in main.
In main I want do display a message and exit the program and I don't understand how to do it.
```
public void addProfessor() throws Exception {
if(professor) {
throw new Exception(" prof already exists");
}
else {
professor=true;
System.out.println("\n--- addProfessor ---");
System.out.println("Professor: " + professor);
superState=SuperState.OPEN;
System.out.println(superState);
subState=SubState.ASSIGNED;
System.out.println(subState);
}
}
try {
C.addProfessor();
C.addProfessor();//here an exception should be displayed because I should have only one professor
} catch(Exception e) {
e.printStackTrace();
}
finally {
}
```<issue_comment>username_1: To create a custom `Exception` you need to create a class that extends `Exception`. For example as follow:
```
public class ProfessorException extends Exception {
public ProfessorException(String msg) {
super(msg);
}
}
```
Then you need to use this `ProfessorException` in your code:
```
public void addProfessor() throws ProfessorException {
if(professor) {
throw new ProfessorException(" prof already exists");
}
...
}
...
try {
C.addProfessor();
C.addProfessor();//here an exception should be displayed because I should have only one professor
} catch (ProfessorException e) {
e.printStackTrace();
} finally { // Note that finally block is not needed here because it does nothing
}
```
If you want to display a message on standard output instead of printing the stack trace you can do that:
```
try {
C.addProfessor();
C.addProfessor();//here an exception should be displayed because I should have only one professor
} catch (ProfessorException e) {
System.out.println(e.getMessage());
}
```
Upvotes: 0 <issue_comment>username_2: First of all your example looks like the exception you are trying to use is thrown in standard buisness flow.
It's good practice to keep exceptions to handle really exceptional cases, and not use it in a program flow.
If it's just an example then:
**First:** (as mentioned in one of comments) better create your own exception (just derive for example from RuntimeException if you want unchecked
or from Exception for checked one) - then you will not catch some other unexpected exception by accident.
**Second:** when you catch the exception then you have a choice what to do:
1. do some cleanup & rethrow
2. just log it
3. you can also re-try if it makes sense (in your example it does not, because re-trying will just throw another exception - unless the profesor has been removed by another thread)
When you catch the exceptin instead of `e.printStackTrace();` you can get a message from the exception or even (as you created your own meaningful exception) you already know the root cause and can just display it to the user.
just an ilustration:
```
catch(ProfessorAlreadyExistsException e) {
System.out.println("Professor already exists");
}
```
Upvotes: 2 [selected_answer]
|
2018/03/14
| 1,320 | 4,887 |
<issue_start>username_0: I have searched some info about this error,but it seems none match mine,may someone familiar with this error take a look.
"Code generated by a SAS macro, or submitted with a "submit selected" operation in your editor, can leave off a semicolon inadvertently." it is still abstruse for me to explore in my code by this comment.although I got this error,the outcomes is right.may someone give any advice..thanks!
```
%let cnt=500;
%let dataset=fund_sellList;
%let sclj='~/task_out_szfh/fundSale/';
%let wjm='sz_fundSale_';
%macro write_dx;
options spool;
data _null_;
cur_date=put(today(),yymmdd10.);
cur_date=compress(cur_date,'-');
cnt=&cnt
retain i;
set &dataset
if _n_=1 then i=cnt;
if _n_<=i then do;
abs_filename=&sclj.||&wjm.||cur_date||'.dat';
abs_filename=compress(abs_filename,'');
file anyname filevar=abs_filename encoding='utf8' nobom ls=32767 DLM='|';
put cst_id @;
put '@|' @;
put cust_name @;
put '@|' ;
end;
run;
%mend write_dx;
%write_dx();
```
and if I am not using macro,there is no error.
```
data _null_;
options spool;
cur_date=put(today(),yymmdd10.);
cur_date=compress(cur_date,'-');
cnt=&cnt
retain i;
set &dataset
if _n_=1 then i=cnt;
if _n_<=i then do;
abs_filename=&sclj.||&wjm.||cur_date||'.dat';
abs_filename=compress(abs_filename,'');
file anyname filevar=abs_filename encoding='utf8' nobom ls=32767 DLM='|';
put cst_id @;
put '@|' @;
put cust_name @;
put '@|' ;
end;
run;
```
--------------------------------update----------------------------------
I add % to the keyword,but still get the same error
```
%macro write_dx;
options spool;
data _null_;
cur_date=put(today(),yymmdd10.);
cur_date=compress(cur_date,'-');
cnt=&cnt
retain i;
set &dataset
%if _n_=1 %then i=cnt;
%if _n_<=i %then %do;
abs_filename=&sclj.||&wjm.||cur_date||'.dat';
abs_filename=compress(abs_filename,'');
file anyname filevar=abs_filename encoding='utf8' nobom ls=32767 DLM='|';
put cst_id @;
put '@|' @;
put cust_name @;
put '@|' ;
%end;
run;
%mend write_dx;
%write_dx();
```<issue_comment>username_1: To create a custom `Exception` you need to create a class that extends `Exception`. For example as follow:
```
public class ProfessorException extends Exception {
public ProfessorException(String msg) {
super(msg);
}
}
```
Then you need to use this `ProfessorException` in your code:
```
public void addProfessor() throws ProfessorException {
if(professor) {
throw new ProfessorException(" prof already exists");
}
...
}
...
try {
C.addProfessor();
C.addProfessor();//here an exception should be displayed because I should have only one professor
} catch (ProfessorException e) {
e.printStackTrace();
} finally { // Note that finally block is not needed here because it does nothing
}
```
If you want to display a message on standard output instead of printing the stack trace you can do that:
```
try {
C.addProfessor();
C.addProfessor();//here an exception should be displayed because I should have only one professor
} catch (ProfessorException e) {
System.out.println(e.getMessage());
}
```
Upvotes: 0 <issue_comment>username_2: First of all your example looks like the exception you are trying to use is thrown in standard buisness flow.
It's good practice to keep exceptions to handle really exceptional cases, and not use it in a program flow.
If it's just an example then:
**First:** (as mentioned in one of comments) better create your own exception (just derive for example from RuntimeException if you want unchecked
or from Exception for checked one) - then you will not catch some other unexpected exception by accident.
**Second:** when you catch the exception then you have a choice what to do:
1. do some cleanup & rethrow
2. just log it
3. you can also re-try if it makes sense (in your example it does not, because re-trying will just throw another exception - unless the profesor has been removed by another thread)
When you catch the exceptin instead of `e.printStackTrace();` you can get a message from the exception or even (as you created your own meaningful exception) you already know the root cause and can just display it to the user.
just an ilustration:
```
catch(ProfessorAlreadyExistsException e) {
System.out.println("Professor already exists");
}
```
Upvotes: 2 [selected_answer]
|
2018/03/14
| 1,331 | 3,960 |
<issue_start>username_0: Afternoon All,
I have been trying to resolve this for awhile, any help would be appreciated.
Here is my dataframe:
```
Channel state rfq_qty
A Done 10
B Tied Done 10
C Done 10
C Done 10
C Done 10
C Tied Done 10
B Done 10
B Done 10
```
>
> I would like to:
>
>
> 1. Group by channel, then state
> 2. Sum the rfq\_qty for each channel
> 3. Count the occurences of each 'done' string in state ('Done' is treated the same as 'Tied Done' i.e. anything with 'done' in it)
> 4. Display the channels rfq\_qty as a percentage of the total number of rfq\_qty (80)
>
>
>
```
Channel state rfq_qty Percentage
A 1 10 0.125
B 3 30 0.375
C 4 40 0.5
```
>
> I have attempted this with the following:
>
>
>
```
df_Done = df[
(
df['state']=='Done'
)
|
(
df['state'] == 'Tied Done'
)
][['Channel','state','rfq_qty']]
df_Done['Percentage_Qty']= df_Done['rfq_qty']/df_Done['rfq_qty'].sum()
df_Done['Done_Trades']= df_Done['state'].count()
display(
df_Done[
(df_Done['Channel'] != 0)
].groupby(['Channel'])['Channel','Count of Done','rfq_qty','Percentage_Qty'].sum().sort_values(['rfq_qty'], ascending=False)
)
```
>
> Works but looks convoluted. Any improvements?
>
>
><issue_comment>username_1: I think you can use:
* first filter by [`isin`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html) and `loc`
* [`groupby`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html) and aggregate by [`agg`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html) with tuples of new columns names and functions
* add `Percentage` by divide by [`div`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.div.html) and `sum`
* last if necessary [`sort_values`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html) by `rfq_qty`
---
```
df_Done = df.loc[df['state'].isin(['Done', 'Tied Done']), ['Channel','state','rfq_qty']]
#if want filter all values contains Done
#df_Done = df[df['state'].str.contains('Done')]
#if necessary filter out Channel == 0
#mask = (df['Channel'] != 0) & df['state'].isin(['Done', 'Tied Done'])
#df_Done = df.loc[mask, ['Channel','state','rfq_qty']]
d = {('rfq_qty', 'sum'), ('Done_Trades','size')}
df = df_Done.groupby('Channel')['rfq_qty'].agg(d).reset_index()
df['Percentage'] = df['rfq_qty'].div(df['rfq_qty'].sum())
df = df.sort_values('rfq_qty')
print (df)
Channel Done_Trades rfq_qty Percentage
0 A 1 10 0.125
1 B 3 30 0.375
2 C 4 40 0.500
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: One way is to use a single `df.groupby.agg` and rename columns:
```
import pandas as pd
df = pd.DataFrame({'Channel': ['A', 'B', 'C', 'C', 'C', 'C', 'B', 'B'],
'state': ['Done', 'Tied Done', 'Done', 'Done', 'Done', 'Tied Done', 'Done', 'Done'],
'rfq_qty': [10, 10, 10, 10, 10, 10, 10, 10]})
agg_funcs = {'state': lambda x: x[x.str.contains('Done')].count(),
'rfq_qty': ['sum', lambda x: x.sum() / df['rfq_qty'].sum()]}
res = df.groupby('Channel').agg(agg_funcs).reset_index()
res.columns = ['Channel', 'state', 'rfq_qty', 'Percentage']
# Channel state rfq_qty Percentage
# 0 A 1 10 0.125
# 1 B 3 30 0.375
# 2 C 4 40 0.500
```
This isn't the *most efficient* way, since it relies of non-vectorised aggregations, but it may be a good option if it is performant for your use case.
Upvotes: 0
|
2018/03/14
| 2,243 | 6,798 |
<issue_start>username_0: I'm building a news feed using React and moment.js. Using `.map` I'm rendering items with a title and content. I'd like to check if an item was posted in the same year and month as another item. If this is the case I want to hide the second items title.
[Please see my fiddle](https://jsfiddle.net/9uv9acLz/15/)
Currently my code renders this:
March 2018
----------
news item one
March 2018
----------
news item two
September 2017
--------------
news item three
June 2017
---------
news item four
>
> Since item one and two share the same month and year I would like to render like this instead:
>
>
>
March 2018
----------
news item one
news item two
September 2017
--------------
news item three
June 2017
---------
news item four
[Based on this answer](https://stackoverflow.com/questions/840781/get-all-non-unique-values-i-e-duplicate-more-than-one-occurrence-in-an-array) I've tried to find nodes with duplicate class names but I'm not quite there:
```
let monthNodes = [...document.querySelectorAll('.months')];
let months = []
monthNodes.map(month => {
months.push(month.className)
})
const count = names =>
names.reduce((a, b) =>
Object.assign(a, {[b]: (a[b] || 0) + 1}), {})
const duplicates = dict =>
Object.keys(dict).filter((a) => dict[a] > 1)
console.log(count(months)) // {March_2018: 2, December_2017: 1, November_2017: 1}
console.log(duplicates(count(months))) // [ 'March_2018' ]
```
Maybe I'm going about this the wrong way and using `.map` in the first place is a bad idea?
**Update**
Thanks for all the great answers, it was hard to pick between them as they all work well. I have to accept <NAME>'s answer since he was first to provide a working example.<issue_comment>username_1: you can do it this way:
<https://jsfiddle.net/2e27jvvh/>
```
render() {
const arr = new Array();
return(
{this.state.news.map(item => {
const yearMonth = moment(item.date).format("MMMM YYYY");
const yearM = moment(item.date).format("MMMM\_YYYY");
if (arr.indexOf(yearMonth) < 0){
arr.push(yearMonth);
return (
{yearMonth}
-----------
{item.content}
)
} else {
return (
{item.content}
)
}
})
}
)
}
```
Maybe you should sort items based on year and month before to ensure correct behaviour even when items are not sorted initially. But this works with your example.
Upvotes: 2 [selected_answer]<issue_comment>username_2: Assuming the data structure looked like this:
```
const data = [
{
date: 'March 2018',
item: {
title: 'news item one'
}
},
{
date: 'March 2018',
item: {
title: 'news item two'
}
},
{
date: 'September 2017',
item: {
title: 'news item two'
}
},
{
date: 'June 2017',
item: {
title: 'news item one'
}
}
]
```
You could use [Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce):
```
const formatted = data.reduce((obj, item) => {
obj[item.date] = obj[item.date] ? [...obj[item.date], item] : [item]
return obj
}, {})
```
[Example Codepen](https://codepen.io/simmo/pen/WzrLGq?editors=0010)
Upvotes: 1 <issue_comment>username_3: 1) You can define `previousYearMonth` variable and store the previous year and month names there. You can check if your current `yearMonth` and `previousYearMonth` are the same and show/hide the appropriate tag:
```
render() {
return(
{this.state.news.map((item, index) => {
const yearMonth = moment(item.date).format("MMMM YYYY");
const yearM = moment(item.date).format("MMMM\_YYYY");
const previousYearMonth = index
? moment(this.state.news[index - 1].date).format("MMMM YYYY")
: false;
return(
{
(yearMonth !== previousYearMonth) && ({yearMonth}
-----------
)
}
{item.content}
)
})
}
)
}
```
Check [the fork of your fiddle](https://jsfiddle.net/seskodn0/).
2) Another way you can preprocess your data in the `constructor` method and set `title` property this way:
```
constructor(props) {
super(props);
const data = [
{content: 'news item one', date: '2018-03-02'},
{content: 'news item two', date: '2018-03-17'},
{content: 'news item two', date: '2017-09-21'},
{content: 'news item one', date: '2017-06-15'}
];
data.forEach((item, index) => {
const yearMonth = moment(item.date).format("MMMM YYYY");
const previousYearMonth = index
? moment(data[index - 1].date).format("MMMM YYYY")
: false;
if (yearMonth !== previousYearMonth) {
item.title = yearMonth
}
});
this.state = {
news: data
}
}
```
In this case, in the `render` method you can just check that `title` property exists and show title:
```
{
item.title && ({item.title}
------------
)
}
{item.content}
```
Check [the fiddle with this approach](https://jsfiddle.net/wrxsyLtn/).
Upvotes: 1 <issue_comment>username_4: [`Array.prototype.reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) can be leveraged to organise your `Articles` in `Object` form by `year` and `month`.
See below for a practical example.
[JSFiddle](https://jsfiddle.net/khhd8qej/)
```js
// News
class News extends React.Component {
// State.
state = {
news: [
{content: 'news item one -- march 2018', date: '2018-03-02'},
{content: 'news item two -- march 2018', date: '2018-03-17'},
{content: 'news item two -- sep 2017', date: '2017-09-21'},
{content: 'news item one -- june 2017', date: '2017-06-15'}
]
}
// Render.
render = () => (
{
Object.entries(this.organised()).map(([yearmonth, articles], i) => (
### {yearmonth}
{articles.map((article, j) => (
{article.content}
))}
))
}
)
// Organised.
organised = () => this.state.news.reduce((total, article) => {
const key = moment(article.date).format('YYYY MMMM')
return {
...total,
[key]: total[key] && total[key].concat(article) || [article]
}
}, {})
}
// Mount.
ReactDOM.render(,document.getElementById('container'));
```
```html
```
Upvotes: 2 <issue_comment>username_5: Considering that this list is coming from an API, you can have something like this once the data has arrived.
```
const monthwise = this.state.news.reduce((res, obj) => {
const ym = moment(obj.date).format("YYYY-MM")
res[ym] = res[ym] || []
res[ym].push(obj);
return res;
}, {})
this.setState({monthwise})
```
Now, in your `render`, you can have:
```
render() {
return(
{Object.values(this.state.monthwise).map((items, index) => {
return(
#### {moment(items[0].date).format("YYYY MMMM")}
{items.map((item, key) => {item.content} )}
)
})}
)
}
```
[Working jsfiddle](https://jsfiddle.net/dn91nred/)
Upvotes: 1
|
2018/03/14
| 749 | 2,862 |
<issue_start>username_0: could you help me accessing some information in the result of the yum list module?
This is my task:
```
- name: check if lgto networker is installed
yum:
list: "{{ (item | basename | splitext)[0] }}"
state: present
register: yum_result
with_fileglob:
- "lgt*.rpm"
```
When i debug my registered var `yum_result` i got this output:
```
ok: [XX.XX.XX.XXX] => {
"yum_result": [
{
"_ansible_ignore_errors": null,
"_ansible_item_result": true,
"_ansible_no_log": false,
"_ansible_parsed": true,
"changed": false,
"failed": false,
"invocation": {
"module_args": {
"allow_downgrade": false,
"conf_file": null,
"disable_gpg_check": false,
"disablerepo": null,
"enablerepo": null,
"exclude": null,
"install_repoquery": true,
"installroot": "/",
"list": "lgtoclnt-8.2.4.9-1.x86_64",
"name": null,
"security": false,
"skip_broken": false,
"state": "installed",
"update_cache": false,
"validate_certs": true
}
},
"item": "/data/playbooks/roles/backup_networker/files/lgtoclnt-8.2.4.9-1.x86_64.rpm",
"results": [
{
"arch": "x86_64",
"envra": "0:lgtoclnt-8.2.4.9-1.x86_64",
"epoch": "0",
"name": "lgtoclnt",
"release": "1",
"repo": "installed",
"version": "8.2.4.9",
"yumstate": "installed"
}
]
}
```
How can i access the information in the last results block?
```
"arch": "x86_64",
"envra": "0:lgtoclnt-8.2.4.9-1.x86_64",
"epoch": "0",
"name": "lgtoclnt",
"release": "1",
"repo": "installed",
"version": "8.2.4.9",
"yumstate": "installed"
```
I've tried something like `yum_result.results.yumstate` or `yum_result[2].yumstate`, but nothing works.<issue_comment>username_1: Use:
`yum_result` to access registered dictionary
`yum_result.results` to access the list of registered iterations
`yum_result.results[-1]` to access result of last iteration
`yum_result.results[-1].yumstate` to access it's `yumstate` status
Upvotes: 0 <issue_comment>username_2: You can access the result with
```yaml
yum_result.results[0].yumstate
```
Upvotes: 1
|
2018/03/14
| 1,216 | 5,191 |
<issue_start>username_0: ```
import java.io.*;
import java.sql.*;
public class jdbcdemo
{
public static void main(String args[])throws IOException
{
Connection con=null;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:ebbill","","");
System.out.println("ConnectionSuccesfull");
Statement stat=con.createStatement();
int result=stat.executeUpdate("Insert into tableone values(5,'siva',50,6000)");
System.out.println("Record Inserted");
stat.close();
con.close();
}
catch(ClassNotFoundException e)
{
System.out.println("Exception:"+e.getMessage());
}
catch(SQLException e)
{
System.out.println("Exception:"+e.getMessage());
}
}
}
```
I dont understand what happens in this try block. Please explain briefly in simpleton terms.
This line `Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");` doesnt work in latest `java`. It works only in `java 6` or previous versions.<issue_comment>username_1: The line
```
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
```
try to load the class `sun.jdbc.odbc.JdbcOdbcDriver` from the classpath of your application.
If the class is not found the exception `ClassNotFoundException` is thrown.
Since java 8 this class (`sun.jdbc.odbc.JdbcOdbcDriver`) has been removed as per [oracle documentation](https://docs.oracle.com/javase/7/docs/technotes/guides/jdbc/bridge.html):
>
> Status of the JDBC-ODBC Bridge
> The **JDBC-ODBC Bridge** should be considered a transitional solution; **it will be removed in JDK 8**. In addition, Oracle does not support the JDBC-ODBC Bridge. Oracle recommends that you use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.
>
>
>
Upvotes: 2 <issue_comment>username_2: The purpose of a `try` block is to handle the error prone code i.e. the code which is inside a try block, tend to throw exceptions during run-time.
```
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:ebbill","","");
Statement stat=con.createStatement();
```
Above piece of code can result in an error when something is not right and it leads to the termination of JVM (in other words the application would have an ERROR). In order to handle the exception caused during the run-time, we include the error prone code in `try` block and a remedy in the `catch` block to handle the exception scenarios.
Your code tries to load the class "*sun.jdbc.odbc.JdbcOdbcDriver*" . If the class is not found, then ClassNotFoundException exception is thrown.
Upvotes: 0 <issue_comment>username_3: In simpleton terms, within the try block, the code attempts to establish a connection to a database. It then tries to insert a record into a table within that database, before disconnecting from the database.
Putting it within a try block and having the catch blocks below, means that if something goes wrong in your code at any point, then the code within the corresponding catch block relevant to the particular error that occurs is executed.
In your case, you have two catch blocks, ClassNotFoundException, and SQLException.
Typically, a ClassNotFoundException may occur when the below lines are executed:
```
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:ebbill","","");
```
And a common cause might be that the JDBC Driver is not installed on your project.
An SQLException might be thrown when the below lines are executed:
```
Statement stat=con.createStatement();
int result=stat.executeUpdate("Insert into tableone values(5,'siva',50,6000)");
```
And would typically occur because something has gone wrong on the database side when trying to access the database or with the SQL query.
Other exceptions could be thrown, however these would result in your program falling over with less useful error logging and no logic to handle the errors. You could just catch Exception (which would catch any exception thrown) however in the real world this can be considered bad practice as you should know what types of exception may be thrown and handle them appropriately.
In your example, let's suppose that for some reason, we know that occasionally, an SQL Exception may get thrown in an edge case scenario when your application is running. Let's also assume it is not programatically feasible to write code to prevent this from happening, and so we instead just want to log the error, provide a message to the user and the continue with the normal flow of execution for running the program.
If however, a ClassNotFoundException is thrown, let's assume we do not want to continue with the normal running of the application (we would not be able to). So we may instead want to log the error, and output a message to the user advising them to contact their system administrator.
So here we have two different responses to the two different types of error, hence the need for the two catch blocks catching the different types of error.
Upvotes: 0
|
2018/03/14
| 349 | 1,408 |
<issue_start>username_0: ```
@SpringBootApplication
public class InfoServerSpringApplication {
//this is my code in java
public InfoServerSpringApplication() {
System.out.println("Hello world");
}
public static void main(String[] args) {
SpringApplication.run(InfoServerSpringApplication.class, args);
}
}
```
so that's how i print hello world in Spring boot java , i use constructor but how about in kotlin ?
```
@SpringBootApplication
class Kotlin2Application
//constructor code to print hello world in kotlin
fun main(args: Array) {
runApplication(\*args)
}
```
I'm using eclipse. Is there any solution please ?<issue_comment>username_1: You can run code when an instance is created by using an *initializer block* (or even multiple ones), code placed in these becomes part of the body of the primary constructor.
```
class Kotlin2Application {
init {
println("Hello world")
}
}
```
(This is just a general answer about how to translate the specific Java code in question, not to be taken as best practice for running code after your Spring application starts.)
See also: [official documentation about classes and constructors](https://kotlinlang.org/docs/reference/classes.html#constructors).
Upvotes: 2 <issue_comment>username_2: 1. Please try with this.
```
class Kotlin2Application {
constructor(){
println("Hello world")
}
}
```
Upvotes: 0
|
2018/03/14
| 455 | 2,045 |
<issue_start>username_0: I need to execute derived class constructor before base class constructor.
I am attaching code which is using virtual object in base class which need to be initialised in derived class. We decide type of virtual object in derived class and then assign values to that object once we have type of that object.
How could I call derived class constructor before base class constructor in this scenario.
```
public class BaseClass : UserControl, INotifyPropertyChanged
{
public Path ConnIn;
public Path ConnOut;
public virtual ObjectBase BaseObject { get; set; }
public void BaseClass(XmlElementConfig config)
{
this.BaseObject.Title = config.Title;
this.BaseObject.GroupID = config.GroupID;
}
}
public partial class DerivedClass : CanvasBase
{
private Audio_MonitorAction audio_objectAction;
public override ObjectBase BaseObject
{
get { return audio_objectAction; }
set
{
audio_objectAction = (Audio_MonitorAction)value;
NotifyPropertyChanged();
}
}
public DerivedClass(XmlElementConfig config) : base(config)
{
InitializeComponent();
audio_objectAction = new Audio_MonitorAction(createGuid);
}
}
```<issue_comment>username_1: You can run code when an instance is created by using an *initializer block* (or even multiple ones), code placed in these becomes part of the body of the primary constructor.
```
class Kotlin2Application {
init {
println("Hello world")
}
}
```
(This is just a general answer about how to translate the specific Java code in question, not to be taken as best practice for running code after your Spring application starts.)
See also: [official documentation about classes and constructors](https://kotlinlang.org/docs/reference/classes.html#constructors).
Upvotes: 2 <issue_comment>username_2: 1. Please try with this.
```
class Kotlin2Application {
constructor(){
println("Hello world")
}
}
```
Upvotes: 0
|
2018/03/14
| 400 | 1,497 |
<issue_start>username_0: i m new to vue (version 2.5) in my project i had install v-select i go through document and got confuse on few thing
here is my code
```
Category
next
```<issue_comment>username_1: Are we talking about [this select component](https://sagalbot.github.io/vue-select/docs/Api/Props.html)? The simplest usage is to put a v-model attribute on your v-select. Then this variable will automatically reflect the user selected value.
If you need to specify options, which you might, then you also need to provide a value prop and listen for @change.
Upvotes: 0 <issue_comment>username_2: You need to bind options to category. i.e. `v-bind:options` or short hand `:options` I would also suggest you use a method to make your ajax call, and then call the method in `mounted()` instead. Also you probably want a `v-model` on that select so I added that in the example.
First in your template...
```
```
Then in your script definition...
```
data(){
return{
category:[],
selectedCategory: null,
}
},
methods:{
getCategories(){
this.$http.get('http://localhost:3000/api/categories')
.then(function (response) {
this.category=response.data
}.bind(this))
.catch(function (error) {
console.log("error.response");
});
}
},
mounted(){
this.getCategories();
}
```
Here is a working jfiddle <https://jsfiddle.net/username_2/mghbLyva/3/>
Upvotes: 3 [selected_answer]
|
2018/03/14
| 775 | 2,780 |
<issue_start>username_0: I have an weave network plugin.
inside my folder /etc/cni/net.d there is a 10-weave.conf
```
{
"name": "weave",
"type": "weave-net",
"hairpinMode": true
}
```
My weave pods are running and the dns pod is also running
But when I want to run a pod like a simple nginx which will pull an nginx image
The pod stuck at container creating, describe pod gives me the error, failed create pod sandbox.
When I run `journalctl -u kubelet` I get this error
>
> cni.go:171] Unable to update cni config: No networks found in /etc/cni/net.d
>
>
>
is my network plugin not well configured?
I used this command to configure my weave network
```
kubectl apply -f https://git.io/weave-kube-1.6
```
After this won't work I also tried this command
```
kubectl apply -f “https://cloud.weave.works/k8s/net?k8s-version=$(kubectl version | base64 | tr -d ‘\n’)”
```
I even tried flannel and that gives me the same error.
The system I am setting kubernetes on is a raspberry pi.
I am trying to build a raspberry pi cluster with 3 nodes and 1 master with kubernetes
Does anyone have ideas on this?<issue_comment>username_1: Looking at the [pertinent code in Kubernetes](https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/network/cni/cni.go#L99) and [in CNI](https://github.com/containernetworking/cni/blob/master/libcni/conf.go#L128), the specific error you see seems to indicate that it cannot find any files ending in `.json`, `.conf` or `.conflist` in the directory given.
This makes me think it could be something as the conf file not being present on all the hosts, so I would verify that as a first step.
Upvotes: 1 [selected_answer]<issue_comment>username_2: Thank you all for responding to my question. I solved my problem now. For anyone who has come to my question in the future the solution was as followed.
I cloned my raspberry pi images because i wanted a basicConfig.img for when i needed to add a new node to my cluster of when one gets down.
Weave network (the plugin i used) got confused because on every node and master the os had the same machine-id. When i deleted the machine id and created a new one (and reboot the nodes) my error got fixed. The commands to do this was
sudo rm /etc/machine-id
sudo rm /var/lib/dbus/machine-id
sudo dbus-uuidgen --ensure=/etc/machine-id
Once again my patience was being tested. Because my kubernetes setup was normal and my raspberry pi os was normal. I founded this with the help of someone in the kubernetes community. This again shows us how important and great are IT community is. To the people of the future who will come to this question. I hope this solution will fix your error and will decrease the amount of time you will be searching after a stupid small thing.
Upvotes: 2
|
2018/03/14
| 466 | 1,365 |
<issue_start>username_0: I have tried following code to print memory usage in %.. It print the answer as follow,
71.2505 - I need the answer as 71% ..how can I resolve this ?
```
free | grep Mem | awk '{print $3/$2 * 100}'
```<issue_comment>username_1: You have at least three options so far. (1) capture the output from the *command substitution* in a variable and then use simple *parameter expansion with substring removal* to discard up to the decimal from the right, e.g.
```
val=$(free | grep Mem | awk '{print $3/$2 * 100}'); echo ${val%.*}
```
Next as @melpomene suggested, using the int(...) operation with `awk`
```
awk '{print int($3/$2 * 100)}'
```
Finally, you can use `printf` with the `%d` *format specifier* to discard the decimals as well, e.g.
```
free | grep Mem | awk '{printf "%d\n", $3/$2 * 100}'
```
(**note:** another, and perhaps better *format specifier* in place of `%d` would be `%.0f` to preserve the floating point character, while trimming the additional decimals)
Either one will do.
Upvotes: 3 [selected_answer]<issue_comment>username_2: `awk` isn't needed:
1. *POSIX* shell method, (*i.e.* `bash`, `dash`, *et al*):
```
free | { read; read a b c d; echo $((c*100/b)); }
```
2. *POSIX* shell:
```
set -- `free` ; echo $(($9*100/$8))
```
3. Pure `bash`:
```
m=(`free`) ; echo $((m[8]*100/m[7]))
```
Upvotes: 1
|
2018/03/14
| 1,270 | 4,652 |
<issue_start>username_0: I have two tables
```
CREATE TABLE RetailGroup(
Id int IDENTITY(1,1),
GroupName nvarchar(50),
)
CREATE TABLE RetailStore(
Id int IDENTITY(1,1),
StoreName nvarchar(100),
RetailGroupId int
)
```
Where RetailGroupId in RetailStore is referencing RetailGroup ID. I am trying to create a search function where I can search for both RetailGroup and RetailsStores. If I get a matching RetailStore I want to return the Group it is tied to and the matching Store record. If I get a matching Group, I want the group record but no retail stores.
I tried to do it the following way:
```
public List SearchGroupsAndStores(string value)
{
return \_context.RetailGroups.Where(group => group.GroupName.Contains(value)).Include(group => group.RetailStores.Where(store => store.StoreName.Contains(value))).ToList();
}
```
But this is wrong because include should not be used for selection.
Here is my entity framework model for groups
```
public class RetailGroup
{
[Key]
public int Id { set; get; }
[MaxLength(50)]
public String GroupName { set; get; }
//Relations
public ICollection RetailStores { set; get; }
}
```
And here is the one for the store
```
public class RetailStore
{
[Key]
public int Id { get; set; }
[MaxLength(100)]
public string StoreName { get; set; }
[ForeignKey("RetailGroup")]
public int RetailGroupId { get; set; }
//Relations
public RetailGroup RetailGroup { get; set; }
public ICollection Licenses { get; set; }
}
```
How do I create my `LINQ` to get the results I am looking for ?<issue_comment>username_1: Try using an `OR` condition to filter both the group name and the store name.
```
return _context.RetailGroups
.Where(group => group.GroupName.Contains(value) || group.RetailStores.Any(store => store.StoreName.Contains(value)))
.Include(group => group.RetailStores.Where(store => store.StoreName.Contains(value)))
.ToList();
```
Another option would be doing 2 searches, one for the groups and other for the stores. The problem here would be geting a unique set of groups from both results.
```
List retailGroups = new List();
var groupSearchResults = \_context.RetailGroups
.Where(group => group.GroupName.Contains(value))
.Include(group => group.RetailStores.Where(store => store.StoreName.Contains(value)))
.ToList();
var storeSearchResults = \_context.RetailStores
.Where(store => store.StoreName.Contains(value))
.Select(store => store.RetailGroup)
.ToList();
retailGroups.AddRange(groupSearchResults);
retailGroups.AddRange(storeSearchResults);
// Remove duplicates by ID
retailGroups = retailGroups
.GroupBy(group => group.Id)
.Select(group => group.First());
```
Upvotes: 0 <issue_comment>username_2: Either use `OR` condition and have the search in one statement :
```
public List SearchGroupsAndStores(string value)
{
return \_context.RetailGroups
.Where(rg => rg.GroupName.Contains(value) || rg.RetailStores.Any(rs => rs.StoreName.Contains(value)))
.Include(rg => rg.RetailStores.Where(rs => rs.StoreName.Contains(value)).ToList())
.ToList();
}
```
Or you can split the search, first look for `RetailGroups` then search `RetailStores` and return their `RetailGroup` :
```
public List SearchGroupsAndStores(string value)
{
List searchResults = new List();
searchResults.AddRange(\_context.RetailGroups.Where(rg => rg.GroupName.Contains(value)).ToList());
searchResults.AddRange(\_context.RetailStores.Where(rs => rs.StoreName.Contains(value)).Select(rs => rs.RetailGroup).ToList());
}
```
Upvotes: -1 <issue_comment>username_3: The query returning the desired result with projection is not hard:
```
var dbQuery = _context.RetailGroups
.Select(rg => new
{
Group = rg,
Stores = rg.RetailStores.Where(rs => rs.StoreName.Contains(value))
})
.Where(r => r.Group.GroupName.Contains(value) || r.Stores.Any());
```
The problem is that you want the result to be contained in the entity class, and EF6 neither supports projecting to entity types nor filtered includes.
To overcome these limitations, you can switch to LINQ to Objects context by using `AsEnumerable()` method, which at that point will effectively execute the database query, and then use delegate block to extract the entity instance from the anonymous type projection, bind the filtered collection to it and return it:
```
var result = dbQuery
.AsEnumerable()
.Select(r =>
{
r.Group.RetailStores = r.Stores.ToList();
return r.Group;
})
.ToList();
```
Upvotes: 2 [selected_answer]
|
2018/03/14
| 1,475 | 4,661 |
<issue_start>username_0: I am trying to import xml into my database with the following query using OpenXML in Microsoft SQL Server:
```
DECLARE @xml XML;
DECLARE @y INT;
SET @xml
= '
5135399
Stocks divided into two corners
News papeer
Foreign capital doubled this year.
2017-12-30T00:00:00
1
News general
Times
http://test.com
111
New York Times
1
Positive
222
Washington Post
1
Negative
111
New York Times
2
Neither
222
Washington Post
2
Neither
26
0
0
0
';
EXEC sp_xml_preparedocument @y OUTPUT, @xml;
SELECT *
FROM
OPENXML(@y, '/ArrayOfArticle/Article', 1)
WITH
(
ScriptId VARCHAR(20),
Title VARCHAR(30),
Mediatype VARCHAR(30)
);
```
The query however only returns NULL values. What am I missing here? Would it be optimal to import the XML using SSIS instead. Not sure how much more details I can give at the given hour.
[](https://i.stack.imgur.com/iSIge.jpg)<issue_comment>username_1: Do not use `FROM OPENXML`. This approach (together with the corresponding SPs to prepare and to remove a document) is outdated and should not be used any more.
Try the XML type's native methods, in this case `.value()`:
Your XML is rather weird - concerning namespaces. If its creation is under your control you should try to clean this namespace mess. The unusual thing is, that your XML declares **default** namespaces over and over.
You can use the *deep search with `//`* together with a namespace wildcard `*:`
```
--GetItEasyCheesy (not recommended)
SELECT @xml.value(N'(//*:ScriptId)[1]',N'int') AS ScriptId
,@xml.value(N'(//*:Title)[1]',N'nvarchar(max)') AS Title
,@xml.value(N'(//*:Mediatype )[1]',N'nvarchar(max)') AS Mediatype ;
```
You can declare the namespace as default, but in this case you must wildcard the outer elements, as they are not part of this namespace:
```
--Use a default namespace
WITH XMLNAMESPACES(DEFAULT 'https://test.com/')
SELECT @xml.value(N'(/*:ArrayOfArticle/*:Article/ScriptId/text())[1]',N'int') AS ScriptId
,@xml.value(N'(/*:ArrayOfArticle/*:Article/Title/text())[1]',N'nvarchar(max)') AS Title
,@xml.value(N'(/*:ArrayOfArticle/*:Article/Mediatype/text())[1]',N'nvarchar(max)') AS Mediatype;
```
The recommended approach is to bind the inner namespace to a prefix and use this
```
--Recommended
WITH XMLNAMESPACES('https://test.com/' AS ns)
SELECT @xml.value(N'(/ArrayOfArticle/Article/ns:ScriptId/text())[1]',N'int') AS ScriptId
,@xml.value(N'(/ArrayOfArticle/Article/ns:Title/text())[1]',N'nvarchar(max)') AS Title
,@xml.value(N'(/ArrayOfArticle/Article/ns:Mediatype/text())[1]',N'nvarchar(max)') AS Mediatype;
```
If your contains more than one you can use `.nodes()` to get alle of them as derived table. In this case the query is
```
WITH XMLNAMESPACES('https://test.com/' AS ns)
SELECT art.value(N'(ns:ScriptId/text())[1]',N'int') AS Recommended
,art.value(N'(ns:Title/text())[1]',N'nvarchar(max)') AS Title
,art.value(N'(ns:Mediatype/text())[1]',N'nvarchar(max)') AS Mediatype
FROM @xml.nodes(N'/ArrayOfArticle/Article') AS A(art);
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: your XML contains namespaces, I'd use xquery in order to extract the data from your XML
**UPDATE** with additional elements extract
```
DECLARE @xml XML;
SET @xml
= '
5135399
Stocks divided into two corners
News papeer
Foreign capital doubled this year.
2017-12-30T00:00:00
1
News general
Times
http://test.com
111
New York Times
1
Positive
222
Washington Post
1
Negative
111
New York Times
2
Neither
222
Washington Post
2
Neither
26
0
0
0
'
DECLARE @T TABLE (XmlCol XML)
INSERT INTO @T
SELECT @xml
;WITH XMLNAMESPACES ('https://test.com/' as p1)
SELECT z.t.value ('../../p1:ScriptId[1]',' varchar(100)') ScriptId,
z.t.value ('../../p1:Title[1]',' varchar(100)') Title,
z.t.value ('../../p1:Mediatype[1]',' varchar(100)') Mediatype,
z.t.value ('p1:CompanyName[1]', 'varchar(100)') CompanyName
FROM @T t
CROSS APPLY XmlCol.nodes ('/ArrayOfArticle/Article/p1:MediaScore/p1:MediaScore') z(t)
```
Upvotes: 2 <issue_comment>username_3: ```
DECLARE @y INT
EXEC sp_xml_preparedocument @y OUTPUT, @xml,
''
SELECT *
FROM
OPENXML(@y, '/ArrayOfArticle/Article', 2)
WITH
(
[ScriptId] VARCHAR(20) 'x:ScriptId', --<< and so on
[Title] VARCHAR(30),
Mediatype VARCHAR(30)
)
EXEC sp_xml_removedocument @y --<< lost in your code
```
Upvotes: 1
|
2018/03/14
| 556 | 2,041 |
<issue_start>username_0: I have created a table with selection and pagination in angular 2 using angular material.
I have taken a button with the name **Remove Selected Rows** to delete the selected rows from the table.
But as a delete the selected rows , all the table data is being loaded which doesn't match with value specified for the pagination.
Below is the stack-blitz link for my code..
-------------------------------------------
<https://stackblitz.com/edit/delete-rows-mat-table-vj4hbg?file=app%2Ftable-selection-example.html>
Below shown is the output.
--------------------------
Initially the table displays only the rows as specified for the pagination value.
[](https://i.stack.imgur.com/4vBJ7.png)
But as I deleted the row 3 , all rows are being loaded even if the pagination value is only 3..
[](https://i.stack.imgur.com/gZEA9.png)
can anybody tell me how can I limit my table rows with the pagination value specified after deleting the rows.<issue_comment>username_1: **[Here you go buddy.](https://stackblitz.com/edit/delete-rows-mat-table-odej4h?file=app/table-selection-example.ts)**
You forgot to reassign the paginator to the datasource after deletion. Angular may do some magic, but sometimes it needs a little bit of help.
I use a timeout because I always face an issue, feel free to try without it.
```
setTimeout(() => {
this.dataSource.paginator = this.paginator;
});
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: It's very simple after close of dialog to subscibe and call listing API
```
openDialog(requestId): void {
//this.abc=requestId;
const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
disableClose: true,
width: '400px',
data: { name: this.name, animal: this.animal, sendtochild: requestId }
});
dialogRef.afterClosed().subscribe(result => {
this.getUserList();
});
}
```
Upvotes: 0
|
2018/03/14
| 370 | 1,328 |
<issue_start>username_0: I'm trying to configure a maven build profile, my purpose is to add the following dependencies everytime the is doesn't match some\_id.
for some reason this does not work, I suspect that using the `! logical operator` does not work with id's. any ideas ?
```
!some\_id
com.project.apps
apps-cf
${apps.version}
com.project.apps
apps-core
${apps.version}
```<issue_comment>username_1: **[Here you go buddy.](https://stackblitz.com/edit/delete-rows-mat-table-odej4h?file=app/table-selection-example.ts)**
You forgot to reassign the paginator to the datasource after deletion. Angular may do some magic, but sometimes it needs a little bit of help.
I use a timeout because I always face an issue, feel free to try without it.
```
setTimeout(() => {
this.dataSource.paginator = this.paginator;
});
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: It's very simple after close of dialog to subscibe and call listing API
```
openDialog(requestId): void {
//this.abc=requestId;
const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
disableClose: true,
width: '400px',
data: { name: this.name, animal: this.animal, sendtochild: requestId }
});
dialogRef.afterClosed().subscribe(result => {
this.getUserList();
});
}
```
Upvotes: 0
|
2018/03/14
| 446 | 1,241 |
<issue_start>username_0: I would like to extract a certain numbers in a string, after numerous tries with regex, I can't seem to find the correct pattern for it. There are other numbers but I require only the 3 digits after "M". Thank you.
Example:
line: `"2018-01-23 - member data. member_id=[M001]."`
Result:
```
001
```<issue_comment>username_1: You can use [`re.findall`](https://docs.python.org/3/library/re.html#re.findall) with a capturing group as follows:
```
matches = re.findall( r'.*\[M(.*?)\]', '2018-01-23 - member data. member_id=[M001].')
print(matches[0]) # 001
```
Upvotes: 1 <issue_comment>username_2: You can use [`re.findall`](https://docs.python.org/3/library/re.html#re.findall) as follows:
```
matches = re.findall( r'\[M(\d{3})\]', '2018-01-23 - member data. member_id=[M001].')
print(matches[0])
out:
001
```
**Explanation:**
```
\d will find any number.
{3} will find occurrence of the match.
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: You say you already tried this:
```
m = re.search(r'member_id=[M(\d+)]', line)
```
but you need to escape the `[` and `]` characters, as they have a special meaning here. Try this:
```
m = re.search(r'member_id=\[M(\d+)\]', line)
```
Upvotes: 0
|
2018/03/14
| 586 | 1,924 |
<issue_start>username_0: I'm using 2 tables:
First as main table that keeps data
Second one is a temp table to import new report everyday and check the difference between records in new report and main table.
```
tablename="Temp"
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel10, tablename,strPath, True, "A:CH"
stringSQL =
UPDATE
Main INNER JOIN Temp ON Main.[PackageNumber] = Temp.[PackageNumber]
SET
Main.[Field1]=Temp.[Field1],
Main.[Field2]=Temp.[Field2] ...
```
If in temp table i can find record with already existing package number I have to update the entire row in main table with data from temp table.
There is about 30 columns in main table and about few thousands of records to check in temp report everyday.
Currently i'm meeting performance issues, cause whole operation can take even more than hour!
What are the possibilities to make it run faster?
I've already tried "Repair and compact db" function.<issue_comment>username_1: You can use [`re.findall`](https://docs.python.org/3/library/re.html#re.findall) with a capturing group as follows:
```
matches = re.findall( r'.*\[M(.*?)\]', '2018-01-23 - member data. member_id=[M001].')
print(matches[0]) # 001
```
Upvotes: 1 <issue_comment>username_2: You can use [`re.findall`](https://docs.python.org/3/library/re.html#re.findall) as follows:
```
matches = re.findall( r'\[M(\d{3})\]', '2018-01-23 - member data. member_id=[M001].')
print(matches[0])
out:
001
```
**Explanation:**
```
\d will find any number.
{3} will find occurrence of the match.
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: You say you already tried this:
```
m = re.search(r'member_id=[M(\d+)]', line)
```
but you need to escape the `[` and `]` characters, as they have a special meaning here. Try this:
```
m = re.search(r'member_id=\[M(\d+)\]', line)
```
Upvotes: 0
|
2018/03/14
| 582 | 2,098 |
<issue_start>username_0: I'm using kartik's fileInput widget. What I need to do is to change the size of browse icon and change the caption name (because now it is "Select file").. Im really struggling with that and I cannot find any information for the problem.
Here's my widget:
```
echo FileInput::widget([
'model' => $model,
'attribute' => 'user',
'pluginOptions' => [
'showPreview' => false,
'showRemove' => false,
'uploadLabel' => '',
'uploadIcon' => '',
'browseLabel' => '',
]
]);
```<issue_comment>username_1: You can use `browseClass` and `browseIcon` like below
```
'browseClass' => 'btn btn-success btn-block' ,
'browseIcon' => ' ' ,
```
you can adjust the css classes `btn btn-success` properties to match your needs
Upvotes: 1 <issue_comment>username_2: There is an option to change the button caption `browseLabel`:
```
echo 'Project Images ';
echo FileInput::widget([
'model' => $imagemodel,
'attribute' => 'upload_image[]',
'pluginOptions' => [
'initialPreviewConfig' => $imagesListId,
'overwriteInitial'=>false,
'previewFileType' => 'image',
'initialPreview' => $imagesListId1 ,
'showRemove' => true,
// 'deleteUrl'=>!empty($imagesID)? $imagesID:'',
'browseIcon' => ' ',
'browseLabel' => 'Upload Image',
'allowedFileExtensions' => ['jpg', 'png','jpeg','tiff','JPEG'],
'previewFileType' => ['jpg', 'png','jpeg','tiff','JPEG'],
'msgUploadBegin' => Yii::t('app', 'Please wait, system is uploading the files'),
'msgFilesTooMany' => 'Maximum 5 Images are allowed to be uploaded.',
"uploadAsync" => true,
"browseOnZoneClick" => true,
'maxFileSize' => 1024,
'showPreview' => true,
'showCaption' => true,
'showRemove' => true,
'showUpload' => false,
],
'options' => ['multiple' => true]
]);
```
This is what it look likes:
[](https://i.stack.imgur.com/5Qyve.jpg)
Upvotes: 0
|
2018/03/14
| 861 | 2,925 |
<issue_start>username_0: I am trying to implement multi-task CNN using adaptive `loss_weight`, which decays as the epoch increases. I referred to this [Github issue](https://github.com/keras-team/keras/issues/2595).
```
# callback for adaptive loss_weight
class LossWeightCallback(Callback):
def __init__(self, alpha):
self.alpha = alpha
def on_epoch_end(self, epoch, logs={}):
self.alpha = self.alpha * 0.9
# initial loss_weight
alpha = K.variable(10)
# model
img_input = Input(shape=(224, 224, 3), name='input')
...
model = Model(inputs=img_input, outputs=[y1, y2])
# compile
model.compile(keras.optimizers.SGD(lr=1e-4, momentum=0.9),
loss={'output1': 'categorical_crossentropy', 'output2': 'mse'},
loss_weights={'output1': 1, 'output2': alpha},
metrics={'output1': 'accuracy', 'output2': 'mse'})
# Fit model
checkpointer = ModelCheckpoint('multitask_model.h5', monitor='val_output1_acc', verbose=1, save_best_only=True)
results = model.fit(x_train, {'output1': y_train1, 'output2': y_train2},
validation_split=0.1, batch_size= 100, epochs=50,
callbacks=[checkpointer, LossWeightCallback(alpha)])
```
But this code returns an error after the 1st epoch ends:
```
TypeError: ('Not JSON Serializable:', )
```
Is there any solution to this error?
Thank you in advance.<issue_comment>username_1: You can use `browseClass` and `browseIcon` like below
```
'browseClass' => 'btn btn-success btn-block' ,
'browseIcon' => ' ' ,
```
you can adjust the css classes `btn btn-success` properties to match your needs
Upvotes: 1 <issue_comment>username_2: There is an option to change the button caption `browseLabel`:
```
echo 'Project Images ';
echo FileInput::widget([
'model' => $imagemodel,
'attribute' => 'upload_image[]',
'pluginOptions' => [
'initialPreviewConfig' => $imagesListId,
'overwriteInitial'=>false,
'previewFileType' => 'image',
'initialPreview' => $imagesListId1 ,
'showRemove' => true,
// 'deleteUrl'=>!empty($imagesID)? $imagesID:'',
'browseIcon' => ' ',
'browseLabel' => 'Upload Image',
'allowedFileExtensions' => ['jpg', 'png','jpeg','tiff','JPEG'],
'previewFileType' => ['jpg', 'png','jpeg','tiff','JPEG'],
'msgUploadBegin' => Yii::t('app', 'Please wait, system is uploading the files'),
'msgFilesTooMany' => 'Maximum 5 Images are allowed to be uploaded.',
"uploadAsync" => true,
"browseOnZoneClick" => true,
'maxFileSize' => 1024,
'showPreview' => true,
'showCaption' => true,
'showRemove' => true,
'showUpload' => false,
],
'options' => ['multiple' => true]
]);
```
This is what it look likes:
[](https://i.stack.imgur.com/5Qyve.jpg)
Upvotes: 0
|
2018/03/14
| 326 | 1,082 |
<issue_start>username_0: In vim I can use `:global/foo` to find lines matching foo. In normal mode I can also use `*` to find the next word under cursor.
Is there any (standard) way to do a `:global` with the word under the cursor? If it is not, what would be the best way to do it?<issue_comment>username_1: ```
:map gg* yaw:global/"
```
Let me explain step by step.
```
:map gg*
```
I decided to use the name `gg*` for the mapping to "extend" the command [`g*`](http://vimdoc.sourceforge.net/htmldoc/pattern.html#gstar). The name is actually bad as it stomps the command [`gg`](http://vimdoc.sourceforge.net/htmldoc/motion.html#gg). You can use any name you want.
```
yaw
```
Copy the word under cursor into the `"` buffer.
```
:global/
```
Start entering the command in the command line .
```
"
```
Paste the buffer `"` into the command line.
```
```
Execute the command.
Upvotes: 0 <issue_comment>username_2: Press to insert the word under cursor when editing command line (any command, not just `:global`).
See `:help c_CTRL-R`.
Upvotes: 3 [selected_answer]
|
2018/03/14
| 631 | 1,793 |
<issue_start>username_0: I have a column called Last Payment as such
```
last payment
12DEC09:00:00:00
```
all the observations follow this structure, I've tried taking a substring such that
```
data want;
set have;
last_payment=substr(last_payment,1,7);
run;
```
that doesn't work, I've tried formatting the date with the date7. and date.9 but both just return \*\*\*\*\*\*\*\*, can someone help me format it into a ddmmmyy ty.<issue_comment>username_1: You have to use datapart function before formating it in date7. or date9.
Example:
```
data new;
format date_new date9. ;
date_new = datepart("12DEC09:00:00:00"dt);
run;
```
Upvotes: 2 <issue_comment>username_2: The censored text means wrong format used.
* if last\_payment is a string then replace "datetime\_as\_string " with last\_payment.
* if last\_payment is datetime then replace "datetime\_as\_dt" with last\_payment.
The code below will handle the two cases where you are reading the date time as string and numeric values.
**Code:**
```
data new;
format datetime_as_dt datetime21. dt_to_date date7. datetime1 date7.;
datetime_as_dt="12DEC09:00:00:00"dt;
datetime_as_string ="12DEC09:00:00:00";
/*Converting datetime to date*/
dt_to_date= datepart(datetime_as_dt);
/*converting datetime string to date*/
/*Option1: Convert string to datetime then extract date*/
datetime1 = datepart(input(datetime_as_string,datetime21.));
/*Option2: Extract date from string then convert to date*/
datetime2 = scan(datetime_as_string,1,':');
put _all_;
run;
```
**Log:**
```
datetime_as_dt=12DEC2009:00:00:00
datetime_as_string=12DEC09:00:00:00
dt_to_date=12DEC09
datetime1=12DEC09
datetime2=12DEC09
```
**Table created:**
[](https://i.stack.imgur.com/5Pcz2.jpg)
Upvotes: 0
|
2018/03/14
| 609 | 1,561 |
<issue_start>username_0: I am using centOS 7 and my machine is changing IP randomly on restart. So, I want to assign IP static to get-rid from further changes on other areas.
For example I have to change ip address again and again in putty settings. etc<issue_comment>username_1: First you can check your IP and subnetmask details from your machine with command
```
ifconfig
```
**1st Solution :**
Create a file named /etc/sysconfig/network-scripts/ifcfg-eth0 as follows:
```
DEVICE=eth0
BOOTPROTO=none
ONBOOT=yes
PREFIX=24
IPADDR=192.004.6.123
```
Restart network service: systemctl restart network
**2nd Solution :**
Open default file vi /etc/sysconfig/network-scripts/ifcfg-ens33
and modify you settings according to below settings
```
IPADDR=192.004.6.123
NETMASK=255.255.255.0
BROADCAST=172.16.17.32
BOOTPROTO="static"
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Please follow the following steps to assign static IP in CentOs7
vim /etc/sysconfig/network-scripts/ifcfg-eth0
```
TYPE="Ethernet"
BOOTPROTO="static"
IPADDR=192.168.7.203
NETMASK=255.255.255.0
BROADCAST=192.168.7.255
NETWORK=192.168.7.0
GATEWAY=192.168.7.245
DNS1=8.8.8.8
DNS2=8.8.4.4
DEFROUTE="yes"
PEERDNS="yes"
PEERROUTES="yes"
IPV4_FAILURE_FATAL="no"
IPV6INIT="yes"
IPV6_AUTOCONF="yes"
IPV6_DEFROUTE="yes"
IPV6_PEERDNS="yes"
IPV6_PEERROUTES="yes"
IPV6_FAILURE_FATAL="no"
NAME="eth0"
UUID="696cc3d6-ac01-453b-967c-7decf10e6e6a"
DEVICE="eth0"
ONBOOT="yes"
ZONE=public
```
Now restart network interface by "service network restart"
its all done.
Upvotes: 2
|
2018/03/14
| 1,118 | 3,406 |
<issue_start>username_0: I’m using Grafana with Prometheus and want to use the World Map plugin: the idea is that I have several geopoints with some values that I want to visualize with World Map.
Data example that is being returned from prometheus has the following structure:
[](https://i.stack.imgur.com/B3MCq.png)
Also I edit probes.json and 100% shure that World Map plugin is using my customized probes.json file. Here is the part of it:
```
…
{
“key”: “taipei”,
“latitude”: 25.105497,
“longitude”: 121.597366,
“name”: “Taipei”
},
{
“key”: “tokyo”,
“latitude”: 35.652832,
“longitude”: 139.839478,
“name”: “Tokyo”
},
{
“key”: “y1918”,
“latitude”: 53.717564,
“longitude”: 91.429317,
“name”: “ABAKAN”
},
{
“key”: “szvpz”,
“latitude”: 44.993166,
“longitude”: 41.103135,
“name”: “ARMAVIR”
},
{
“key”: “ugkz7”,
“latitude”: 64.5562829,
“longitude”: 40.5962809,
“name”: “ARKHANGELSK”
},
{
“key”: “v04pt”,
“latitude”: 46.3432541,
“longitude”: 47.933211,
“name”: “ASTRAKHAN”
},
…
```
Here is the Grafana setup:
[](https://i.stack.imgur.com/PbG0G.png)
I get no error but there is no circles on the map, what am I doing wrong? What data should I provide to grafana from prometheus if it is the reason of the problem I’m having? Adding Legend format “{{geohash}}” doesn’t help either.<issue_comment>username_1: As per the [World Panel documentation](https://github.com/grafana/worldmap-panel#map-data-options), geohashes are not directly supported with Prometheus as a datasource, only countries and states.
But you can use them anyway if you also provide a custom json file with the location data to resolve them.
First, configure your Prometheus datasource and enter your query. Make sure you have the legend set to `{{ whatever your geohash field in the Prometheus timeseries is }}`. If I did not have the legend, set then nothing would display.
Now go to the "Worldmap" tab and set the drop-down to "json endpoint" and point the URL to wherever you keep your json file with the mappings.
Make sure it's valid json and make sure that the webserver sets correct CORS headers so your browser can load the file (confirm via the network inspector tab).
Now refresh the map and you should see your data points.
Upvotes: 1 <issue_comment>username_2: I was given an answer in [grafana community forum](https://community.grafana.com/t/prometheus-grafana-worldmap-not-working/1997/14) and going to repost it here, so people could find if they need it.
So it apears that World Map Plugin for Grafana with Prometheus is supporting geohash, despite the fact that it is not written in doc.
To make it work you have to enter corect settings, the data that I provide from Prometheus is correct. First you need to format metrics as a table:
[](https://i.stack.imgur.com/GW6aL.png)
In the Worldmap pannel you should enter following data:
[](https://i.stack.imgur.com/k1n7q.png)
For ES Metric Field to work with geohash you allways should enter "Value", ES Location Name Field is where do you went the points name from, and ES geo\_point Filed where do you get the data geohash value from. Data I'm getting from Prometheus you can find in a question part.
Upvotes: 1 [selected_answer]
|
2018/03/14
| 1,306 | 4,716 |
<issue_start>username_0: I have a requirement that on loading the google map application, have to automatically start the navigation.
Current scenario - It shows the route but user has to click on `start` to start navigation
I couldn't find any flag associated for the same?
[Found this article which shows the flags used in google maps](http://alvarestech.com/temp/routeconverter/RouteConverter/navigation-formats/src/main/doc/googlemaps/Google_Map_Parameters.htm)
[Official google maps docs](https://developers.google.com/maps/documentation/urls/guide) shows to use it as `dir_action=navigate` but I am clueless on how to translate it into `react-native-google-maps-directions` package
Any idea how could we approach the problem?<issue_comment>username_1: The [react-native-maps-directions](https://github.com/bramus/react-native-maps-directions) uses the Directions API to display routes. Please note that Directions API doesn't include any real-time navigation, it is meant only to show routes. The real-time navigation additionally is prohibited in the Google Maps APIs.
Have a look at the Google Maps API Terms of Service paragraph 10.4 (c, iii). It reads
>
> **No navigation.** You will not use the Service or Content for or in connection with (a) real-time navigation or route guidance; or (b) automatic or autonomous vehicle control.
>
>
>
source: <https://developers.google.com/maps/terms#10-license-restrictions>
In order to be compliant with Google Maps API Terms of Service you should open the Google Maps app installed in your device using the [Google Maps URLs](https://developers.google.com/maps/documentation/urls/guide#directions-action) in navigation mode.
```
var url = "https://www.google.com/maps/dir/?api=1&travelmode=driving&dir_action=navigate&destination=Los+Angeles";
Linking.canOpenURL(url).then(supported => {
if (!supported) {
console.log('Can\'t handle url: ' + url);
} else {
return Linking.openURL(url);
}
}).catch(err => console.error('An error occurred', err));
```
I hope this helps!
Upvotes: 6 [selected_answer]<issue_comment>username_2: ```js
import getDirections from "react-native-google-maps-directions";
...
handleGetDirections = () => {
const data = {
source: {
latitude: originLatitude,
longitude: originLongitude
},
destination: {
latitude: destinaationLatitude,
longitude: destinationLatitude
},
params: [
{
key: "travelmode",
value: "driving" // may be "walking", "bicycling" or "transit" as well
},
{
key: "dir_action",
value: "navigate" // this instantly initializes navigation using the given travel mode
}
]
}
getDirections(data)
}
```
**Source:** <https://www.npmjs.com/package/react-native-google-maps-directions#install>
Upvotes: 1 <issue_comment>username_3: >
> 100% work
>
>
>
If you want to auto-start navigation from your current location to specific location <https://developers.google.com/maps/documentation/urls/android-intents#launch_turn-by-turn_navigation>
>
> Sample Code
>
>
>
```
static googleMapOpenUrl = ({ latitude, longitude }) => {
const latLng = `${latitude},${longitude}`;
return `google.navigation:q=${latLng}`;
}
```
>
> To open google map on click React-Native will do like this
>
>
>
```
Linking.openURL(googleMapOpenUrl({ latitude: 23.235899, longitude: 78.323258 }));
```
Upvotes: 3 <issue_comment>username_4: Add an intent to `android/app/src/main/AndroidManifest.xml` (a new requirement since Android 11 SDK 30):
```xml
```
Use `Linking.openURL` with a [universal, cross-platform URL to launch Google Maps](https://developers.google.com/maps/documentation/urls/get-started#directions-action) e.g. The following example launches a map with bicycling directions from the Space Needle to Pike Place Market, in Seattle, WA:
```
Linking.canOpenURL(url).then((supported) => {
if (supported) {
Linking.openURL(`https://www.google.com/maps/dir/?api=1&origin=Space+Needle+Seattle+WA&destination=Pike+Place+Market+Seattle+WA&travelmode=bicycling`);
} else {
logger.error("Don't know how to open URI: " + url);
}
});
```
Sources
* Android intent - <https://stackoverflow.com/a/65114851/3469524>
* Linking.openURL - <https://stackoverflow.com/a/43804295/3469524>
* [Universal, cross-platform URL to launch Google Maps](https://developers.google.com/maps/documentation/urls/get-started#directions-action)
Upvotes: 0
|
2018/03/14
| 1,351 | 4,623 |
<issue_start>username_0: File name : URL.java
Content:
```
public static String serverURL = "http://192.168.127.12:8080";
public static String serverURL1 = "http://192.168.127.12:8080";
public static String serverURL2 = "http://192.168.127.12:8080";
public static String serverURL3 = "http://192.168.127.12:8080";
```
In the above file ,
I need to change the ServerURL variable value to <http://172.16.17.32:8080> dynamically using shell script
Note:
Should not change the value dynamically based on line number.
Some extra lines will get added to this file on future.
So i need to change the serverURL variable value based on some condition .<issue_comment>username_1: The [react-native-maps-directions](https://github.com/bramus/react-native-maps-directions) uses the Directions API to display routes. Please note that Directions API doesn't include any real-time navigation, it is meant only to show routes. The real-time navigation additionally is prohibited in the Google Maps APIs.
Have a look at the Google Maps API Terms of Service paragraph 10.4 (c, iii). It reads
>
> **No navigation.** You will not use the Service or Content for or in connection with (a) real-time navigation or route guidance; or (b) automatic or autonomous vehicle control.
>
>
>
source: <https://developers.google.com/maps/terms#10-license-restrictions>
In order to be compliant with Google Maps API Terms of Service you should open the Google Maps app installed in your device using the [Google Maps URLs](https://developers.google.com/maps/documentation/urls/guide#directions-action) in navigation mode.
```
var url = "https://www.google.com/maps/dir/?api=1&travelmode=driving&dir_action=navigate&destination=Los+Angeles";
Linking.canOpenURL(url).then(supported => {
if (!supported) {
console.log('Can\'t handle url: ' + url);
} else {
return Linking.openURL(url);
}
}).catch(err => console.error('An error occurred', err));
```
I hope this helps!
Upvotes: 6 [selected_answer]<issue_comment>username_2: ```js
import getDirections from "react-native-google-maps-directions";
...
handleGetDirections = () => {
const data = {
source: {
latitude: originLatitude,
longitude: originLongitude
},
destination: {
latitude: destinaationLatitude,
longitude: destinationLatitude
},
params: [
{
key: "travelmode",
value: "driving" // may be "walking", "bicycling" or "transit" as well
},
{
key: "dir_action",
value: "navigate" // this instantly initializes navigation using the given travel mode
}
]
}
getDirections(data)
}
```
**Source:** <https://www.npmjs.com/package/react-native-google-maps-directions#install>
Upvotes: 1 <issue_comment>username_3: >
> 100% work
>
>
>
If you want to auto-start navigation from your current location to specific location <https://developers.google.com/maps/documentation/urls/android-intents#launch_turn-by-turn_navigation>
>
> Sample Code
>
>
>
```
static googleMapOpenUrl = ({ latitude, longitude }) => {
const latLng = `${latitude},${longitude}`;
return `google.navigation:q=${latLng}`;
}
```
>
> To open google map on click React-Native will do like this
>
>
>
```
Linking.openURL(googleMapOpenUrl({ latitude: 23.235899, longitude: 78.323258 }));
```
Upvotes: 3 <issue_comment>username_4: Add an intent to `android/app/src/main/AndroidManifest.xml` (a new requirement since Android 11 SDK 30):
```xml
```
Use `Linking.openURL` with a [universal, cross-platform URL to launch Google Maps](https://developers.google.com/maps/documentation/urls/get-started#directions-action) e.g. The following example launches a map with bicycling directions from the Space Needle to Pike Place Market, in Seattle, WA:
```
Linking.canOpenURL(url).then((supported) => {
if (supported) {
Linking.openURL(`https://www.google.com/maps/dir/?api=1&origin=Space+Needle+Seattle+WA&destination=Pike+Place+Market+Seattle+WA&travelmode=bicycling`);
} else {
logger.error("Don't know how to open URI: " + url);
}
});
```
Sources
* Android intent - <https://stackoverflow.com/a/65114851/3469524>
* Linking.openURL - <https://stackoverflow.com/a/43804295/3469524>
* [Universal, cross-platform URL to launch Google Maps](https://developers.google.com/maps/documentation/urls/get-started#directions-action)
Upvotes: 0
|
2018/03/14
| 1,717 | 6,350 |
<issue_start>username_0: Consider a scenario, I have a function "REFRESH", this function is called by different methods simultaneously, let's say the methods are "A", "B", "C". If method "A" calls "REFRESH TOKEN" firstly then methods "B" and "C" should wait until it finishes.
How can I attain this scenario? Appreciate your help!
```
let serialQueue = DispatchQueue(label: "serialQueue")
var myFlag = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.refresh(param: 1) // Method A
self.refresh(param: 2) // Method B
self.refresh(param: 3) // Method C
}
// Method REFRESH
func refresh(param: NSInteger) -> Void {
let absolutePath = "MY SAMPLE API"
var headers: [String: String] = Dictionary();
headers["Content-Type"] = "application/json"
serialQueue.sync {
print("\nEntered ", param)
Alamofire.request(absolutePath, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseString {
response in
switch response.result {
case .success:
print("SUCCESS")
break
case .failure(let error):
print(error)
}
}
```
Above code output:
```
Entered 1
Entered 2
Entered 3
SUCCESS
SUCCESS
SUCCESS
```
I need an output like this:
```
Entered 1
SUCCESS
Entered 2
SUCCESS
Entered 3
SUCCESS
```<issue_comment>username_1: ```
func refresh(param: NSInteger, completion: (Void) -> ()) -> Void {
let absolutePath = "MY SAMPLE API"
var headers: [String: String] = Dictionary();
headers["Content-Type"] = "application/json"
print("\nEntered ", param)
Alamofire.request(absolutePath, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseString {
response in
switch response.result {
case .success:
completion()
break
case .failure(let error):
completion()
}
}
}
//In viewDidLoad :- Add these below code
// Create one custom queue.
let serialQueue = DispatchQueue(label: "serialQueue")
// Create one dispacth group.
let dispatchGorup = DispatchGroup()
//Call first refresh method with respective parameters.
dispatchGorup.enter()
//Wait for the response and then call leave method.
refresh(param: "") { (result) in
dispatchGorup.leave()
}
//Call second refresh method with respective parameters.
dispatchGorup.enter()
//Wait for the response and then call leave method.
refresh(param: "") { (result) in
dispatchGorup.leave()
}
//Indication that all the request is done.
dispatchGorup.notify(queue: serialQueue) {
Print("All methods invoked")
}
```
Upvotes: 2 <issue_comment>username_2: Something like this?
```
var param:[Int] = [1,2,3]
func refresh(){
DispatchQueue.global().async {
for i in 0..();
headers["Content-Type"] = "application/json"
Alamofire.request(absolutePath, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseString {
response in
switch response.result {
case .success:
print("SUCCESS")
break
case .failure(let error):
print(error)
}
group.leave()
}
group.wait()
}
}
}
```
Upvotes: 0 <issue_comment>username_3: Based on your request, I would say that you want a serialized calling of those `refresh` calls. That means that you have to wait until one call ends to call next.
Simple, but a bit ugly solution is to use completion closure:
```
override func viewDidLoad() {
super.viewDidLoad()
self.refresh(param: 1, completion: { [weak self] in
self?.refresh(param: 2, completion: { [weak self] in
self?.refresh(param: 3, completion: nil)
})
})
}
// Method REFRESH
func refresh(param: NSInteger, completion: (() -> Void)?) -> Void {
let absolutePath = "MY SAMPLE API"
var headers: [String: String] = Dictionary();
headers["Content-Type"] = "application/json"
print("\nEntered ", param)
Alamofire.request(absolutePath, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseString {
response in
switch response.result {
case .success:
print("SUCCESS")
break
case .failure(let error):
print(error)
}
completion?()
}
}
```
Based on what you say in your comment (that you just want to get refresh token from the first call and then it does not matter) you can rewrite `viewDidLoad` it as this:
```
self.refresh(param: 1, completion: { [weak self] in
// these two can now go in parallel, since the first call got you the refresh token
self?.refresh(param: 2, completion: nil)
self?.refresh(param: 3, completion: nil)
})
```
Upvotes: 0 <issue_comment>username_4: What you need is something called ***resource locking***. You can achieve this by using `DispatchGroup`.
First you need to create a `DispatchGroup`. Add a property in your controller:
```
let dispatchGroup = DispatchGroup()
```
Then modify your `refresh(param:)` function as: (I've modified some of the coding patterns)
```
func refresh(param: NSInteger) -> Void {
// You lock your resource by entering to the dispatch group
dispatchGroup.enter()
let absolutePath = "MY SAMPLE API"
var headers = [String: String]()
headers["Content-Type"] = "application/json"
print("Entered \(param)")
Alamofire.request(absolutePath, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseString { [weak self] (response) in
switch response.result {
case .success:
print("SUCCESS \(param)")
break
case .failure(let error):
print(error)
}
// You release the resource as soon as you get the response so that other processes may be able to use the resource
self?.dispatchGroup.leave()
}
// The lock continues by invoking the wait method
dispatchGroup.wait()
}
```
So, this will work as:
`Method 1` & `Method 2` are requesting to use the same resource. When `Method 1` is executing, `Method 2` will wait for Method 1 to finish. When `Method 1` is finished, `Method 2` will be given the opportunity to start it's execution.
***So, basically which method first starts executing will finish and then the other will be started***. Though it's not guaranteed which will start the execution first (As, you don't need dependency on each other). But it will depend on the sequence you invoke this method.
Upvotes: 3 [selected_answer]
|
2018/03/14
| 403 | 1,299 |
<issue_start>username_0: ```
with CTE AS
(
select AGENT_USERID,
ROW_NUMBER() OVER(PARTITION BY AGENT_USERID ORDER BY (agent_USERID)) AS RN
FROM KYCKEN.PAP_KYCAGENTCONFIG
)
DELETE FROM CTE where RN > 1
```
I am getting error that from statement is required while running the query. There is no code before that. Using the query to delete duplicates. Select in place of delete is working fine but while using the delete throwing error.<issue_comment>username_1: Db2 for Linux/Unix/Windows accepts the syntax below:
```
with cte as
(
select agent_userid
,row_number() over (partition by agent_userid order by (agent_userid)) as rn
from kycken.pap_kycagentconfig
)
select agent_userid as agent_userid_to_delete
from old table
( delete from kycken.pap_kycagentconfig
where agent_userid in (select agent_userid from cte where rn > 1)
)
;
```
Upvotes: 1 <issue_comment>username_2: On DB2, try Something like this :
```
DELETE FROM KYCKEN.PAP_KYCAGENTCONFIG f0
where rrn(f0) in
(
select f2.rnwrite
from (
select f1.AGENT_USERID, rrn(f1) rnwrite,
ROWNUMBER() OVER(PARTITION BY f1.AGENT_USERID ORDER BY f1.agent_USERID) AS RN
FROM KYCKEN.PAP_KYCAGENTCONFIG f1
) f2
where f2.RN>1
)
```
Upvotes: 0
|
2018/03/14
| 524 | 2,118 |
<issue_start>username_0: ```
module Main where
import Control.Monad.IO.Class
import Graphics.UI.Gtk
main :: IO ()
main = do
initGUI
window <- windowNew
canvas <- drawingAreaNew
widgetAddEvents canvas [Button1MotionMask]
canvas `on` motionNotifyEvent $ do
c <- eventCoordinates
liftIO $ print c
return False
containerAdd window canvas
widgetShowAll window
mainGUI
```
In the code above, I am trying to handle a 'mouse drag' on a `GtkDrawingArea`, where the left mouse button is depressed. However, nothing is printed, indicating that the event is never firing. Even stranger, when I change `Button1MotionMask` to `PointerMotionMask`, the event fires when I move my mouse normally (as expected), but not when I move the mouse while depressing the left mouse button. What is going on here? I am using the `gtk3-0.14.8` package on Windows 10.
**EDIT:** I should probably be a bit clearer about my problem. When I hold the left mouse button down while moving the mouse, `motionNotifyEvent`does not fire. This does not depend on whether I have added `PointerMotionMask` or `Button1MotionMask`.<issue_comment>username_1: Interesting, C documentation on motion-notify-event says
>
> To receive this signal, the GdkWindow associated to the widget needs to enable the GDK\_POINTER\_MOTION\_MASK mask
>
>
>
Enabling only GDK\_BUTTON1\_MOTION\_MASK doesn't work for me too.
Fortunately, GdkEventMotion has field `state`, where you can check whether button1 is pressed or not.
Upvotes: 0 <issue_comment>username_2: It doesn't seem to be mentioned in the documentation, but it turns out that you also need to enable `ButtonPressMask` to recieve *any* event with the mouse button pressed - including motion events which occur when the button is pressed down. This results in the paradoxical behaviour where enabling only `Button1MotionMask` results in no events being received unless you also enable `ButtonPressMask`. I finally figured this out after discovering the gtk-demo sample application - it's very useful for learning GTK!
Upvotes: 3 [selected_answer]
|
2018/03/14
| 315 | 1,219 |
<issue_start>username_0: ```
session.createStoredProcedureQuery("procedureName");
```
I am only getting `session.createSQLQuery`
**pom.xml**
```
org.hibernate
hibernate-core
5.2.12.Final
```
I want to use it for executing a stored procedure.<issue_comment>username_1: Interesting, C documentation on motion-notify-event says
>
> To receive this signal, the GdkWindow associated to the widget needs to enable the GDK\_POINTER\_MOTION\_MASK mask
>
>
>
Enabling only GDK\_BUTTON1\_MOTION\_MASK doesn't work for me too.
Fortunately, GdkEventMotion has field `state`, where you can check whether button1 is pressed or not.
Upvotes: 0 <issue_comment>username_2: It doesn't seem to be mentioned in the documentation, but it turns out that you also need to enable `ButtonPressMask` to recieve *any* event with the mouse button pressed - including motion events which occur when the button is pressed down. This results in the paradoxical behaviour where enabling only `Button1MotionMask` results in no events being received unless you also enable `ButtonPressMask`. I finally figured this out after discovering the gtk-demo sample application - it's very useful for learning GTK!
Upvotes: 3 [selected_answer]
|
2018/03/14
| 1,361 | 4,079 |
<issue_start>username_0: **Please have a look at the following fiddle:**
**<https://jsfiddle.net/y7w705wb/20/>**
```css
.row {
height: 25px;
width: 300px;
background-color: red;
overflow: visible;
border: 1px solid black;
position: absolute;
}
.modal {
width: 200px;
height: 100px;
background-color: yellow;
z-index: 10;
position: absolute;
left: 3px;
top: 3px;
}
```
```html
Content
Content
```
The second div row overlaps the yellow "modal popup" I created in the first row. I am trying to let the yellow box overlap the second row. How can I archive that?
My prerequisites are, that I have a bunch of rows, but in some of them I want to display a small popup window, that contains information.
This information should not be overlapped by subsequent rows.
**This is only a very basic example to show my core problem.
Any ideas?**
>
> Update:
>
>
>
**I updated my fiddle:**
**<https://jsfiddle.net/y7w705wb/20/>**
`The reason why I ask this question is, because I am using ag-grid as datatable in my app and want to display a modal inside one of the cells.
I cannot change the cell structure, so I really have to do it like in my fiddle example.`<issue_comment>username_1: Maybe try this:
HTML snippet:
```
Content
Content
```
CSS snippet:
```
.row {height: 25px; width: 300px; background-color: red; overflow: visible; border: 1px solid black;
position: relative;}
.modal {width: 200px; height: 100px; background-color: yellow; z-index: 10; position: absolute; left: 3px; top: 3px; }
```
Working fiddle: <https://jsfiddle.net/74kmte2g/5/>
Upvotes: 0 <issue_comment>username_2: A modal window is normally above the normal document flow. Therefor I wouldn't put it inside an other element.
Taking it outside `.row` fixes the problem as well.
```css
.row {
height: 25px;
width: 300px;
background-color: red;
overflow: visible;
border: 1px solid black;
z-index: 1;
position: relative;
}
.modal {
width: 200px;
height: 100px;
background-color: yellow;
z-index: 10;
position: absolute;
left: 3px;
top: 3px;
}
```
```html
Content
Content
```
Upvotes: 0 <issue_comment>username_3: Remove z-index: 1 from the .row class. It should work Fine.
Upvotes: 2 [selected_answer]<issue_comment>username_4: You can remove z-index for .row class
```
.row {
height: 25px;
width: 300px;
background-color: red;
overflow: visible;
border: 1px solid black;
position: relative;
}
.modal {
width: 200px;
height: 100px;
background-color: yellow;
z-index: 10;
position: absolute;
left: 3px;
top: 3px;
}
Content
Content
```
OR
You can try this also where z-index remains the same.
```
.row {
height: 25px;
width: 300px;
background-color: red;
overflow: visible;
z-index:1;
border: 1px solid black;
position: relative;
}
.modal {
width: 200px;
height: 100px;
background-color: yellow;
z-index: 10;
position: absolute;
left: 3px;
top: 3px;
}
Content
Content
```
OR you also have another solution for this issue:
.row div is a parent div so give it position relative and z-index for 1st div
```
.row {
height: 25px;
width: 300px;
background-color: red;
position:relative;
overflow: visible;
border: 1px solid black;
}
.modal {
width: 200px;
height: 100px;
background-color: yellow;
z-index: 10;
position: absolute;
left: 3px;
top: 3px;
}
Content
Content
```
Upvotes: 2 <issue_comment>username_5: **Try this one**
I just switch `modal & second .row`.
**Here is the working code**
```css
.row {
height: 25px;
width: 300px;
background-color: red;
overflow: visible;
border: 1px solid black;
position: absolute;
}
.modal {
width: 200px;
height: 100px;
background-color: yellow;
z-index: 10;
position: absolute;
left: 3px;
top: 3px;
}
```
```html
Content
Content
```
Upvotes: 0
|
2018/03/14
| 1,269 | 4,012 |
<issue_start>username_0: I'm using the official [Google Node connector to BigQuery](https://github.com/googleapis/nodejs-bigquery).
I have the following snippet to stream records into the database:
```
module.exports.sendToBigQuery = (rows) => {
bigquery
.dataset(DATASET_NAME)
.table(TABLE_NAME)
.insert(rows)
.catch(err => {
if (err && err.name === 'PartialFailureError') {
if (err.errors && err.errors.length > 0) {
console.log('Insert errors:');
err.errors.forEach(err => console.error(err));
}
} else {
console.error('ERROR:', err);
}
});
};
```
Unfortunately, whenever my data doesn't match the scema, all I'm getting is this cryptic error object:
`{ errors: [ { message: 'no such field.', reason: 'invalid' } ],`
There is no `location` field that would tell me which field is missing which makes debugging this code a nightmare for more complex schemas.
Is there any way to enable debug level of errors somehow? Or it's just a bug in client implementation? Any idea how I could access this information?<issue_comment>username_1: Maybe try this:
HTML snippet:
```
Content
Content
```
CSS snippet:
```
.row {height: 25px; width: 300px; background-color: red; overflow: visible; border: 1px solid black;
position: relative;}
.modal {width: 200px; height: 100px; background-color: yellow; z-index: 10; position: absolute; left: 3px; top: 3px; }
```
Working fiddle: <https://jsfiddle.net/74kmte2g/5/>
Upvotes: 0 <issue_comment>username_2: A modal window is normally above the normal document flow. Therefor I wouldn't put it inside an other element.
Taking it outside `.row` fixes the problem as well.
```css
.row {
height: 25px;
width: 300px;
background-color: red;
overflow: visible;
border: 1px solid black;
z-index: 1;
position: relative;
}
.modal {
width: 200px;
height: 100px;
background-color: yellow;
z-index: 10;
position: absolute;
left: 3px;
top: 3px;
}
```
```html
Content
Content
```
Upvotes: 0 <issue_comment>username_3: Remove z-index: 1 from the .row class. It should work Fine.
Upvotes: 2 [selected_answer]<issue_comment>username_4: You can remove z-index for .row class
```
.row {
height: 25px;
width: 300px;
background-color: red;
overflow: visible;
border: 1px solid black;
position: relative;
}
.modal {
width: 200px;
height: 100px;
background-color: yellow;
z-index: 10;
position: absolute;
left: 3px;
top: 3px;
}
Content
Content
```
OR
You can try this also where z-index remains the same.
```
.row {
height: 25px;
width: 300px;
background-color: red;
overflow: visible;
z-index:1;
border: 1px solid black;
position: relative;
}
.modal {
width: 200px;
height: 100px;
background-color: yellow;
z-index: 10;
position: absolute;
left: 3px;
top: 3px;
}
Content
Content
```
OR you also have another solution for this issue:
.row div is a parent div so give it position relative and z-index for 1st div
```
.row {
height: 25px;
width: 300px;
background-color: red;
position:relative;
overflow: visible;
border: 1px solid black;
}
.modal {
width: 200px;
height: 100px;
background-color: yellow;
z-index: 10;
position: absolute;
left: 3px;
top: 3px;
}
Content
Content
```
Upvotes: 2 <issue_comment>username_5: **Try this one**
I just switch `modal & second .row`.
**Here is the working code**
```css
.row {
height: 25px;
width: 300px;
background-color: red;
overflow: visible;
border: 1px solid black;
position: absolute;
}
.modal {
width: 200px;
height: 100px;
background-color: yellow;
z-index: 10;
position: absolute;
left: 3px;
top: 3px;
}
```
```html
Content
Content
```
Upvotes: 0
|
2018/03/14
| 1,068 | 3,146 |
<issue_start>username_0: i have a table with two column compay id and revenueper. I want to fetch conpany list where revenueper is >50 if this criteria returns >=60 records then fine else reduce the criteria by 5 points and fetch where revenueper >50-5 and reduce the points by 5 till the count is >=60.
Please help.<issue_comment>username_1: Maybe try this:
HTML snippet:
```
Content
Content
```
CSS snippet:
```
.row {height: 25px; width: 300px; background-color: red; overflow: visible; border: 1px solid black;
position: relative;}
.modal {width: 200px; height: 100px; background-color: yellow; z-index: 10; position: absolute; left: 3px; top: 3px; }
```
Working fiddle: <https://jsfiddle.net/74kmte2g/5/>
Upvotes: 0 <issue_comment>username_2: A modal window is normally above the normal document flow. Therefor I wouldn't put it inside an other element.
Taking it outside `.row` fixes the problem as well.
```css
.row {
height: 25px;
width: 300px;
background-color: red;
overflow: visible;
border: 1px solid black;
z-index: 1;
position: relative;
}
.modal {
width: 200px;
height: 100px;
background-color: yellow;
z-index: 10;
position: absolute;
left: 3px;
top: 3px;
}
```
```html
Content
Content
```
Upvotes: 0 <issue_comment>username_3: Remove z-index: 1 from the .row class. It should work Fine.
Upvotes: 2 [selected_answer]<issue_comment>username_4: You can remove z-index for .row class
```
.row {
height: 25px;
width: 300px;
background-color: red;
overflow: visible;
border: 1px solid black;
position: relative;
}
.modal {
width: 200px;
height: 100px;
background-color: yellow;
z-index: 10;
position: absolute;
left: 3px;
top: 3px;
}
Content
Content
```
OR
You can try this also where z-index remains the same.
```
.row {
height: 25px;
width: 300px;
background-color: red;
overflow: visible;
z-index:1;
border: 1px solid black;
position: relative;
}
.modal {
width: 200px;
height: 100px;
background-color: yellow;
z-index: 10;
position: absolute;
left: 3px;
top: 3px;
}
Content
Content
```
OR you also have another solution for this issue:
.row div is a parent div so give it position relative and z-index for 1st div
```
.row {
height: 25px;
width: 300px;
background-color: red;
position:relative;
overflow: visible;
border: 1px solid black;
}
.modal {
width: 200px;
height: 100px;
background-color: yellow;
z-index: 10;
position: absolute;
left: 3px;
top: 3px;
}
Content
Content
```
Upvotes: 2 <issue_comment>username_5: **Try this one**
I just switch `modal & second .row`.
**Here is the working code**
```css
.row {
height: 25px;
width: 300px;
background-color: red;
overflow: visible;
border: 1px solid black;
position: absolute;
}
.modal {
width: 200px;
height: 100px;
background-color: yellow;
z-index: 10;
position: absolute;
left: 3px;
top: 3px;
}
```
```html
Content
Content
```
Upvotes: 0
|
2018/03/14
| 1,274 | 4,628 |
<issue_start>username_0: I would like my node.js project to generate log files that are a bit similar to log4j format in that I would like each log line to commence with the file name and the js function name that the log request originated from.
e.g:
If my js file is called aNiceFile.js and my js function is called doImportantStuff() and I invoke a log statement with something like:
```
log.info('About to start on the important stuff')
```
I would like my log file to look a bit like:
```
2018-03-14 06:33:26:619 INFO aNiceFile.js doImportantStuff() About to start on the important stuff.
```
I want to do a lot of logging, so I don't mind one off, upfront effort to set this up, but I am after minimal additional effort per file / function that I add to my code.
I am using [Winston](https://github.com/winstonjs) today, I am happy to switch to something else if that is necessary, with Winston this does not seem to be possible without some effort on my part: <https://github.com/winstonjs/winston/issues/200>
For completeness, I don't *need* the line numbers, but they would be nice to have too.
My current clumsy work around is to:
1) Start each file with this to get the current file name:
```
const sn = path.basename(__filename) // this script file name, used for logging purposes
```
I am ok with this step, it is not onerous, a single *identical* line pasted at the top of each file, I can accept this.
2) Start each function with this to get the current function name:
```
const fn = '*'*
```
I don't like this step, I have to copy the function name into the string constant, and it could get out of sync later if I rename the function.
If I could turn this into the version below that would be better, not sure how to do that:
```
const fn = getCurrentFunctionName()
```
3) I do each log statement like this:
```
log.info(`${sn}:${fn} Starting important stuff`)
```
I don't like this step because all my log statements start with this (${sn}:${fn}) noise.
As you can see this is primitive, but it does work. What should I really be doing here?
I am interested in performance so solutions that require the generation of an Error object to harvest a stack trace from are probably not acceptable.<issue_comment>username_1: Edit adding all stuff.
This is a basic example of filename, lines, columns and caller function. Maybe you need to adapt somethings. But this is the idea.
```js
let log = {
info: function info(message) {
const callerInfo = getFileName(info.caller.name);
console.log(
new Date() +
' ' +
arguments.callee.name.toUpperCase() +
' ' +
callerInfo.filename +
':' +
callerInfo.line +
':' +
callerInfo.column +
' ' +
info.caller.name +
'() ' +
message
);
},
};
function getFileName(caller) {
const STACK_FUNC_NAME = new RegExp(/at\s+((\S+)\s)?\((\S+):(\d+):(\d+)\)/);
let err = new Error();
Error.captureStackTrace(err);
let stacks = err.stack.split('\n').slice(1);
let callerInfo = null;
for (let i = 0; i < stacks.length; i++) {
callerInfo = STACK_FUNC_NAME.exec(stacks[i]);
if (callerInfo[2] === caller) {
return {
filename: callerInfo[3],
line: callerInfo[4],
column: callerInfo[5],
};
}
}
return null;
}
function iWantToLog() {
log.info('Testing my log');
}
iWantToLog();
```
Upvotes: 3 <issue_comment>username_2: A colleague suggested using a Gulp PreProcess to solve this issue. The idea being I would not perform any of the manual steps 1) 2) and 3) described above, however before running/deploying my code, I would feed it through a Gulp preprocess which would update all my js source code, adding all of code described in steps 1) 2) and 3).
I have not used Gulp much, but on the surface, this sounds like a promising idea. On the upside:
1. as long as Gulp can update my source files as required it will work
2. should not cause any significant runtime js performance issues, no requirement for generation of js Error objects to create stack traces from which to extract script and function names
3. my source code will not be littered with any of this extra code to log script name and function name
On the down side:
1. need to make Gulp part of my workflow - that seems acceptable
2. I need to setup the gulp preprocessor to alter my js source - no idea how hard this will be, would [gulp pre-process](https://www.npmjs.com/package/gulp-preprocess "gulp-preprocess") be my starting point?
3. when I make code changes to js source files Gulp will need to rerun each time, impacting my iteration time
Upvotes: 2
|
2018/03/14
| 1,442 | 5,888 |
<issue_start>username_0: I've read about bindActionCreators, i've compiled a resumen here:
```
import { addTodo,deleteTodo } from './actionCreators'
import { bindActionCreators } from 'redux'
function mapStateToProps(state) {
return { todos: state.todos }
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ addTodo, deleteTodo }, dispatch)
}
*short way
const mapDispatchToProps = {
addTodo,
deleteTodo
}
export default connect(mapStateToProps, mapDispatchToProps)(TodoApp)
```
another code use like this:
```
function mapDispatchToProps(dispatch) {
let actions = bindActionCreators({ getApplications });
return { ...actions, dispatch };
}
```
why previous code with bindActionCreators , don't need disptach parameter?
i've tried this way to get dispatch on this.props (but not working):
```
const mapDispatchToProps = (dispatch) => {
return bindActionCreators ({ appSubmitStart, appSubmitStop}, dispatch );
};
const withState = connect(
null ,
mapDispatchToProps,
)(withGraphqlandRouter);
```
why I had to change my old short way:
```
const withState = connect(
null ,
{ appSubmitStart, appSubmitStop}
)(withGraphqlandRouter);
```
in order to get this.props.dispatch()? because i neede to use dispatch for an isolated action creator inside a library with js functions. I mean before I don't needed use "bindActionCreators", reading this doc:
<https://redux.js.org/api-reference/bindactioncreators>
"The only use case for bindActionCreators is when you want to pass some action creators down to a component that isn't aware of Redux, and you don't want to pass dispatch or the Redux store to it."
I'm importing:
```
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
```
what is the difference using redux pure, and react-redux?
really I need "bindActionCreators" in my new code? because without this i can't see this.props.dispatch()
UPDATE:
I've found this solutions to get this.props.dispatch working:
```
const mapDispatchToProps = (dispatch) => {
return bindActionCreators ({ appSubmitStart, appSubmitStop, dispatch }, dispatch ); // to set this.props.dispatch
};
```
does anyone can explain me? how i can send same distpach like a creator ?<issue_comment>username_1: I have made some changes to your code please try this
```
import * as Actions from './actionCreators'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
const mapStateToProps = (state)=>(
{
todos: state.todos
}
)
const mapDispatchToProps = (dispatch)=> (
bindActionCreators(Actions, dispatch)
)
export default connect(mapStateToProps, mapDispatchToProps)(TodoApp)
```
Upvotes: 2 <issue_comment>username_2: First let's clear our minds regarding some of the key concepts here:
* `bindActionCreators` is a util provided by Redux. It wraps each action creators to a dispatch call so they may be invoked directly.
* `dispatch` is a function of the Redux store. It is used to dispatch actions to store.
+ When you use the object shorthand for `mapState`, React-Redux wraps them with the store's `dispatch` using Redux's `bindActionCreators`.
* `connect` is a function provided by React-Redux. It is used to connect your component to the Redux store. When you connect your component:
+ It injects `dispatch` to your component **only if** you do not provide your customized `mapDispatchToProps` parameter.
Regarding what happened above to your code:
### Component will not receive `dispatch` with customized `mapDispatchToProps`
In the code here:
```
const mapDispatchToProps = (dispatch) => {
return bindActionCreators(
{ appSubmitStart, appSubmitStop, dispatch }, // a bit problematic here, explained later
dispatch
); // to set this.props.dispatch
};
```
You are providing your own `mapDispatch`, therefore your component will **not** receive `dispatch`. Instead, it will rely on your returned object to contain the action creators wrapped around by `dispatch`.
As you may feel it is easy to make mistake here. It is suggested that you use the object shorthand directly, feeding in all the action creators your component will need. React-Redux binds each one of those with `dispatch` for you, and do not give `dispatch` anymore. (See [this issue](https://github.com/reduxjs/react-redux/issues/255) for more discussion.)
### Writing customized `mapState` and inject `dispatch` manually
However, if you do need `dispatch` specifically alongside other action dispatchers, you will need to define your `mapDispatch` this way:
```
const mapDispatchToProps = (dispatch) => {
return {
appSubmitStart: () => dispatch(appSubmitStart),
appSubmitStop: () => dispatch(appSubmitStop),
dispatch,
};
};
```
### Using `bindActionCreators`
This is exactly what `bindActionCreators` does. Therefore, you can simplify a bit by using Redux's `bindActionCreators`:
```
const mapDispatchToProps = (dispatch) => {
return bindActionCreators(
{ appSubmitStart, appSubmitStop }, // do not include dispatch here
dispatch
);
};
```
As mentioned above, the problem to include `dispatch` in the first argument is that it essentially gets it wrapped around by `dispatch`. You will be calling `dispatch(dispatch)` when you call `this.props.dispatch`.
However, `bindActionCreators` does not return the object with `dispatch`. It's passed in for it to be called internally, it does not give it back to you. So you will need to include that by yourself:
```
const mapDispatchToProps = (dispatch) => {
return {
...bindActionCreators({appSubmitStart, appSubmitStop}, dispatch),
dispatch
};
};
```
Hope it helped! And please let me know if anything here is unclear :)
Upvotes: 4 [selected_answer]
|
2018/03/14
| 526 | 1,882 |
<issue_start>username_0: I wanted to Embed to twitter widget in my angular app, however, the data-widget-id required in twitter is stored in the database when I pass the widget id from variable twitter component does not render if I pass the widget id hard code string then twitter widget loads successfully
```
```
Here is and Example
<https://stackblitz.com/edit/angular-xxavf8?file=app%2Fapp.component.html><issue_comment>username_1: Your code has two problems. You use `twitterWigetId` in your markup but your defined attribute is `witterWigetId`. Also, change it to `string` from `number`
I, also, recommend you define `twttr` at the top of your class so that your IDE does not give error.
`declare var twttr: any;`
Check out following code
```
import { Component , AfterViewInit , ViewChild } from '@angular/core';
declare var twttr: any;
@Component({
selector: 'my-app',
template: ' '
})
export class AppComponent implements AfterViewInit {
twitterWidgetId = '973470934035202049';
ngAfterViewInit() {
twttr.widgets.load();
}
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Best way to integrate any twitter widgets in Angular2
You can easily pass widget-id in options
Use <https://www.npmjs.com/package/ngx-twitter-widgets>
Install package
```
npm install --save ngx-twitter-widgets
```
Import NgxTwitterWidgetsModule to NgModule
```
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgxTwitterWidgetsModule } from "ngx-twitter-widgets";
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
NgxTwitterWidgetsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
```
Use ngx-twitter-timeline tag to your template
```
```
Upvotes: 0
|
2018/03/14
| 986 | 2,680 |
<issue_start>username_0: How can i change this:
```
array_of_hash = [{"month"=>"January", "count"=>67241},
{"month"=>"February", "count"=>60464},
{"month"=>"March", "count"=>30403}]
```
To this :
```
month = ["January", "February", "March"]
count = [67241, 60464,30403]
```<issue_comment>username_1: A simple solution is to iterate the array of hashes and add the required values to two separate arrays:
```
months = []
counts = []
array_of_hash.each do |hash|
months << hash["month"]
counts << hash["count"]
end
```
But you could also use `each_with_object`
```
months, count = array_of_hash.each_with_object([[], []]) do |hash, accu|
accu[0] << hash["month"]
accu[1] << hash["count"]
end
```
or iterate twice and get the months and counts separately:
```
months = array_of_hash.map { |hash| hash["month"] }
counts = array_of_hash.map { |hash| hash["count"] }
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
months, counts =
array_of_hash.
flat_map(&:values).
partition(&String.method(:===))
```
---
```
months, counts =
%w|month count|.map { |key| array_of_hash.map { |h| h[key] } }
```
Upvotes: 1 <issue_comment>username_3: ```
month = []
count = []
array_of_hash.each do |hash|
month << hash['month']
count << hash['count']
end
```
Upvotes: 0 <issue_comment>username_4: To extract a single value (e.g. `'month'`), you could use [`map`](http://ruby-doc.org/core-2.5.0/Array.html#method-i-map):
```
array_of_hash.map { |hash| hash['month'] }
#=> ["January", "February", "March"]
```
Which can be extended to return the values for both, `'month` and `'count'`:
```
array_of_hash.map { |h| [h['month'], h['count']] }
#=> [["January", 67241], ["February", 60464], ["March", 30403]]
```
There's also a method to fetch multiple values at once – [`values_at`](http://ruby-doc.org/core-2.5.0/Hash.html#method-i-values_at):
```
array_of_hash.map { |h| h.values_at('month', 'count') }
#=> [["January", 67241], ["February", 60464], ["March", 30403]]
```
The resulting array can then be rearranged via [`transpose`](http://ruby-doc.org/core-2.5.0/Array.html#method-i-transpose):
```
array_of_hash.map { |h| h.values_at('month', 'count') }.transpose
#=> [["January", "February", "March"], [67241, 60464, 30403]]
```
The two inner arrays can be assigned to separate variables using Ruby's [array decomposition](http://ruby-doc.org/core-2.5.0/doc/syntax/assignment_rdoc.html#label-Array+Decomposition):
```
months, counts = array_of_hash.map { |h| h.values_at('month', 'count') }.transpose
months #=> ["January", "February", "March"]
counts #=> [67241, 60464, 30403]
```
Upvotes: 2
|
2018/03/14
| 452 | 1,544 |
<issue_start>username_0: I have a search bar which works fine but it produces a duplicate every time it shows the correct result.
```
if params[:nav_search]
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).page(params[:page]).per_page(18)
end
```
Any clue where I'm going wrong?<issue_comment>username_1: include **.uniq**
try this,
```
if params[:nav_search]
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).uniq.page(params[:page]).per_page(18)
end
```
Upvotes: 0 <issue_comment>username_2: Use `uniq` or `distinct` to avoid duplicate records. In your case, you should use `distinct`:
```
if params[:nav_search]
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).distinct.page(params[:page]).per_page(18)
end
```
Upvotes: 0 <issue_comment>username_3: Try to the following
```
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).distinct.page(params[:page]).per_page(18)
```
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.
You can see this [`Rails Guide`](http://guides.rubyonrails.org/active_record_querying.html#retrieving-objects-from-the-database) for very well understand
Upvotes: 2 [selected_answer]
|
2018/03/14
| 412 | 1,452 |
<issue_start>username_0: How could people have been using this code editor for HTML when it butchers this © and this ™? When I edit the page any © symbol will look like a triangle with a question mark and when the page is saved they will look like this �.<issue_comment>username_1: include **.uniq**
try this,
```
if params[:nav_search]
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).uniq.page(params[:page]).per_page(18)
end
```
Upvotes: 0 <issue_comment>username_2: Use `uniq` or `distinct` to avoid duplicate records. In your case, you should use `distinct`:
```
if params[:nav_search]
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).distinct.page(params[:page]).per_page(18)
end
```
Upvotes: 0 <issue_comment>username_3: Try to the following
```
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).distinct.page(params[:page]).per_page(18)
```
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.
You can see this [`Rails Guide`](http://guides.rubyonrails.org/active_record_querying.html#retrieving-objects-from-the-database) for very well understand
Upvotes: 2 [selected_answer]
|
2018/03/14
| 523 | 1,919 |
<issue_start>username_0: I'm working in a strong regulation context, in which using opensource libraries (which is almost synonym of *on GitHub* nowadays) is permitted as long as you're able to have the source of all these libs.
During feasibility stage , I've been linking libs on my project using nuget, storing the project in Git, so far so good.
Before going in production stage, I would like to be able (at least for each production release, even for nightly builds if possible) to have "somewhere" the source of all the libraries that I use.
There might be a strategy for doing this without nuget but with git and submodules, but It doesn't look obvious for me.
Anyone has an idea about how to do this ?
Thanks !<issue_comment>username_1: include **.uniq**
try this,
```
if params[:nav_search]
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).uniq.page(params[:page]).per_page(18)
end
```
Upvotes: 0 <issue_comment>username_2: Use `uniq` or `distinct` to avoid duplicate records. In your case, you should use `distinct`:
```
if params[:nav_search]
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).distinct.page(params[:page]).per_page(18)
end
```
Upvotes: 0 <issue_comment>username_3: Try to the following
```
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).distinct.page(params[:page]).per_page(18)
```
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.
You can see this [`Rails Guide`](http://guides.rubyonrails.org/active_record_querying.html#retrieving-objects-from-the-database) for very well understand
Upvotes: 2 [selected_answer]
|
2018/03/14
| 428 | 1,551 |
<issue_start>username_0: When I push a commit in to git repository, i need some validations to be happening in the commit message. How do i mimic "git push" command with some other?
For example have a function in bash profile which gets invoked when i type git push?
How to have a function in bash profile which can contain space in between function name?<issue_comment>username_1: include **.uniq**
try this,
```
if params[:nav_search]
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).uniq.page(params[:page]).per_page(18)
end
```
Upvotes: 0 <issue_comment>username_2: Use `uniq` or `distinct` to avoid duplicate records. In your case, you should use `distinct`:
```
if params[:nav_search]
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).distinct.page(params[:page]).per_page(18)
end
```
Upvotes: 0 <issue_comment>username_3: Try to the following
```
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).distinct.page(params[:page]).per_page(18)
```
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.
You can see this [`Rails Guide`](http://guides.rubyonrails.org/active_record_querying.html#retrieving-objects-from-the-database) for very well understand
Upvotes: 2 [selected_answer]
|
2018/03/14
| 410 | 1,445 |
<issue_start>username_0: I need to read some words text by text in python, and I am getting this error.
"NameError: global name 'wordList' is not defined.
```
i=0
with fitxer as f:
for line in f:
for word in line.split():
wordList[i]=word
i+1
return wordList
```<issue_comment>username_1: `wordList` is not instantiated as a list or not in scope.
~~If `wordList` is a global variable, the beginning of your function will need `global wordList`~~ *Not needed because the object is mutated*
If the list should only be in scope of the function you will need to instantiate it as a list.
```
wordList = []
```
Edit: as [deceze](https://stackoverflow.com/users/476/deceze) pointed out
Within the function itself you should be appending to the list since the index does not exists.
```
wordList.append(word)
```
Upvotes: 0 <issue_comment>username_2: You haven't defined `wordList` before you try to use it in your loop or return it.
Try adding `wordList = []` below `i=0` to declare `wordList` as an empty list.
Also, you should use `wordList.append(i)` to add your word this list.
Upvotes: -1 <issue_comment>username_3: You need to define wordList to begin with. And you cannot randomly assign indexes in an empty list. You can easily 'extend' the list with new values.
```
worldList = []
with fitxer as f:
for line in f:
wordList.extend(line.split())
return wordList
```
Upvotes: 1
|
2018/03/14
| 647 | 2,722 |
<issue_start>username_0: I want to know if this is a good practice to use my model class in controllers in this way :
```
public function __construct(Rule $rules)
{
$this->rules = $rules;
}
```
I do not want to repeat myself in my controllers so I want to know what is the best approach for that<issue_comment>username_1: You use Dependency Injection - it is very good practice.
According to documentation:
Dependency injection is a fancy phrase that essentially means this: class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods.
```
namespace App\Http\Controllers;
use App\User;
use App\Repositories\UserRepository;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* The user repository implementation.
*
* @var UserRepository
*/
protected $users;
/**
* Create a new controller instance.
*
* @param UserRepository $users
* @return void
*/
public function __construct(UserRepository $users)
{
$this->users = $users;
}
/**
* Show the profile for the given user.
*
* @param int $id
* @return Response
*/
public function show($id)
{
$user = $this->users->find($id);
return view('user.profile', ['user' => $user]);
}
}
```
In this example, the UserController needs to retrieve users from a data source. So, we will inject a service that is able to retrieve users. In this context, our UserRepository most likely uses Eloquent to retrieve user information from the database. However, since the repository is injected, we are able to easily swap it out with another implementation. We are also able to easily "mock", or create a dummy implementation of the UserRepository when testing our application.
Read also about Service Container - it is powerful tool:
<https://laravel.com/docs/5.6/container>
Upvotes: 4 [selected_answer]<issue_comment>username_2: It is a good practice for injecting models in controllers, however, the recommended approach is:
* Have a use statement at the top of your controller file
* Implement it in the functions that requires access to the model, i would not recommend you do it in your controller
* If you have a look at the documentation, you will be able to bind the model directly to your route and eliminate some hassle of Model::find(id) <https://laravel.com/docs/5.6/routing#route-model-binding>
The constructor approach you presented is recommended in using other classes like repositories, singletons, or whatever functionality you wish to inject, see the docs for more info: <https://laravel.com/docs/5.6/container>
Hope this helps
Upvotes: 0
|
2018/03/14
| 907 | 2,757 |
<issue_start>username_0: Configuring SSH Keys from ePass2003 to access servers.
I have a guest ubuntu 16.04 on VirtualBox, i am able to SSH server 1 from VM but while SSH to server 2 from server 1, getting below error.
```
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /usr/lib/x86_64-linux-gnu/opensc-pkcs11.so
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 60
debug1: Server accepts key: pkalg rsa-sha2-512 blen 279
debug2: input_userauth_pk_ok: fp SHA256:M0HzYuvGQ8LcKpJIGPgQDrN6Xs8jpyjH4wRQdslGeV
debug3: sign_and_send_pubkey: RSA SHA256:M0HzYuvGQ8LcKpJIGPgQDrN6Xs8jpyjH4wRQdslGeV
**sign_and_send_pubkey: signing failed: agent refused operation**
```
When i run *ssh-add -l* on server 2, i can see the below output.
```
$ ssh-add -l
error fetching identities for protocol 1: agent refused operation
2048 SHA256:M0HzYuvGQ8LcKpJIGPgQDrN6Xs8jpyjH4wRQdslGeV /usr/lib/x86_64-linux-gnu/opensc-pkcs11.so (RSA)
```
I have made *AllowAgentForwarding yes* in */etc/ssh/sshd\_config* file. But still no luck in getting SSH connection to Server2 from Server1.
If anyone can help me getting through this would be great.
Thanks in Advance !!<issue_comment>username_1: I was able to get the fix for connection issue with SSH Keys. I had to make changes in SSH config files at location ***/etc/ssh/ssh\_config*** and ***~/.ssh/config***
```
$ cat ~/.ssh/config
Host *
Compression yes
ForwardAgent yes
ForwardX11Trusted no
GSSAPIAuthentication no
PreferredAuthentications=publickey
```
and
```
$ cat /etc/ssh/ssh_config
Host *
ForwardAgent yes
ForwardX11Trusted yes
HashKnownHosts yes
GSSAPIAuthentication no
GSSAPIDelegateCredentials no
```
After above changes, restart **ssh-agent** and do **ssh-add**.
```
$ eval $(ssh-agent)
$ ssh-add -s /usr/lib/x86_64-linux-gnu/opensc-pkcs11.so
```
I hope this should work with you all as well if you come across such issues.
Upvotes: 3 <issue_comment>username_2: I'd just like to add that I saw the same issue (in Ubuntu 18.04) and it was caused by bad permissions on my private key files. I did `chmod 600` on the relevant files and the problem was resolved. Not sure why ssh-agent didn't complain about this until today.
Upvotes: 3 <issue_comment>username_3: We only need to execute this time.
```
eval "$(ssh-agent -s)"
Ssh-add
```
That's OK.
Upvotes: 1 <issue_comment>username_4: kind of random, but make sure your network isn't blocking it. I was at a hotel and I couldn't ssh into a server. I tried connecting in through my phones hotspot and it worked immediately. Give a different network a try as a quick way to trouble shoot.
Upvotes: -1
|
2018/03/14
| 475 | 1,631 |
<issue_start>username_0: I tried to install face recognition in python 2.7.but i am getting the below error[enter image description here](https://i.stack.imgur.com/bIExe.png)<issue_comment>username_1: I was able to get the fix for connection issue with SSH Keys. I had to make changes in SSH config files at location ***/etc/ssh/ssh\_config*** and ***~/.ssh/config***
```
$ cat ~/.ssh/config
Host *
Compression yes
ForwardAgent yes
ForwardX11Trusted no
GSSAPIAuthentication no
PreferredAuthentications=publickey
```
and
```
$ cat /etc/ssh/ssh_config
Host *
ForwardAgent yes
ForwardX11Trusted yes
HashKnownHosts yes
GSSAPIAuthentication no
GSSAPIDelegateCredentials no
```
After above changes, restart **ssh-agent** and do **ssh-add**.
```
$ eval $(ssh-agent)
$ ssh-add -s /usr/lib/x86_64-linux-gnu/opensc-pkcs11.so
```
I hope this should work with you all as well if you come across such issues.
Upvotes: 3 <issue_comment>username_2: I'd just like to add that I saw the same issue (in Ubuntu 18.04) and it was caused by bad permissions on my private key files. I did `chmod 600` on the relevant files and the problem was resolved. Not sure why ssh-agent didn't complain about this until today.
Upvotes: 3 <issue_comment>username_3: We only need to execute this time.
```
eval "$(ssh-agent -s)"
Ssh-add
```
That's OK.
Upvotes: 1 <issue_comment>username_4: kind of random, but make sure your network isn't blocking it. I was at a hotel and I couldn't ssh into a server. I tried connecting in through my phones hotspot and it worked immediately. Give a different network a try as a quick way to trouble shoot.
Upvotes: -1
|
2018/03/14
| 1,778 | 6,346 |
<issue_start>username_0: I'm working on an example Placeholder Image Server. This uses a single file approach, so urls, views, settings, are all in just one file called `placeholder.py`.
Each time I try visiting `http://localhost:8000` (the homepage), I get `TemplateDoesNotExist at /` thrown at me. I can't figure out what's wrong. Below is the project structure:
1. /placeholder
* placeholder.py
* /templates
+ home.html
* /static
+ style.css
Here's the content of each file:
`placeholder.py`
```
import hashlib
import os
import sys
from io import BytesIO
from PIL import Image, ImageDraw
from django.conf import settings
from django import forms
from django.urls import path, reverse
from django.core.cache import cache
from django.core.wsgi import get_wsgi_application
from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import render
from django.views.decorators.http import etag
from django.core.management import execute_from_command_line
# settings likely to change between environments
DEBUG = os.environ.get('DEBUG', 'on') == 'on'
SECRET_KEY = os.environ.get('SECRET_KEY', '<KEY>')
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost').split(',')
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# settings
settings.configure(
DEBUG=DEBUG,
SECRET_KEY=SECRET_KEY,
ALLOWED_HOSTS=ALLOWED_HOSTS,
ROOT_URLCONF=__name__,
MIDDLEWARE_CLASSES=(
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
),
INSTALLED_APPS=(
'django.contrib.staticfiles',
),
TEMPLATES=[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': os.path.join(BASE_DIR, 'templates'),
}
],
STATICFILES_DIRS=(
os.path.join(BASE_DIR, 'static'),
),
STATIC_URL='/static/',
)
# simple form to validate the height and width of an image
class ImageForm(forms.Form):
'''form to validate requested placeholder image'''
width = forms.IntegerField(min_value=1, max_value=2000)
height = forms.IntegerField(min_value=1, max_value=2000)
def generate(self, image_format='PNG'):
'''generate an image of the given type and return as raw bytes'''
width = self.cleaned_data['width']
height = self.cleaned_data['height']
key = '{}.{}.{}'.format(width, height, image_format)
content = cache.get(key)
if content is None:
image = Image.new('RGB', (width, height))
draw = ImageDraw.Draw(image)
text = '{} x {}'.format(width, height)
textwidth, textheight = draw.textsize(text)
if textwidth < width and textheight < height:
texttop = (height - textheight) // 2
textleft = (width - textwidth) // 2
draw.text((textleft, texttop), text, fill=(255, 255, 255))
content = BytesIO()
image.save(content, image_format)
content.seek(0)
cache.set(key, content, 60 * 60)
return content
# for client-side caching
def generate_etag(request, width, height):
content = 'Placeholder: {0} x {1}'.format(width, height)
return hashlib.sha1(content.encode('utf-8')).hexdigest()
# views
def index(request):
example = reverse('placeholder', kwargs={'width':50, 'height':50})
context = {
'example' : request.build_absolute_uri(example)
}
return render(request, 'home.html', context)
@etag(generate_etag) # decorator for client-side caching
def placeholder(request, width, height):
form = ImageForm({'width':width, 'height':height})
if form.is_valid():
image = form.generate()
return HttpResponse(image, content_type='image/png')
else:
return HttpResponseBadRequest('Invalid Image Request!
======================
')
# the url
urlpatterns = [
path('', index, name='homepage'),
path('image/x', placeholder, name='placeholder'),
]
# wsgi application
application = get\_wsgi\_application()
# relevant part from manage.py
if \_\_name\_\_ == "\_\_main\_\_":
execute\_from\_command\_line(sys.argv)
```
`home.html`
```
{% load static %}
Demo Placeholder Images
Demo Placeholder Images
=======================
This server can be used for serving placeholder images for any webpage.
To request a placeholder image of a given width and height simply include
an image with the source pointing to **/placeholder/<width>x
<height>/** on this server such as:
```
<img src="{{ example }}">
```
Examples
--------
* 
* 
* 
```
What's wrong?<issue_comment>username_1: I was able to get the fix for connection issue with SSH Keys. I had to make changes in SSH config files at location ***/etc/ssh/ssh\_config*** and ***~/.ssh/config***
```
$ cat ~/.ssh/config
Host *
Compression yes
ForwardAgent yes
ForwardX11Trusted no
GSSAPIAuthentication no
PreferredAuthentications=publickey
```
and
```
$ cat /etc/ssh/ssh_config
Host *
ForwardAgent yes
ForwardX11Trusted yes
HashKnownHosts yes
GSSAPIAuthentication no
GSSAPIDelegateCredentials no
```
After above changes, restart **ssh-agent** and do **ssh-add**.
```
$ eval $(ssh-agent)
$ ssh-add -s /usr/lib/x86_64-linux-gnu/opensc-pkcs11.so
```
I hope this should work with you all as well if you come across such issues.
Upvotes: 3 <issue_comment>username_2: I'd just like to add that I saw the same issue (in Ubuntu 18.04) and it was caused by bad permissions on my private key files. I did `chmod 600` on the relevant files and the problem was resolved. Not sure why ssh-agent didn't complain about this until today.
Upvotes: 3 <issue_comment>username_3: We only need to execute this time.
```
eval "$(ssh-agent -s)"
Ssh-add
```
That's OK.
Upvotes: 1 <issue_comment>username_4: kind of random, but make sure your network isn't blocking it. I was at a hotel and I couldn't ssh into a server. I tried connecting in through my phones hotspot and it worked immediately. Give a different network a try as a quick way to trouble shoot.
Upvotes: -1
|
2018/03/14
| 1,339 | 5,578 |
<issue_start>username_0: I've been trying to figure out what the best practice is for form submission with spring and what the minimum boilerplate is to achieve that.
I think of the following as best practise traits
* Validation enabled and form values preserved on validation failure
* Disable form re-submission `F5` (i.e. use redirects)
* Prevent the model values to appear in the URL between redirects (`model.clear()`)
So far I've come up with this.
```
@Controller
@RequestMapping("/")
public class MyModelController {
@ModelAttribute("myModel")
public MyModel myModel() {
return new MyModel();
}
@GetMapping
public String showPage() {
return "thepage";
}
@PostMapping
public String doAction(
@Valid @ModelAttribute("myModel") MyModel myModel,
BindingResult bindingResult,
Map model,
RedirectAttributes redirectAttrs) throws Exception {
model.clear();
if (bindingResult.hasErrors()) {
redirectAttrs.addFlashAttribute("org.springframework.validation.BindingResult.myModel", bindingResult);
redirectAttrs.addFlashAttribute("myModel", myModel);
} else {
// service logic
}
return "redirect:/thepage";
}
}
```
Is there a way to do this with **less** boilerplate code or is this the least amount of code required to achieve this?<issue_comment>username_1: One possible way is to use Archetype for Web forms, Instead of creating simple project, you can choose to create project from existing archetype of web forms. It will provide you with sufficient broiler plate code. You can also make your own archetype.
Have a look at this link to get deeper insight into archetypes.
[Link To Archetypes in Java Spring](https://maven.apache.org/guides/mini/guide-creating-archetypes.html)
Upvotes: 1 <issue_comment>username_2: First, I wouldn't violate the [Post/Redirect/Get (PRG)](https://en.wikipedia.org/wiki/Post/Redirect/Get) pattern, meaning I would only redirect if the form is posted successfully.
Second, I would get rid of the `BindingResult` style altogether. It is fine for simple cases, but once you need more complex notifications to reach the user from service/domain/business logic, things get hairy. Also, your services are not much reusable.
What I would do is pass the bound DTO directly to the service, which would validate the DTO and put a notification in case of errors/warning. This way you can combine business logic validation with *JSR 303: Bean Validation*.
For that, you can use the [Notification Pattern](https://martinfowler.com/eaaDev/Notification.html) in the service.
Following the Notification Pattern, you would need a generic notification wrapper:
```
public class Notification {
private List errors = new ArrayList<>();
private T model; // model for which the notifications apply
public Notification pushError(String message) {
this.errors.add(message);
return this;
}
public boolean hasErrors() {
return !this.errors.isEmpty();
}
public void clearErrors() {
this.errors.clear();
}
public String getFirstError() {
if (!hasErrors()) {
return "";
}
return errors.get(0);
}
public List getAllErrors() {
return this.errors;
}
public T getModel() {
return model;
}
public void setModel(T model) {
this.model = model;
}
}
```
Your service would be something like:
```
public Notification addMyModel(MyModelDTO myModelDTO){
Notification notification = new Notification();
//if(JSR 303 bean validation errors) -> notification.pushError(...); return notification;
//if(business logic violations) -> notification.pushError(...); return notification;
return notification;
}
```
And then your controller would be something like:
```
Notification addAction = service.addMyModel(myModelDTO);
if (addAction.hasErrors()) {
model.addAttribute("myModel", addAction.getModel());
model.addAttribute("notifications", addAction.getAllErrors());
return "myModelView"; // no redirect if errors
}
redirectAttrs.addFlashAttribute("success", "My Model was added successfully");
return "redirect:/thepage";
```
Although the `hasErrors()` check is still there, this solution is more extensible as your service can continue evolving with new business rules notifications.
**Another approach** which I will keep very short, is to throw a custom `RuntimeException` from your services, this custom `RuntimeException` can contain the necessary messages/models, and use `@ControllerAdvice` to catch this generic exception, extract the models and messages from the exception and put them in the model. This way, your controller does nothing but forward the bound DTO to service.
Upvotes: 3 [selected_answer]<issue_comment>username_3: Based on the answer by [@username_2](https://stackoverflow.com/a/49366598/42962), if redirect happens only after successful validation the code can be simplified to this:
```
@Controller
@RequestMapping("/")
public class MyModelController {
@ModelAttribute("myModel")
public MyModel myModel() {
return new MyModel();
}
@GetMapping
public String showPage() {
return "thepage";
}
@PostMapping
public String doAction(
@Valid @ModelAttribute("myModel") MyModel myModel,
BindingResult bindingResult,
RedirectAttributes redirectAttrs) throws Exception {
if (bindingResult.hasErrors()) {
return "thepage";
}
// service logic
redirectAttrs.addFlashAttribute("success", "My Model was added successfully");
return "redirect:/thepage";
}
}
```
Upvotes: 2
|
2018/03/14
| 1,327 | 5,257 |
<issue_start>username_0: I am not able to run `bundle update devise` or `bundle install`
`$ bundle update devise`
```
Fetching gem metadata from http://rubygems.org/.............
Fetching gem metadata from http://rubygems.org/..
Resolving dependencies............
Fetching rake 12.3.0 (was 10.1.0)
Installing rake 12.3.0 (was 10.1.0)
Gem::RuntimeRequirementNotMetError: rake requires Ruby version >= 2.0.0. The current ruby version is 1.9.1.
An error occurred while installing rake (12.3.0), and Bundler cannot continue.
Make sure that `gem install rake -v '12.3.0'` succeeds before bundling.
```
and this is what I am getting on `$ bundle install`
```
Fetching gem metadata from http://rubygems.org/.............
Fetching gem metadata from http://rubygems.org/..
You have requested:
devise = 2.2.4
The bundle currently has devise locked at 3.1.0.
Try running `bundle update devise`
If you are updating multiple gems in your Gemfile at once,
try passing them all to `bundle update`
```
Thanks in advance<issue_comment>username_1: One possible way is to use Archetype for Web forms, Instead of creating simple project, you can choose to create project from existing archetype of web forms. It will provide you with sufficient broiler plate code. You can also make your own archetype.
Have a look at this link to get deeper insight into archetypes.
[Link To Archetypes in Java Spring](https://maven.apache.org/guides/mini/guide-creating-archetypes.html)
Upvotes: 1 <issue_comment>username_2: First, I wouldn't violate the [Post/Redirect/Get (PRG)](https://en.wikipedia.org/wiki/Post/Redirect/Get) pattern, meaning I would only redirect if the form is posted successfully.
Second, I would get rid of the `BindingResult` style altogether. It is fine for simple cases, but once you need more complex notifications to reach the user from service/domain/business logic, things get hairy. Also, your services are not much reusable.
What I would do is pass the bound DTO directly to the service, which would validate the DTO and put a notification in case of errors/warning. This way you can combine business logic validation with *JSR 303: Bean Validation*.
For that, you can use the [Notification Pattern](https://martinfowler.com/eaaDev/Notification.html) in the service.
Following the Notification Pattern, you would need a generic notification wrapper:
```
public class Notification {
private List errors = new ArrayList<>();
private T model; // model for which the notifications apply
public Notification pushError(String message) {
this.errors.add(message);
return this;
}
public boolean hasErrors() {
return !this.errors.isEmpty();
}
public void clearErrors() {
this.errors.clear();
}
public String getFirstError() {
if (!hasErrors()) {
return "";
}
return errors.get(0);
}
public List getAllErrors() {
return this.errors;
}
public T getModel() {
return model;
}
public void setModel(T model) {
this.model = model;
}
}
```
Your service would be something like:
```
public Notification addMyModel(MyModelDTO myModelDTO){
Notification notification = new Notification();
//if(JSR 303 bean validation errors) -> notification.pushError(...); return notification;
//if(business logic violations) -> notification.pushError(...); return notification;
return notification;
}
```
And then your controller would be something like:
```
Notification addAction = service.addMyModel(myModelDTO);
if (addAction.hasErrors()) {
model.addAttribute("myModel", addAction.getModel());
model.addAttribute("notifications", addAction.getAllErrors());
return "myModelView"; // no redirect if errors
}
redirectAttrs.addFlashAttribute("success", "My Model was added successfully");
return "redirect:/thepage";
```
Although the `hasErrors()` check is still there, this solution is more extensible as your service can continue evolving with new business rules notifications.
**Another approach** which I will keep very short, is to throw a custom `RuntimeException` from your services, this custom `RuntimeException` can contain the necessary messages/models, and use `@ControllerAdvice` to catch this generic exception, extract the models and messages from the exception and put them in the model. This way, your controller does nothing but forward the bound DTO to service.
Upvotes: 3 [selected_answer]<issue_comment>username_3: Based on the answer by [@username_2](https://stackoverflow.com/a/49366598/42962), if redirect happens only after successful validation the code can be simplified to this:
```
@Controller
@RequestMapping("/")
public class MyModelController {
@ModelAttribute("myModel")
public MyModel myModel() {
return new MyModel();
}
@GetMapping
public String showPage() {
return "thepage";
}
@PostMapping
public String doAction(
@Valid @ModelAttribute("myModel") MyModel myModel,
BindingResult bindingResult,
RedirectAttributes redirectAttrs) throws Exception {
if (bindingResult.hasErrors()) {
return "thepage";
}
// service logic
redirectAttrs.addFlashAttribute("success", "My Model was added successfully");
return "redirect:/thepage";
}
}
```
Upvotes: 2
|
2018/03/14
| 998 | 3,403 |
<issue_start>username_0: Feels like I'm missing something obvious here - but I can't figure out how to access my JSON data. I have a Container component:
```
class About extends Component {
componentDidMount(){
const APP_URL = 'http://localhost/wordpress/'
const PAGES_URL = `${APP_URL}/wp-json/wp/v2/pages`
this.props.fetchAllPages(PAGES_URL, 'about')
}
render(){
return (
AAAAABBBBBOOOOUUUUUT
====================
)
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({ fetchAllPages }, dispatch)
}
export default connect(null, mapDispatchToProps)(About);
```
And a Smart component:
```
class AboutInfo extends Component {
render(){
console.log(this.props.page);
console.log(this.props.page.id);
return (
This is ID: {this.props.page.id}
================================
)
}
}
const mapStateToProps = ({ page }) => {
return { page }
}
export default connect(mapStateToProps)(AboutInfo);
```
My action:
```
export const fetchAllPages = (URL, SLUG) => {
var URLEN;
if(!SLUG){
URLEN = URL
} else {
URLEN = URL + "?slug=" + SLUG
}
return (dispatch) => {
dispatch(fetchRequest());
return fetchPosts(URLEN).then(([response, json]) => {
if(response.status === 200){
if(!SLUG) {
dispatch(fetchPagesSuccess(json))
} else {
dispatch(fetchPageBySlugSuccess(json))
}
} else {
dispatch(fetchError())
}
})
}
}
const fetchPageBySlugSuccess = (payload) => {
return {
type: types.FETCH_PAGE_BY_SLUG,
payload
}
}
```
My reducer:
```
const page = (state = {}, action) => {
switch (action.type) {
case FETCH_PAGE_BY_SLUG:
console.log(action.paylod)
return action.payload
default:
return state
}
}
```
This gives me:
[](https://i.stack.imgur.com/dNh5Q.png)
When I console.log(this.props.page) in my AboutInfo component, it prints the object, but when I print console.log(this.props.page.id) it gives me **undefined**. Why can't I print the JSON content? Thanks!<issue_comment>username_1: That is because `page` is an array and the `id` is a property of its 1st element.
So use `this.props.page[0].id`
If the logged object in your screenshot is the `this.props.page` then you will need and additional `.page` as that is also a part of the object `this.props.page.page[0].id`
Upvotes: 0 <issue_comment>username_2: Getting data from the store is async So you must adding loading varibale on your reducer
```
class AboutInfo extends Component {
render(){
if(this.props.loading) return (loading);
return (
This is ID: {this.props.page.id}
================================
);
}
}
const mapStateToProps = ({ page, loading }) => {
return { page, loading }
}
```
on your action try returing
```
json.page[0]
```
Upvotes: 1 <issue_comment>username_3: **page is an array** and hence `this.props.page.id` is `undefined`. You might want to access the first element in array in which case you would do
```
this.props.page[0].id
```
but you might also need to add a test, since before the response is available you will be trying to access `page[0].id` and it might break.
You could instead write
```
this.props.page && this.props.page[0] && this.props.page[0].id
```
Upvotes: 3 [selected_answer]
|