Further hint: If you don't need those information you can change the Table Type to "Blackhole" (instead of InnoDB). This means, nothing will be stored in the future and the insert statements are still working fine.
You can also disable the logs by setting all events to disabled:
yes, %c
will print a single char:
printf("%c", 'h');
also, putchar
/putc
will work too. From "man putchar":
#include <stdio.h>
int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c);
* fputc() writes the character c, cast to an unsigned char, to stream.
* putc() is equivalent to fputc() except that it may be implemented as a macro which evaluates stream more than once.
* putchar(c); is equivalent to putc(c,stdout).
EDIT:
Also note, that if you have a string, to output a single char, you need get the character in the string that you want to output. For example:
const char *h = "hello world";
printf("%c\n", h[4]); /* outputs an 'o' character */
here $key will contain the $key associated with $value in $featured. The difference is that now you have that key.
array("thekey"=>array("name"=>"joe"))
here $value is
array("name"=>"joe")
$key is "thekey"
You can also try this, after injecting $window service.
$window.location.reload();
Fixed by adding crossorigin to the script tag.
From: https://code.jquery.com/
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source. Read more at srihash.org
Dictionaries are specifically designed to do super fast key lookups. They are implemented as hashtables and the more entries the faster they are relative to other methods. Using the exception engine is only supposed to be done when your method has failed to do what you designed it to do because it is a large set of object that give you a lot of functionality for handling errors. I built an entire library class once with everything surrounded by try catch blocks once and was appalled to see the debug output which contained a seperate line for every single one of over 600 exceptions!
Another similar method to those described above is to use plt.ylim
for example:
plt.ylim(max(y_array), min(y_array))
This method works for me when I'm attempting to compound multiple datasets on Y1 and/or Y2
With bootstrap3-typeahead, I made it to work with the following code:
<input id="typeahead-input" type="text" data-provide="typeahead" />
<script type="text/javascript">
jQuery(document).ready(function() {
$('#typeahead-input').typeahead({
source: function (query, process) {
return $.get('search?q=' + query, function (data) {
return process(data.search_results);
});
}
});
})
</script>
The backend provides search service under the search
GET endpoint, receiving the query in the q
parameter, and returns a JSON in the format { 'search_results': ['resultA', 'resultB', ... ] }
. The elements of the search_results
array are displayed in the typeahead input.
If I want the sort to be applied to only one of the UNION if use Union all:
Select id,name,age
From Student
Where age < 15
Union all
Select id,name,age
From
(
Select id,name,age
From Student
Where Name like "%a%"
Order by name
)
I solved the problem (How to connect multiple database using spring and Hibernate) in this way, I hope it will help :)
NOTE: I have added the relevant code, kindly make the dao with the help of impl I used in the below mentioned code.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>MultipleDatabaseConnectivityInSpring</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/dispatcher-servlet.xml
</param-value>
</context-param>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="localPersistenceUnitOne"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>in.india.entities.CustomerDetails</class>
<exclude-unlisted-classes />
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
<property name="hibernate.jdbc.batch_size" value="0" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/shankar?sslmode=require" />
<property name="hibernate.connection.username" value="username" />
<property name="hibernate.connection.password" value="password" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
<persistence-unit name="localPersistenceUnitTwo"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>in.india.entities.CompanyDetails</class>
<exclude-unlisted-classes />
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
<property name="hibernate.jdbc.batch_size" value="0" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/shankarTwo?sslmode=require" />
<property name="hibernate.connection.username" value="username" />
<property name="hibernate.connection.password" value="password" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
dispatcher-servlet
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task" xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
default-autowire="byName"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Configure messageSource -->
<mvc:annotation-driven />
<context:component-scan base-package="in.india.*" />
<bean id="messageResource"
class="org.springframework.context.support.ResourceBundleMessageSource"
autowire="byName">
<property name="basename" value="messageResource"></property>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="entityManagerFactoryOne"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
autowire="constructor">
<property name="persistenceUnitName" value="localPersistenceUnitOne" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
autowire="byName">
<property name="basename" value="messageResource" />
</bean>
<bean id="entityManagerFactoryTwo"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
autowire="constructor">
<property name="persistenceUnitName" value="localPersistenceUnitTwo" />
</bean>
<bean id="manager1" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryOne" />
</bean>
<bean id="manager2" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryTwo" />
</bean>
<tx:annotation-driven transaction-manager="manager1" />
<tx:annotation-driven transaction-manager="manager2" />
<!-- declare dependies here -->
<bean class="in.india.service.dao.impl.CustomerServiceImpl" />
<bean class="in.india.service.dao.impl.CompanyServiceImpl" />
<!-- Configure MVC annotations -->
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
</beans>
java class to persist into one database
package in.india.service.dao.impl;
import in.india.entities.CompanyDetails;
import in.india.service.CompanyService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;
public class CompanyServiceImpl implements CompanyService {
@PersistenceContext(unitName = "entityManagerFactoryTwo")
EntityManager entityManager;
@Transactional("manager2")
@Override
public boolean companyService(CompanyDetails companyDetails) {
boolean flag = false;
try
{
entityManager.persist(companyDetails);
flag = true;
}
catch (Exception e)
{
flag = false;
}
return flag;
}
}
java class to persist in another database
package in.india.service.dao.impl;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;
import in.india.entities.CustomerDetails;
import in.india.service.CustomerService;
public class CustomerServiceImpl implements CustomerService {
@PersistenceContext(unitName = "localPersistenceUnitOne")
EntityManager entityManager;
@Override
@Transactional(value = "manager1")
public boolean customerService(CustomerDetails companyData) {
boolean flag = false;
entityManager.persist(companyData);
return flag;
}
}
customer.jsp
<%@page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<h1>SpringWithMultipleDatabase's</h1>
</center>
<form:form method="GET" action="addCustomer.htm" modelAttribute="customerBean" >
<table>
<tr>
<td><form:label path="firstName">First Name</form:label></td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td><form:label path="lastName">Last Name</form:label></td>
<td><form:input path="lastName" /></td>
</tr>
<tr>
<td><form:label path="emailId">Email Id</form:label></td>
<td><form:input path="emailId" /></td>
</tr>
<tr>
<td><form:label path="profession">Profession</form:label></td>
<td><form:input path="profession" /></td>
</tr>
<tr>
<td><form:label path="address">Address</form:label></td>
<td><form:input path="address" /></td>
</tr>
<tr>
<td><form:label path="age">Age</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
</body>
</html>
company.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>ScheduleJobs</title>
</head>
<body>
<center><h1>SpringWithMultipleDatabase's</h1></center>
<form:form method="GET" action="addCompany.htm" modelAttribute="companyBean" >
<table>
<tr>
<td><form:label path="companyName">Company Name</form:label></td>
<td><form:input path="companyName" /></td>
</tr>
<tr>
<td><form:label path="companyStrength">Company Strength</form:label></td>
<td><form:input path="companyStrength" /></td>
</tr>
<tr>
<td><form:label path="companyLocation">Company Location</form:label></td>
<td><form:input path="companyLocation" /></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home</title>
</head>
<body>
<center><h1>Multiple Database Connectivity In Spring sdfsdsd</h1></center>
<a href='customerRequest.htm'>Click here to go on Customer page</a>
<br>
<a href='companyRequest.htm'>Click here to go on Company page</a>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>ScheduleJobs</title>
</head>
<body>
<center><h1>SpringWithMultipleDatabase</h1></center>
<b>Successfully Saved</b>
</body>
</html>
CompanyController
package in.india.controller;
import in.india.bean.CompanyBean;
import in.india.entities.CompanyDetails;
import in.india.service.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class CompanyController {
@Autowired
CompanyService companyService;
@RequestMapping(value = "/companyRequest.htm", method = RequestMethod.GET)
public ModelAndView addStudent(ModelMap model) {
CompanyBean companyBean = new CompanyBean();
model.addAttribute(companyBean);
return new ModelAndView("company");
}
@RequestMapping(value = "/addCompany.htm", method = RequestMethod.GET)
public ModelAndView companyController(@ModelAttribute("companyBean") CompanyBean companyBean, Model model) {
CompanyDetails companyDetails = new CompanyDetails();
companyDetails.setCompanyLocation(companyBean.getCompanyLocation());
companyDetails.setCompanyName(companyBean.getCompanyName());
companyDetails.setCompanyStrength(companyBean.getCompanyStrength());
companyService.companyService(companyDetails);
return new ModelAndView("success");
}
}
CustomerController
package in.india.controller;
import in.india.bean.CustomerBean;
import in.india.entities.CustomerDetails;
import in.india.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class CustomerController {
@Autowired
CustomerService customerService;
@RequestMapping(value = "/customerRequest.htm", method = RequestMethod.GET)
public ModelAndView addStudent(ModelMap model) {
CustomerBean customerBean = new CustomerBean();
model.addAttribute(customerBean);
return new ModelAndView("customer");
}
@RequestMapping(value = "/addCustomer.htm", method = RequestMethod.GET)
public ModelAndView customerController(@ModelAttribute("customerBean") CustomerBean customer, Model model) {
CustomerDetails customerDetails = new CustomerDetails();
customerDetails.setAddress(customer.getAddress());
customerDetails.setAge(customer.getAge());
customerDetails.setEmailId(customer.getEmailId());
customerDetails.setFirstName(customer.getFirstName());
customerDetails.setLastName(customer.getLastName());
customerDetails.setProfession(customer.getProfession());
customerService.customerService(customerDetails);
return new ModelAndView("success");
}
}
CompanyDetails Entity
package in.india.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "company_details")
public class CompanyDetails {
@Id
@SequenceGenerator(name = "company_details_seq", sequenceName = "company_details_seq", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "company_details_seq")
@Column(name = "company_details_id")
private Long companyDetailsId;
@Column(name = "company_name")
private String companyName;
@Column(name = "company_strength")
private Long companyStrength;
@Column(name = "company_location")
private String companyLocation;
public Long getCompanyDetailsId() {
return companyDetailsId;
}
public void setCompanyDetailsId(Long companyDetailsId) {
this.companyDetailsId = companyDetailsId;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public Long getCompanyStrength() {
return companyStrength;
}
public void setCompanyStrength(Long companyStrength) {
this.companyStrength = companyStrength;
}
public String getCompanyLocation() {
return companyLocation;
}
public void setCompanyLocation(String companyLocation) {
this.companyLocation = companyLocation;
}
}
CustomerDetails Entity
package in.india.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "customer_details")
public class CustomerDetails {
@Id
@SequenceGenerator(name = "customer_details_seq", sequenceName = "customer_details_seq", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customer_details_seq")
@Column(name = "customer_details_id")
private Long customerDetailsId;
@Column(name = "first_name ")
private String firstName;
@Column(name = "last_name ")
private String lastName;
@Column(name = "email_id")
private String emailId;
@Column(name = "profession")
private String profession;
@Column(name = "address")
private String address;
@Column(name = "age")
private int age;
public Long getCustomerDetailsId() {
return customerDetailsId;
}
public void setCustomerDetailsId(Long customerDetailsId) {
this.customerDetailsId = customerDetailsId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
You can try using one of their tools: http://www.ws-i.org/deliverables/workinggroup.aspx?wg=testingtools
These will check both WSDL validity and Basic Profile 1.1 compliance.
You can apply styles and Themes in Overflow MenuItem as per below. OverFlow Menu is ListView so, we can apply theme as per listview.
Apply below code in styles.xml
<style name="AppTheme" parent="@android:style/Theme.Holo.Light">
<item name="android:dropDownListViewStyle">@style/PopupMenuListView</item>
<item name="android:actionBarWidgetTheme">@style/PopupMenuTextView</item>
<item name="android:popupMenuStyle">@style/PopupMenu</item>
<item name="android:listPreferredItemHeightSmall">40dp</item>
</style>
<!-- Change Overflow Menu ListView Divider Property -->
<style name="PopupMenuListView" parent="@android:style/Widget.Holo.ListView.DropDown">
<item name="android:divider">@color/app_navigation_divider</item>
<item name="android:dividerHeight">1sp</item>
<item name="android:listSelector">@drawable/list_selector</item>
</style>
<!-- Change Overflow Menu ListView Text Size and Text Size -->
<style name="PopupMenuTextView" parent="@android:style/Widget.Holo.Light.TextView">
<item name="android:textColor">@color/app_white</item>
<item name="android:textStyle">normal</item>
<item name="android:textSize">18sp</item>
<item name="android:drawablePadding">25dp</item>
<item name="android:drawableRight">@drawable/navigation_arrow_selector</item>
</style>
<!-- Change Overflow Menu Background -->
<style name="PopupMenu" parent="android:Widget.Holo.Light.ListPopupWindow">
<item name="android:popupBackground">@drawable/menu_overflow_bg</item>
</style>
For example,
package main
import (
"fmt"
"strings"
)
func main() {
s := "\t Hello, World\n "
fmt.Printf("%d %q\n", len(s), s)
t := strings.TrimSpace(s)
fmt.Printf("%d %q\n", len(t), t)
}
Output:
16 "\t Hello, World\n "
12 "Hello, World"
I'll add a bit hint: it seems what you pass as the key value of a header depends on your authorization type, in my case that was PRIVATE-TOKEN
header = {'PRIVATE-TOKEN': 'my_token'}
response = requests.get(myUrl, headers=header)
Note: Using Android Support Library v22.1.0 and targeting API level 11 and up? Scroll down to the last update.
My application style is set to Theme.Holo which is dark and I would like the check boxes on my list view to be of style Theme.Holo.Light. I am not trying to create a custom style. The code below doesn't seem to work, nothing happens at all.
At first it may not be apparent why the system exhibits this behaviour, but when you actually look into the mechanics you can easily deduce it. Let me take you through it step by step.
First, let's take a look what the Widget.Holo.Light.CompoundButton.CheckBox
style defines. To make things more clear, I've also added the 'regular' (non-light) style definition.
<style name="Widget.Holo.Light.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />
<style name="Widget.Holo.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />
As you can see, both are empty declarations that simply wrap Widget.CompoundButton.CheckBox
in a different name. So let's look at that parent style.
<style name="Widget.CompoundButton.CheckBox">
<item name="android:background">@android:drawable/btn_check_label_background</item>
<item name="android:button">?android:attr/listChoiceIndicatorMultiple</item>
</style>
This style references both a background and button drawable. btn_check_label_background
is simply a 9-patch and hence not very interesting with respect to this matter. However, ?android:attr/listChoiceIndicatorMultiple
indicates that some attribute based on the current theme (this is important to realise) will determine the actual look of the CheckBox
.
As listChoiceIndicatorMultiple
is a theme attribute, you will find multiple declarations for it - one for each theme (or none if it gets inherited from a parent theme). This will look as follows (with other attributes omitted for clarity):
<style name="Theme">
<item name="listChoiceIndicatorMultiple">@android:drawable/btn_check</item>
...
</style>
<style name="Theme.Holo">
<item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_dark</item>
...
</style>
<style name="Theme.Holo.Light" parent="Theme.Light">
<item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_light</item>
...
</style>
So this where the real magic happens: based on the theme's listChoiceIndicatorMultiple
attribute, the actual appearance of the CheckBox
is determined. The phenomenon you're seeing is now easily explained: since the appearance is theme-based (and not style-based, because that is merely an empty definition) and you're inheriting from Theme.Holo
, you will always get the CheckBox
appearance matching the theme.
Now, if you want to change your CheckBox
's appearance to the Holo.Light version, you will need to take a copy of those resources, add them to your local assets and use a custom style to apply them.
As for your second question:
Also can you set styles to individual widgets if you set a style to the application?
Absolutely, and they will override any activity- or application-set styles.
Is there any way to set a theme(style with images) to the checkbox widget. (...) Is there anyway to use this selector: link?
Update:
Let me start with saying again that you're not supposed to rely on Android's internal resources. There's a reason you can't just access the internal namespace as you please.
However, a way to access system resources after all is by doing an id lookup by name. Consider the following code snippet:
int id = Resources.getSystem().getIdentifier("btn_check_holo_light", "drawable", "android");
((CheckBox) findViewById(R.id.checkbox)).setButtonDrawable(id);
The first line will actually return the resource id of the btn_check_holo_light
drawable resource. Since we established earlier that this is the button selector that determines the look of the CheckBox
, we can set it as 'button drawable' on the widget. The result is a CheckBox
with the appearance of the Holo.Light
version, no matter what theme/style you set on the application, activity or widget in xml. Since this sets only the button drawable, you will need to manually change other styling; e.g. with respect to the text appearance.
Below a screenshot showing the result. The top checkbox uses the method described above (I manually set the text colour to black in xml), while the second uses the default theme-based Holo
styling (non-light, that is).
Update2:
With the introduction of Support Library v22.1.0, things have just gotten a lot easier! A quote from the release notes (my emphasis):
Lollipop added the ability to overwrite the theme at a view by view level by using the
android:theme
XML attribute - incredibly useful for things such as dark action bars on light activities. Now, AppCompat allows you to useandroid:theme
for Toolbars (deprecating theapp:theme
used previously) and, even better, bringsandroid:theme
support to all views on API 11+ devices.
In other words: you can now apply a theme on a per-view basis, which makes solving the original problem a lot easier: just specify the theme you'd like to apply for the relevant view. I.e. in the context of the original question, compare the results of below:
<CheckBox
...
android:theme="@android:style/Theme.Holo" />
<CheckBox
...
android:theme="@android:style/Theme.Holo.Light" />
The first CheckBox
is styled as if used in a dark theme, the second as if in a light theme, regardless of the actual theme set to your activity or application.
Of course you should no longer be using the Holo theme, but instead use Material.
I had the error too.
Turn out that my zip file include the code parent folder. When I unzip
and inspect the zip file, the lambda_function
file is under parent folder ./lambda
.
Use the zip
command, fix the error:
zip -r ../lambda.zip ./*
Turns out for me this error was actually telling the truth - I was trying to resize a Null image, which was usually the 'last' frame of a video file, so the assertion was valid.
Now I have an extra step before attempting the resize operation, which is to do the assertion myself:
def getSizedFrame(width, height):
"""Function to return an image with the size I want"""
s, img = self.cam.read()
# Only process valid image frames
if s:
img = cv2.resize(img, (width, height), interpolation = cv2.INTER_AREA)
return s, img
Now I don't see the error.
For references and the future, one should read the doc here https://dev.mysql.com/doc/mysql-secure-deployment-guide/5.7/en/secure-deployment-password-validation.html
Then you should edit your mysqld.cnf
file, for instance :
vim /etc/mysql/mysql.conf.d/mysqld.cnf
Then, add in the [mysqld] part, the following :
plugin-load-add=validate_password.so
validate_password_policy=LOW
Basically, if you edit your default, it will looks like :
[mysqld]
#
# * Basic Settings
#
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
plugin-load-add=validate_password.so
validate_password_policy=LOW
Then, you can restart:
systemctl restart mysql
If you forget the plugin-load-add=validate_password.so
part, you will it an error at restart.
Enjoy !
var duplicates = lst.GroupBy(s => s)
.SelectMany(grp => grp.Skip(1));
Note that this will return all duplicates, so if you only want to know which items are duplicated in the source list, you could apply Distinct
to the resulting sequence or use the solution given by Mark Byers.
Try this out
/**
* Checks the string if undefined, null, not typeof string, empty or space(s)
* @param {any} str string to be evaluated
* @returns {boolean} the evaluated result
*/
function isStringNullOrWhiteSpace(str) {
return str === undefined || str === null
|| typeof str !== 'string'
|| str.match(/^ *$/) !== null;
}
You can use it like this
isStringNullOrWhiteSpace('Your String');
If you want the 'active' in the html:
header with html and php:
<?php
$menu_items = wp_get_nav_menu_items( 'main_nav' ); // id or name of menu
foreach ( (array) $menu_items as $key => $menu_item ) {
if ( ! $menu_item->menu_item_parent ) {
echo "<li class=" . vince_check_active_menu($menu_item) . "><a href='$menu_item->url'>";
echo $menu_item->title;
echo "</a></li>";
}
}
?>
functions.php:
function vince_check_active_menu( $menu_item ) {
$actual_link = ( isset( $_SERVER['HTTPS'] ) ? "https" : "http" ) . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if ( $actual_link == $menu_item->url ) {
return 'active';
}
return '';
}
I had problems with this following:
on Android Studio version: 3.3.2
until I killed the .idea/workspace.xml file.
$ cp -rv Testcopysource/ TestCopyDest
$ rm TestCopyDest/.idea/workspace.xml
$ stdio.sh & # Run Android Studio on Linux
Prior to doing that Android Studio would still point to the original source folder and all renames were applied to the original source files (within Testcopysource in my example above).
output = new ByteArrayOutputStream();
...
input = new ByteArrayInputStream( output.toByteArray() )
This is the way it worked for me:
$.post("/Controller/Action", $("#form").serialize(), function(json) {
// handle response
}, "json");
[HttpPost]
public ActionResult TV(MyModel id)
{
return Json(new { success = true });
}
I know this is an old thread, but if you prefer case-insensitive searching:
SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE Lower(TABLE_NAME) LIKE Lower('%%')
Take a look there : http://developer.android.com/guide/topics/intents/intents-filters.html
DO you have update your manifest file in order to give call rights ?
public class Test {
public static void main(String args[]) {
String s = "pre/fix/dir1/dir2/dir3/dir4/..";
String prefix = "pre/fix";
String[] tokens = s.substring(prefix.length()).split("/");
for (int i=0; i<tokens.length; i++) {
System.out.println(tokens[i]);
}
}
}
This was not as straightforward as I would have hoped. You need to use enumerate to keep track of how many columns you have. Then use that counter to look up the name of the column. The accepted answer does not show you how to access the column names dynamically.
for row in df.itertuples(index=False, name=None):
for k,v in enumerate(row):
print("column: {0}".format(df.columns.values[k]))
print("value: {0}".format(v)
There are many ways of doing this (and I encourage you to look them up as they will be more efficient generally) but the simplest way of doing this is to use a non-set operation to define the value of the third column:
SELECT
t1.previous
,t1.present
,(t1.present - t1.previous) as difference
FROM #TEMP1 t1
Note, this style of selection is considered bad practice because it requires the query plan to reselect the value of the first two columns to logically determine the third (a violation of set theory that SQL is based on). Though it is more complicated, if you plan on using this to evaluate more than the values you listed in your example, I would investigate using an APPLY clause. http://technet.microsoft.com/en-us/library/ms175156(v=sql.105).aspx
What you are currently doing is checking whether neither the start_date nor the end_date fall within the range of the dates given.
I guess what you are really looking for is a record which does not fit in the date range given. If so, use the query below.
SELECT *
FROM `test_table`
WHERE CAST('2009-12-15' AS DATE) > start_date AND CAST('2010-01-02' AS DATE) < end_date
Very simple , using Alt fragment
Lets take an example of sequence diagram for an ATM machine.Let's say here you want
IF card inserted is valid then prompt "Enter Pin"....ELSE prompt "Invalid Pin"
Then here is the sequence diagram for the same
Hope this helps!
That's exactly why the "fuser -m /mount/point" exists.
BTW, I don't think "fuser" or "lsof" will indicate when a resource is held by kernel module, although I don't usually have that issue..
You might sort the helper[]
array directly:
java.util.Arrays.sort(helper, 1, helper.length);
Sorts the array from index 1 to the end. Leaves the first item at index 0 untouched.
A common cause is cloning using the default (HTTPS) instead of SSH. You can correct this by going to your repository, clicking "Clone or download", then clicking the "Use SSH" button above the URL field and updating the URL of your origin remote like this:
git remote set-url origin [email protected]:username/repo.git
This is documented at GitHub: Switching remote URLs from HTTPS to SSH.
My IDE is NetBeans. I put log4j.property file as shown in the pictures
Root
Web
WEB-INF
To use this property file you should to write this code:
package example;
import java.io.File;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Logger;
import javax.servlet.*;
public class test {
public static ServletContext context;
static Logger log = Logger.getLogger("example/test");
public test() {
String homeDir = context.getRealPath("/");
File propertiesFile = new File(homeDir, "WEB-INF/log4j.properties");
PropertyConfigurator.configure(propertiesFile.toString());
log.info("This is a test");
}
}
You can define static ServletContext context from another JSP file. Example:
test.context = getServletContext();
test sample = new test();
Now you can use log4j.property file in your projects.
The other already explained to you that the syntax that you observe is called "constructor initializer list". This syntax lets you to custom-initialize base subobjects and member subobjects of the class (as opposed to allowing them to default-initialize or to remain uninitialized).
I just want to note that the syntax that, as you said, "looks like a constructor call", is not necessarily a constructor call. In C++ language the ()
syntax is just one standard form of initialization syntax. It is interpreted differently for different types. For class types with user-defined constructor it means one thing (it is indeed a constructor call), for class types without user-defined constructor it means another thing (so called value initialization ) for empty ()
) and for non-class types it again means something different (since non-class types have no constructors).
In your case the data member has type int
. int
is not a class type, so it has no constructor. For type int
this syntax means simply "initialize bar
with the value of num
" and that's it. It is done just like that, directly, no constructors involved, since, once again, int
is not a class type of therefore it can't have any constructors.
/*$mpdf = new mPDF('', // mode - default ''
'', // format - A4, for example, default ''
0, // font size - default 0
'', // default font family
15, // margin_left
15, // margin right
16, // margin top
16, // margin bottom
9, // margin header
9, // margin footer
'L'); // L - landscape, P - portrait*/
String logStringVal= date+"";
Can convert the long into string object, cool shortcut for converting into string...but use of String.valueOf(date);
is advisable
I figured out what's the problem - it is with orientation changes. If you change camera orientation to 90 or 270 degrees than you need to swap width and height of supported sizes and all will be ok.
Also surface view should lie in a frame layout and have center gravity.
Here is example on C# (Xamarin):
public void SurfaceChanged(ISurfaceHolder holder, Android.Graphics.Format format, int width, int height)
{
_camera.StopPreview();
// find best supported preview size
var parameters = _camera.GetParameters();
var supportedSizes = parameters.SupportedPreviewSizes;
var bestPreviewSize = supportedSizes
.Select(x => new { Width = x.Height, Height = x.Width, Original = x }) // HACK swap height and width because of changed orientation to 90 degrees
.OrderBy(x => Math.Pow(Math.Abs(x.Width - width), 3) + Math.Pow(Math.Abs(x.Height - height), 2))
.First();
if (height == bestPreviewSize.Height && width == bestPreviewSize.Width)
{
// start preview if best supported preview size equals current surface view size
parameters.SetPreviewSize(bestPreviewSize.Original.Width, bestPreviewSize.Original.Height);
_camera.SetParameters(parameters);
_camera.StartPreview();
}
else
{
// if not than change surface view size to best supported (SurfaceChanged will be called once again)
var layoutParameters = _surfaceView.LayoutParameters;
layoutParameters.Width = bestPreviewSize.Width;
layoutParameters.Height = bestPreviewSize.Height;
_surfaceView.LayoutParameters = layoutParameters;
}
}
Pay attention that camera parameters should be set as original size (not swapped), and surface view size should be swapped.
If you are talking about Datepicker for bootstrap, you set the start date (the min date) by using the following:
$('#datepicker').datepicker('setStartDate', <DATETIME STRING HERE>);
You can concat the data in this way:
InfoDF = pd.DataFrame()
tempDF = pd.DataFrame(rows,columns=['id','min_date'])
InfoDF = pd.concat([InfoDF,tempDF])
Under the job workspace folder, like:
C:\Program Files (x86)\Jenkins\jobs\job_name
there is a file named nextBuildNumber
.
Setting the build number in the file and reloading the configuration from disk (Manage Jenkins menu) will force the next build you start to have the value from the file as BUILD_NUMBER.
I had a similar issue that was resolved by unchecking the option in java advanced security for "Use SSL 2.0 compatible ClientHello format.
I recommend using this HttpURLConnection
instead HttpGet
. As HttpGet
is already deprecated in Android API level 22.
HttpURLConnection httpcon;
String url = null;
String data = null;
String result = null;
try {
//Connect
httpcon = (HttpURLConnection) ((new URL (url).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();
//Write
OutputStream os = httpcon.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(data);
writer.close();
os.close();
//Read
BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Actually now you can use generics in Python 3.5+. See PEP-484 and typing module documentation.
According to my practice it is not very seamless and clear especially for those who are familiar with Java Generics, but still usable.
Check if your project files are read-only. Remove the read-only property by right clicking on the project folder and select properties. In the properties screen remove the read-only checkbox. I came across the same problem, and this solved it for me.
I had the same issue. After retracing my recent steps, I found that adding a target declaration for a new target, followed by running pod install,
was the cause of the problem:
Resetting my branch and cleaning my project did not work, since Cocoapods modified at least one file that is not under source control. I know this because once I reset the remote branch to a commit before adding the extra target, and re-cloned the repo, the problem no longer existed.
Yes, there is one, it's the asterisk: *
a* // looks for 0 or more instances of "a"
This should be covered in any Java regex tutorial or documentation that you look up.
Swift 4+
This is extremely easy with autolayout! I'll explain the most simple use case. Let's say there is only a UITextView
in your UITableViewCell
.
textView
to the contentView
with constraints.textView
.tableView
on textViewDidChange
.That's all!
protocol TextViewUpdateProtocol {
func textViewChanged()
}
class TextViewCell: UITableViewCell {
//MARK: Reuse ID
static let identifier = debugDescription()
//MARK: UI Element(s)
/// Reference of the parent table view so that it can be updated
var textViewUpdateDelegate: TextViewUpdateProtocol!
lazy var textView: UITextView = {
let textView = UITextView()
textView.isScrollEnabled = false
textView.delegate = self
textView.layer.borderColor = UIColor.lightGray.cgColor
textView.layer.borderWidth = 1
textView.translatesAutoresizingMaskIntoConstraints = false
return textView
}()
//MARK: Padding Variable(s)
let padding: CGFloat = 50
//MARK: Initializer(s)
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubviews()
addConstraints()
textView.becomeFirstResponder()
}
//MARK: Helper Method(s)
func addSubviews() {
contentView.addSubview(textView)
}
func addConstraints() {
textView.leadingAnchor .constraint(equalTo: contentView.leadingAnchor, constant: padding).isActive = true
textView.trailingAnchor .constraint(equalTo: contentView.trailingAnchor, constant: -padding).isActive = true
textView.topAnchor .constraint(equalTo: contentView.topAnchor, constant: padding).isActive = true
textView.bottomAnchor .constraint(equalTo: contentView.bottomAnchor, constant: -padding).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TextViewCell: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
textViewUpdateDelegate.textViewChanged()
}
}
Now you have to inherit implement the protocol in your ViewController
.
extension ViewController: TextViewUpdateProtocol {
func textViewChanged() {
tableView.beginUpdates()
tableView.endUpdates()
}
}
Check out my repo for the full implementation.
If you want to terminate the thread, then just returning is fine. You do NOT need to call Thread.currentThread().interrupt()
(it will not do anything bad though. It's just that you don't need to.) This is because interrupt()
is basically used to notify the owner of the thread (well, not 100% accurate, but sort of). Because you are the owner of the thread, and you decided to terminate the thread, there is no one to notify, so you don't need to call it.
By the way, why in the first case we need to use currentThread? Is Thread does not refer to the current thread?
Yes, it doesn't. I guess it can be confusing because e.g. Thread.sleep() affects the current thread, but Thread.sleep() is a static method.
If you are NOT the owner of the thread (e.g. if you have not extended Thread
and coded a Runnable
etc.) you should do
Thread.currentThread().interrupt();
return;
This way, whatever code that called your runnable will know the thread is interrupted = (normally) should stop whatever it is doing and terminate. As I said earlier, it is just a mechanism of communication though. The owner might simply ignore the interrupted status and do nothing.. but if you do set the interrupted status, somebody might thank you for that in the future.
For the same reason, you should never do
Catch(InterruptedException ie){
//ignore
}
Because if you do, you are stopping the message there. Instead one should do
Catch(InterruptedException ie){
Thread.currentThread().interrupt();//preserve the message
return;//Stop doing whatever I am doing and terminate
}
Updating @Chackle's answer for Swift 2.x:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let currentPoint = touch.locationInView(self)
// do something with your currentPoint
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let currentPoint = touch.locationInView(self)
// do something with your currentPoint
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let currentPoint = touch.locationInView(self)
// do something with your currentPoint
}
}
You can use regex
here:
>>> import re
>>> strs = "foo\tbar\t\tspam"
>>> re.split(r'\t+', strs)
['foo', 'bar', 'spam']
update:
You can use str.rstrip
to get rid of trailing '\t'
and then apply regex.
>>> yas = "yas\t\tbs\tcda\t\t"
>>> re.split(r'\t+', yas.rstrip('\t'))
['yas', 'bs', 'cda']
This line of code might not work in IE 8 because of native support problems.
$(".hidden").attr("placeholder", "Type here to search");
You can try importing a JQuery placeholder plugin for this task. Simply import it to your libraries and initiate from the sample code below.
$('input, textarea').placeholder();
In my case, my website's output path is changed by somebody, the IIS Express even not load OWIN, and the setup class will not be hit of course. After I set the output path as "bin\", it works well.
This is a warning related to the fact that most JavaScript frameworks (jQuery, Angular, YUI, Bootstrap...) offer backward support for old-nasty-most-hated Internet Explorer starting from IE8 down to IE6 :/
One day that backward compatibility support will be dropped (for IE8/7/6 since IE9 deals with it), and you will no more see this warning (and other IEish bugs)..
It's a question of time (now IE8 has 10% worldwide share, once it reaches 1% it is DEAD), meanwhile, just ignore the warning and stay zen :)
In Java the type of any variable is either a primitive type or a reference type. Generic type arguments must be reference types. Since primitives do not extend Object
they cannot be used as generic type arguments for a parametrized type.
Instead use the Integer
class which is a wrapper for int
:
List<Integer> list = new ArrayList<Integer>();
If your using Java 7 you can simplify this declaration using the diamond operator:
List<Integer> list = new ArrayList<>();
With autoboxing in Java the primitive type int
will become an Integer
when necessary.
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.
So the following is valid:
int myInt = 1;
List<Integer> list = new ArrayList<Integer>();
list.add(myInt);
System.out.println(list.get(0)); //prints 1
You can use iperf to benchmark network performance (maximum possible throughput). See following links for details:
The solution to this is actually easier than I thought. You can simply add in your custom adapter's getView()
method a setOnClickListener() for the buttons you're using.
Any data associated with the button has to be added with myButton.setTag()
in the getView()
and can be accessed in the onClickListener via view.getTag()
I posted a detailed solution on my blog as a tutorial.
If you have the need to use other libraries in projects --typescript-- not just in projects - angle - you can look for tds's (TypeScript Declaration File) that are depares and that have information of methods, types, functions, etc. , which can be used by TypeScript, usually without the need for import. declare var is the last resource
npm install @types/lib-name --save-dev
Call Application.DoEvents()
after setting the label, but you should do all the work in a separate thread instead, so the user may close the window.
If they're both strings you can just do:
#define STR3 STR1 STR2
This then expands to:
#define STR3 "s" "1"
and in the C language, separating two strings with space as in "s" "1"
is exactly equivalent to having a single string "s1"
.
I just wanted to give it a bash, and made this:
function ditto( s, r, c ) {
return c-- ? ditto( s, r += s, c ) : r;
}
ditto( "foo", "", 128 );
I can't say I gave it much thought, and it probably shows :-)
String.prototype.ditto = function( c ) {
return --c ? this + this.ditto( c ) : this;
};
"foo".ditto( 128 );
And it's a lot like an answer already posted - I know this.
And how about a little default behaviour too?
String.prototype.ditto = function() {
var c = Number( arguments[ 0 ] ) || 2,
r = this.valueOf();
while ( --c ) {
r += this;
}
return r;
}
"foo".ditto();
Because, although the non recursive method will handle arbitrarily large repeats without hitting call stack limits, it's a lot slower.
Partly for my own amusement, and partly to point out in the simplest way I know that there are many ways to skin a cat, and depending on the situation, it's quite possible that the apparently best method isn't ideal.
A relatively fast and sophisticated method may effectively crash and burn under certain circumstances, whilst a slower, simpler method may get the job done - eventually.
Some methods may be little more than exploits, and as such prone to being fixed out of existence, and other methods may work beautifully in all conditions, but are so constructed that one simply has no idea how it works.
"So what if I dunno how it works?!"
Seriously?
JavaScript suffers from one of its greatest strengths; it's highly tolerant of bad behaviour, and so flexible it'll bend over backwards to return results, when it might have been better for everyone if it'd snapped!
"With great power, comes great responsibility" ;-)
But more seriously and importantly, although general questions like this do lead to awesomeness in the form of clever answers that if nothing else, expand one's knowledge and horizons, in the end, the task at hand - the practical script that uses the resulting method - may require a little less, or a little more clever than is suggested.
These "perfect" algorithms are fun and all, but "one size fits all" will rarely if ever be better than tailor made.
This sermon was brought to you courtesy of a lack of sleep and a passing interest. Go forth and code!
You are reinventing the wheel.
If you need persistence and other enterprise features use JMS (I'd suggest ActiveMq).
If you need fast in-memory queues use one of the impementations of java's Queue.
If you need to support java 1.4 or earlier, use Doug Lea's excellent concurrent package.
Try this, This was the solution that worked for me:
<div class="modal-dialog" style="min-width: 1500px" role="document">
Using System.Environment.NewLine is the only solution that worked for me. When I tried \r\n, it just repeated the actual \r\n in the text box.
If you're able to upgrade to Postgresql 9.5, the jsonb_set
command is available, as others have mentioned.
In each of the following SQL statements, I've omitted the where
clause for brevity; obviously, you'd want to add that back.
Update name:
UPDATE test SET data = jsonb_set(data, '{name}', '"my-other-name"');
Replace the tags (as oppose to adding or removing tags):
UPDATE test SET data = jsonb_set(data, '{tags}', '["tag3", "tag4"]');
Replacing the second tag (0-indexed):
UPDATE test SET data = jsonb_set(data, '{tags,1}', '"tag5"');
Append a tag (this will work as long as there are fewer than 999 tags; changing argument 999 to 1000 or above generates an error. This no longer appears to be the case in Postgres 9.5.3; a much larger index can be used):
UPDATE test SET data = jsonb_set(data, '{tags,999999999}', '"tag6"', true);
Remove the last tag:
UPDATE test SET data = data #- '{tags,-1}'
Complex update (delete the last tag, insert a new tag, and change the name):
UPDATE test SET data = jsonb_set(
jsonb_set(data #- '{tags,-1}', '{tags,999999999}', '"tag3"', true),
'{name}', '"my-other-name"');
It's important to note that in each of these examples, you're not actually updating a single field of the JSON data. Instead, you're creating a temporary, modified version of the data, and assigning that modified version back to the column. In practice, the result should be the same, but keeping this in mind should make complex updates, like the last example, more understandable.
In the complex example, there are three transformations and three temporary versions: First, the last tag is removed. Then, that version is transformed by adding a new tag. Next, the second version is transformed by changing the name
field. The value in the data
column is replaced with the final version.
Things have changed quite a bit since 2010 when this was posted and I haven't tried all the other answers but I have tried a few, and I found this to work the best for me using python3.6.
I was able to fetch about ~150 unique domains per second running on AWS.
import pandas as pd
import concurrent.futures
import requests
import time
out = []
CONNECTIONS = 100
TIMEOUT = 5
tlds = open('../data/sample_1k.txt').read().splitlines()
urls = ['http://{}'.format(x) for x in tlds[1:]]
def load_url(url, timeout):
ans = requests.head(url, timeout=timeout)
return ans.status_code
with concurrent.futures.ThreadPoolExecutor(max_workers=CONNECTIONS) as executor:
future_to_url = (executor.submit(load_url, url, TIMEOUT) for url in urls)
time1 = time.time()
for future in concurrent.futures.as_completed(future_to_url):
try:
data = future.result()
except Exception as exc:
data = str(type(exc))
finally:
out.append(data)
print(str(len(out)),end="\r")
time2 = time.time()
print(f'Took {time2-time1:.2f} s')
print(pd.Series(out).value_counts())
You can calculate with Dates.
var birthdate = new Date("1990/1/1");
var cur = new Date();
var diff = cur-birthdate; // This is the difference in milliseconds
var age = Math.floor(diff/31557600000); // Divide by 1000*60*60*24*365.25
The opposite of the ==
compare operator is !=
.
select Status, * from WorkItems t1
where exists (select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01)
AND TimeStamp>'2009-02-12 18:00:00'
UNION
select 'DELETED', * from WorkItems t1
where exists (select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01)
AND TimeStamp>'2009-02-12 18:00:00'
AND NOT (BoolField05=1)
Perhaps that'd do the trick. I can't test it from here though, and I'm not sure what version of SQL you're working against.
I think the SortedMap interface enforces what you ask for and TreeMap implements that.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/SortedMap.html http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html
Just simply use this Style
of DataGridRow
:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
</Style>
</DataGrid.RowStyle>
You need to loop through and parse/convert the elements in your array, like this:
var result_string = 'a,b,c,d|1,2,3,4',
result = result_string.split("|"),
alpha = result[0],
count = result[1],
count_array = count.split(",");
for(var i=0; i<count_array.length;i++) count_array[i] = +count_array[i];
//now count_array contains numbers
You can test it out here. If the +
, is throwing, think of it as:
for(var i=0; i<count_array.length;i++) count_array[i] = parseInt(count_array[i], 10);
Instead of detecting a browser, you should rather detect a feature (whether it's supported or not). This is what Modernizr does.
Of course there are cases where you still need to check the browser because you need to work around an issue and not to detect a feature. Specific WebKit
check which does not use jQuery $.browser
:
var isWebKit = !!window.webkitURL;
As some of the comments suggested the above approach doesn't work for older Safari versions. Updating with another approach suggested in comments and by another answer:
var isWebKit = 'WebkitAppearance' in document.documentElement.style;
Try the following:
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
class Program
{
static void Main(string[] args)
{
var source = @"
<!DOCTYPE html>
<html>
<body>
<p>An image from W3Schools:</p>
<img
src=""http://www.w3schools.com/images/w3schools_green.jpg""
alt=""W3Schools.com""
width=""104""
height=""142"">
</body>
</html>";
StartBrowser(source);
Console.ReadLine();
}
private static void StartBrowser(string source)
{
var th = new Thread(() =>
{
var webBrowser = new WebBrowser();
webBrowser.ScrollBarsEnabled = false;
webBrowser.DocumentCompleted +=
webBrowser_DocumentCompleted;
webBrowser.DocumentText = source;
Application.Run();
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
}
static void
webBrowser_DocumentCompleted(
object sender,
WebBrowserDocumentCompletedEventArgs e)
{
var webBrowser = (WebBrowser)sender;
using (Bitmap bitmap =
new Bitmap(
webBrowser.Width,
webBrowser.Height))
{
webBrowser
.DrawToBitmap(
bitmap,
new System.Drawing
.Rectangle(0, 0, bitmap.Width, bitmap.Height));
bitmap.Save(@"filename.jpg",
System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.
I could be able to update the environment variable by using the following
string EnvPath = System.Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine) ?? string.Empty;
if (!string.IsNullOrEmpty(EnvPath) && !EnvPath .EndsWith(";"))
EnvPath = EnvPath + ';';
EnvPath = EnvPath + @"C:\Test";
Environment.SetEnvironmentVariable("PATH", EnvPath , EnvironmentVariableTarget.Machine);
The practical use of this construct? It is a javascript replaceAll() on strings.
var s = 'stackoverflow_is_cool';
s = s.split('_').join(' ');
console.log(s);
will output:
stackoverflow is cool
select project to delete->settings->buttom click delete button->enter name of the repositories
The solution I use for large sql restore is a mysqldumpsplitter script. I split my sql.gz into individual tables. then load up something like mysql workbench and process it as a restore to the desired schema.
Here is the script https://github.com/kedarvj/mysqldumpsplitter
And this works for larger sql restores, my average on one site I work with is a 2.5gb sql.gz file, 20GB uncompressed, and ~100Gb once restored fully
HTML Code:
<div id="welcomeDiv" style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" value="Show Div" onclick="showDiv()" />
Javascript:
function showDiv() {
document.getElementById('welcomeDiv').style.display = "block";
}
See the Demo: http://jsfiddle.net/rathoreahsan/vzmnJ/
Although ANSI C does not have this mechanism, it is possible to use itoa() as a shortcut:
char buffer [33];
itoa (i,buffer,2);
printf ("binary: %s\n",buffer);
Here's the origin:
It is non-standard C, but K&R mentioned the implementation in the C book, so it should be quite common. It should be in stdlib.h.
Although optimally it would be nice if your code can run parallel, it can be the case you're simply using a thread so you do not block the UI thread, even if your app's usage flow will have to wait for it.
You've got pretty much 2 options here;
You can execute the code you want waiting, in the AsyncTask itself. If it has to do with updating the UI(thread), you can use the onPostExecute method. This gets called automatically when your background work is done.
If you for some reason are forced to do it in the Activity/Fragment/Whatever, you can also just make yourself a custom listener, which you broadcast from your AsyncTask. By using this, you can have a callback method in your Activity/Fragment/Whatever which only gets called when you want it: aka when your AsyncTask is done with whatever you had to wait for.
As long as your program's in a sane state, you can also call (void)puts(your_string)
to print it to stdout. Same principle applies to all functions available to the debugger, actually.
Adapted from http://docs.python.org/library/sqlite3.html:
# Larger example
for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
]:
c.execute('insert into stocks values (?,?,?,?,?)', t)
If you're doing a LOAD DATA INFILE 'myfile.csv'
operation, the easiest way to see if all the lines went in is to check show warnings();
If you load the data into an empty or temporary table, you can also check the number of rows that it has after the insert.
What you want is this (actually the exact inverse of the currently accepted answer):
git checkout email
git merge --strategy-option=theirs staging
What this does is:
email
branch files will now be exactly the same as staging
branchemail
branch's history will be maintainedstaging
branch's history will be added to email
historyAs added value, if you don't want all of staging
branch's history, you can use squash
to summarize it into a single commit message.
git checkout email
git merge --squash --strategy-option=theirs staging
git commit -m "Single commit message for squash branch's history here'
So in summary, what this second version does is:
email
branch files will now be exactly the same as staging
branchemail
branch's history will be maintainedemail
branch's history. This commit will represent ALL the changes that took place in the staging
branchBased on Gucu112's answer, but for .NET Core Console/Window application, it should be:
string projectDir =
Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\.."));
I'm using this in a xUnit project for a .NET Core Window Application.
[Update] Solution with React ^16.8 using Hooks
import React, { useEffect, useRef, useState } from 'react';
const SampleComponent = () => {
const [clickedOutside, setClickedOutside] = useState(false);
const myRef = useRef();
const handleClickOutside = e => {
if (!myRef.current.contains(e.target)) {
setClickedOutside(true);
}
};
const handleClickInside = () => setClickedOutside(false);
useEffect(() => {
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
});
return (
<button ref={myRef} onClick={handleClickInside}>
{clickedOutside ? 'Bye!' : 'Hello!'}
</button>
);
};
export default SampleComponent;
Solution with React ^16.3:
import React, { Component } from "react";
class SampleComponent extends Component {
state = {
clickedOutside: false
};
componentDidMount() {
document.addEventListener("mousedown", this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}
myRef = React.createRef();
handleClickOutside = e => {
if (!this.myRef.current.contains(e.target)) {
this.setState({ clickedOutside: true });
}
};
handleClickInside = () => this.setState({ clickedOutside: false });
render() {
return (
<button ref={this.myRef} onClick={this.handleClickInside}>
{this.state.clickedOutside ? "Bye!" : "Hello!"}
</button>
);
}
}
export default SampleComponent;
Try deleting your ASO files.
ASO files are cached compiled versions of your class files. Although the IDE is a lot better at letting go of old caches when changes are made, sometimes you have to manually delete them. To delete ASO files: Control>Delete ASO Files.
This is also the cause of the "I-am-not-seeing-my-changes-so-let-me-add-a-trace-now-everything-works" bug that was introduced in CS3.
Assign a new Image
object to your PictureBox
's Image
property. To load an Image
from a file, you may use the Image.FromFile
method. In your particular case, assuming the current directory is one under bin
, this should load the image bin/Pics/image1.jpg
, for example:
pictureBox1.Image = Image.FromFile("../Pics/image1.jpg");
Additionally, if these images are static and to be used only as resources in your application, resources would be a much better fit than files.
Because strip()
only strips trailing and leading characters, based on what you provided. I suggest:
>>> import re
>>> name = "Barack (of Washington)"
>>> name = re.sub('[\(\)\{\}<>]', '', name)
>>> print(name)
Barack of Washington
I am posting a way to use _netrc
to download materials from the site www.course.com.
If someone is going to use the coursera-dl to download the open-class materials on www.coursera.com, and on the Windows OS someone wants to use a file like ".netrc" which is in like-Unix OS to add the option -n
instead of -U <username> -P <password>
for convenience. He/she can do it like this:
Check the home path on Windows OS: setx HOME %USERPROFILE%
(refer to VonC's answer). It will save the HOME
environment variable as C:\Users\"username"
.
Locate into the directory C:\Users\"username"
and create a file name _netrc
.NOTE: there is NOT any suffix.
the content is like: machine coursera-dl login <user> password <pass>
Use a command like coursera-dl -n --path PATH <course name>
to download the class materials. More coursera-dl options details for this page.
If you have a nested list where the inner lists have different types and lengths and you would like to preserve the type, e.g.,
[[1, 2], ["foo", "bar"], [3.14, "baz", 20]]
then you can use the solution proposed by @sam-mason to this question, shown below:
from argparse import ArgumentParser
import json
parser = ArgumentParser()
parser.add_argument('-l', type=json.loads)
parser.parse_args(['-l', '[[1,2],["foo","bar"],[3.14,"baz",20]]'])
which gives:
Namespace(l=[[1, 2], ['foo', 'bar'], [3.14, 'baz', 20]])
$ su - postgres
$ psql
$ \du;
for see the user on db
select the user that do you want be superuser and:
$ ALTER USER "user" with superuser;
You can try this:
df['2nd'] = pd.to_numeric(df['2nd'].str.replace(',', ''))
df['CTR'] = pd.to_numeric(df['CTR'].str.replace('%', ''))
https://issuetracker.google.com/issues/72479188 indicates that plugins sometimes can introduce "compile" dependencies and that's what triggers the warning. Probably just easiest to star that issue and wait until they fix it to point out which plugins are causing the issue.
On your own system, try
install.packages("foo", dependencies=...)
with the dependencies=
argument is documented as
dependencies: logical indicating to also install uninstalled packages
which these packages depend on/link to/import/suggest (and so
on recursively). Not used if ‘repos = NULL’. Can also be a
character vector, a subset of ‘c("Depends", "Imports",
"LinkingTo", "Suggests", "Enhances")’.
Only supported if ‘lib’ is of length one (or missing), so it
is unambiguous where to install the dependent packages. If
this is not the case it is ignored, with a warning.
The default, ‘NA’, means ‘c("Depends", "Imports",
"LinkingTo")’.
‘TRUE’ means (as from R 2.15.0) to use ‘c("Depends",
"Imports", "LinkingTo", "Suggests")’ for ‘pkgs’ and
‘c("Depends", "Imports", "LinkingTo")’ for added
dependencies: this installs all the packages needed to run
‘pkgs’, their examples, tests and vignettes (if the package
author specified them correctly).
so you probably want a value TRUE
.
In your package, list what is needed in Depends:
, see the
Writing R Extensions manual which is pretty clear on this.
There are several ways. One way is to use save()
to save the exact object. e.g. for data frame foo
:
save(foo,file="data.Rda")
Then load it with:
load("data.Rda")
You could also use write.table()
or something like that to save the table in plain text, or dput()
to obtain R code to reproduce the table.
python: read lines from compressed text files
Using gzip.GzipFile
:
import gzip
with gzip.open('input.gz','r') as fin:
for line in fin:
print('got line', line)
How to do it with Oracle SQL Developer: In the Left pane, under the connections you will find "Sequences", right click and select create a new sequence from the context sensitive pop up. Fill out the details: Schema name, sequence_name, properties(start with value, min value, max value, increment value etc.) and click ok. Assuming that you have a table with a key that uses this auto_increment, while inserting in this table just give "your_sequence_name.nextval" in the field that utilizes this property. I guess this should help! :)
I used a local distribution of gradle downloaded from gradle website and used it in android studio.
It fixed the gradle build error.
For all those of you that try to remove the separating line of the tabWidget, here is an example project (and its respective tutorial), that work great for customizing the tabs and thus removing problems when tabs are at bottom. Eclipse Project: android-custom-tabs ; Original explanation: blog; Hope this helped.
On Linux, use the service of "Network Manager" over the DBus.
There is also good'ol shell program which can be invoke and the result grabbed (use an exec function under C):
$ /sbin/ifconfig | grep HWaddr
So, I checked Windows Features to make sure I didn't have this thing called WebDAV installed, and it said I didn't. Anyways, I went ahead and placed the following in my web.config (both front end and WebAPI, just to be sure), and it works now. I placed this inside <system.webServer>
.
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/> <!-- add this -->
</modules>
Additionally, it is often required to add the following to web.config
in the handlers. Thanks to Babak
<handlers>
<remove name="WebDAV" />
...
</handlers>
we can do like this:
in application.yml:
spring:
profiles:
active: test //modify here to switch between environments
include: application-${spring.profiles.active}.yml
in application-test.yml:
server:
port: 5000
and in application-local.yml:
server:
address: 0.0.0.0
port: 8080
then spring boot will start our app as we wish to.
The Law of Leaky Abstractions by Joel Spolsky
http://www.joelonsoftware.com/articles/LeakyAbstractions.html
The usual way to swap two items in Python is:
a, b = b, a
So it would seem to me that you would just do the same with an extended slice. However, it is slightly complicated because strings aren't mutable; so you have to convert to a list and then back to a string.
Therefore, I would do the following:
>>> s = 'badcfe'
>>> t = list(s)
>>> t[::2], t[1::2] = t[1::2], t[::2]
>>> ''.join(t)
'abcdef'
It's worth to mention that CLOB / BLOB data types and their sizes are supported by MySQL 5.0+, so you can choose the proper data type for your need.
http://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html
Data Type Date Type Storage Required
(CLOB) (BLOB)
TINYTEXT TINYBLOB L + 1 bytes, where L < 2**8 (255)
TEXT BLOB L + 2 bytes, where L < 2**16 (64 K)
MEDIUMTEXT MEDIUMBLOB L + 3 bytes, where L < 2**24 (16 MB)
LONGTEXT LONGBLOB L + 4 bytes, where L < 2**32 (4 GB)
where L stands for the byte length of a string
You can easily write one yourself.
given:
int array[]={1,2};
you do:
int temp=array[0];
array[0]=array[1];
array[1]=temp;
And you're done. 3 lines of code.
I tried this and it worked:
C:\cd MySQL installed path\MySQL -uyourusername -pyourpassword
If you tried myList|length and myList|length_is and its not getting desired results, then you should use myList.count
Nginx need to have +x access on all directories leading to the site's root directory.
Ensure you have +x on all of the directories in the path leading to the site's root. For example, if the site root is /home/username/siteroot:
chmod +x /home/
chmod +x /home/username
chmod +x /home/username/siteroot
see there link was very nice and simple. its working fine... u don't want any library its working fine. click here
OnTouchListener gestureListener = new View.OnTouchListener() {
private int padding = 0;
private int initialx = 0;
private int currentx = 0;
private ViewHolder viewHolder;
public boolean onTouch(View v, MotionEvent event) {
if ( event.getAction() == MotionEvent.ACTION_DOWN) {
padding = 0;
initialx = (int) event.getX();
currentx = (int) event.getX();
viewHolder = ((ViewHolder) v.getTag());
}
if ( event.getAction() == MotionEvent.ACTION_MOVE) {
currentx = (int) event.getX();
padding = currentx - initialx;
}
if ( event.getAction() == MotionEvent.ACTION_UP ||
event.getAction() == MotionEvent.ACTION_CANCEL) {
padding = 0;
initialx = 0;
currentx = 0;
}
if(viewHolder != null) {
if(padding == 0) {
v.setBackgroundColor(0xFF000000 );
if(viewHolder.running)
v.setBackgroundColor(0xFF058805);
}
if(padding > 75) {
viewHolder.running = true;
v.setBackgroundColor(0xFF00FF00 );
viewHolder.icon.setImageResource(R.drawable.clock_running);
}
if(padding < -75) {
viewHolder.running = false;
v.setBackgroundColor(0xFFFF0000 );
}
v.setPadding(padding, 0,0, 0);
}
return true;
}
};
At first, the problem is because you did't put any parameter for mysqli_error. I can see that it has been solved based on the post here. Most probably, the next problem is cause by wrong file path for the included file.. .
Are you sure this code
$myConnection = mysqli_connect("$db_host","$db_username","$db_pass","$db_name") or die ("could not connect to mysql");
is in the 'scripts' folder and your main code file is on the same level as the script folder?
Functions are not allowed to have side-effects such as altering table contents.
Stored Procedures are.
If a function called a stored procedure, the function would become able to have side-effects.
So, sorry, but no, you can't call a stored procedure from a function.
You're getting an error because async/await use generators, which are an ES2016 feature, not ES2015. One way to fix this is to install the babel preset for ES2016 (npm install --save babel-preset-es2016
) and compile to ES2016 instead of ES2015:
"presets": [
"es2016",
// etc...
]
As the other answers mention, you can also use polyfills (though make sure you load the polyfill first before any other code runs). Alternatively, if you don't want to include all of the polyfill dependencies, you can use the babel-regenerator-runtime or the babel-plugin-transform-runtime.
I believe this error message is due to a "zombie transaction".
Look for possible areas where the transacton is being committed twice (or rolled back twice, or rolled back and committed, etc.). Does the .Net code commit the transaction after the SP has already committed it? Does the .Net code roll it back on encountering an error, then attempt to roll it back again in a catch (or finally) clause?
It's possible an error condition was never being hit on the old server, and thus the faulty "double rollback" code was never hit. Maybe now you have a situation where there is some configuration error on the new server, and now the faulty code is getting hit via exception handling.
Can you debug into the error code? Do you have a stack trace?
I had this same problem and resolved it by making sure all references to the previous version of crystal from the Web Config file, the server, and the publishing workstation were removed. Other than the full trust basically everything that user707217 did, I did and it worked for my upgraded Web application
Violating the Java naming conventions (variable names and method names start with lowercase, class names start with uppercase) is contributing to your confusion.
The variable Random
is only "in scope" inside the main
method. It's not accessible to any methods called by main
. When you return from main
, the variable disappears (it's part of the stack frame).
If you want all of the methods of your class to use the same Random
instance, declare a member variable:
class MyObj {
private final Random random = new Random();
public void compTurn() {
while (true) {
int a = random.nextInt(10);
if (possibles[a] == 1)
break;
}
}
}
Try disabling iptables: service iptables stop
If this works, enable TCP port 80 to your firewall rules: run system-config-selinux from root, and enable TCP port 80 (HTTP) on your firewall.
.htaccess:
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
php_value error_log /home/path/public_html/domain/PHP_errors.log
Solution 1 - you need to change your backend to accept your incoming requests
Solution 2 - using Angular proxy see here
Please note this is only for
ng serve
, you can't use proxy inng build
Note: the reason it's working via postman is postman doesn't send preflight requests while your browser does.
You should be targeting select for your CSS instead of select option.
select {
padding: 10px;
margin: 0;
-webkit-border-radius:4px;
-moz-border-radius:4px;
border-radius:4px;
}
View this article Styling Select Box with CSS3 for more styling options.
ES6 way, without mutating original data.
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
}];
//find the index of object from array that you want to update
const objIndex = projects.findIndex(obj => obj.value === 'jquery-ui');
// make new object of updated object.
const updatedObj = { ...projects[objIndex], desc: 'updated desc value'};
// make final new array of objects by combining updated object.
const updatedProjects = [
...projects.slice(0, objIndex),
updatedObj,
...projects.slice(objIndex + 1),
];
console.log("original data=", projects);
console.log("updated data=", updatedProjects);
$('#some_id').click(function() {
$("body").css("cursor", "progress");
$.ajax({
url: "test.html",
context: document.body,
success: function() {
$("body").css("cursor", "default");
}
});
});
This will create a loading cursor till your ajax call succeeds.
I'm sure there's a better way to achieve this and I would like to read about it, but a workaround I can think of is this:
rm
'ed directory to the original machine (ssh, ftp, whatever).pip uninstall
the package (should work again then).But, yes, I'd also love to hear about a decent solution for this situation.
Very Easy Code
Follow this instruction
Create excel.php file in your localhost root directory and copy and past this code.
Like this
http://localhost/excel.php?fileName=excelfile&link=1
<!-- http://localhost/excel.php?fileName=excelfile&link=2 -->
<!DOCTYPE html>
<html>
<head>
<title>Export excel file from html table</title>
</head>
<body style="display:
<?php
if( $_REQUEST['link'] == 1 ){
echo 'none';
}
?>;
">
<!-- --------Optional-------- -->
Excel <input type="radio" value="1" name="exportFile">
Others <input type="radio" value="2" name="exportFile">
<button onclick="myFunction()">Download</button>
<br>
<br>
<!-- --------/Optional-------- -->
<table width="100%" id="tblData">
<tbody>
<tr>
<th>Student Name</th>
<th>Group</th>
<th>Roll No.</th>
<th>Class</th>
<th>Contact No</th>
</tr>
<tr>
<td>Bulbul Sarker</td>
<td>Science</td>
<td>1</td>
<td>Nine</td>
<td>01724....</td>
</tr>
<tr>
<td>Karim</td>
<td>Science</td>
<td>3</td>
<td>Nine</td>
<td>0172444...</td>
</tr>
</tbody>
</table>
</body>
</html>
<style>
table#tblData{
border-collapse: collapse;
}
#tblData th,
#tblData td{
border:1px solid #CCC;
text-align: center;
}
</style>
<script type="text/javascript">
/*--------Optional--------*/
function myFunction() {
let val = document.querySelector('input[name="exportFile"]:checked').value;
if(val == 1)
{
this.exportTableToExcel();
}
}
/*--------/Optional--------*/
function exportTableToExcel(){
let filename2 = "<?php echo $_REQUEST['fileName']; ?>";
let tableId = 'tblData';
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableId);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
let filename = filename2?filename2+'.xls':'excel_data.xls';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}
</script>
<?php
if( $_REQUEST['link'] == 1 ){
echo '<script type="text/javascript">
exportTableToExcel();
</script>';
}
?>
background-image
CSS property on the <a>
tagdisplay:block
and adjust width
and height
in CSSThis should do the trick.
More robust:
function trim(word) { word = word.replace(/[^\x21-\x7E]+/g, ' '); // change non-printing chars to spaces return word.replace(/^\s+|\s+$/g, ''); // remove leading/trailing spaces }
Step 1) Remove the semi-colon, it's an object you're creating...
a(this).next().css({
left : c,
transition : 'opacity 1s ease-in-out';
});
to
a(this).next().css({
left : c,
transition : 'opacity 1s ease-in-out'
});
Step 2) Vendor-prefixes... no browsers use transition
since it's the standard and this is an experimental feature even in the latest browsers:
a(this).next().css({
left : c,
WebkitTransition : 'opacity 1s ease-in-out',
MozTransition : 'opacity 1s ease-in-out',
MsTransition : 'opacity 1s ease-in-out',
OTransition : 'opacity 1s ease-in-out',
transition : 'opacity 1s ease-in-out'
});
Here is a demo: http://jsfiddle.net/83FsJ/
Step 3) Better vendor-prefixes... Instead of adding tons of unnecessary CSS to elements (that will just be ignored by the browser) you can use jQuery to decide what vendor-prefix to use:
$('a').on('click', function () {
var myTransition = ($.browser.webkit) ? '-webkit-transition' :
($.browser.mozilla) ? '-moz-transition' :
($.browser.msie) ? '-ms-transition' :
($.browser.opera) ? '-o-transition' : 'transition',
myCSSObj = { opacity : 1 };
myCSSObj[myTransition] = 'opacity 1s ease-in-out';
$(this).next().css(myCSSObj);
});?
Here is a demo: http://jsfiddle.net/83FsJ/1/
Also note that if you specify in your transition
declaration that the property to animate is opacity
, setting a left
property won't be animated.
You could mess with the margins: http://jsfiddle.net/zV2p4/
But you would probably be better off using position: absolute
. This does not change display: block
, but it will make the width auto. To fix this, make the divs width: 100%
I have an idea that I don't have time to try to implement immediately.
But what if you do something like the following:
$ MY_HISTORY_FILE = `get_temp_filename`
$ MY_HISTORY_FILE=$MY_HISTORY_FILE bash -i 2>&1 | tee $MY_HISTORY_FILE
$ some_command
$ cat $MY_HISTORY_FILE
$ # ^You'll want to filter that down in practice!
There might be issues with IO buffering. Also the file might get too huge. One would have to come up with a solution to these problems.
Setting tcp-keepalive to 60 (it was set to 0) in server's redis configuration helped me resolve this issue.
Another nifty way is:
DATEADD(dd, 0, DATEDIFF(dd, 0, [YourDate]))
Which gets the number of days from DAY 0 to YourDate and the adds it to DAY 0 to set the baseline again. This method (or "derivatives" hereof) can be used for a bunch of other date manipulation.
Edit - other date calculations:
First Day of Month:
DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0)
First Day of the Year:
DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0)
First Day of the Quarter:
DATEADD(qq, DATEDIFF(qq, 0, getdate()), 0)
Last Day of Prior Month:
DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0))
Last Day of Current Month:
DATEADD(ms, -3, DATEADD(mm, DATEDIFF(m, 0, getdate()) + 1, 0))
Last Day of Current Year:
DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, getdate()) + 1, 0))
First Monday of the Month:
DATEADD(wk, DATEDIFF(wk, 0, DATEADD(dd, 6 - DATEPART(day, getdate()), getdate())), 0)
Edit: True, Joe, it does not add it to DAY 0, it adds 0 (days) to the number of days which basically just converts it back to a datetime.
i also just got this error message by using the wrong syntax in an if
clause
else if
(syntax error: unexpected end of file) elif
(correct syntax)i debugged it by commenting bits out until it worked
One liner:
Image bmp = (Bitmap)((new ImageConverter()).ConvertFrom(imageBytes));
Disabling and Enabling All Foreign Keys
CREATE PROCEDURE pr_Disable_Triggers_v2
@disable BIT = 1
AS
DECLARE @sql VARCHAR(500)
, @tableName VARCHAR(128)
, @tableSchema VARCHAR(128)
-- List of all tables
DECLARE triggerCursor CURSOR FOR
SELECT t.TABLE_NAME AS TableName
, t.TABLE_SCHEMA AS TableSchema
FROM INFORMATION_SCHEMA.TABLES t
ORDER BY t.TABLE_NAME, t.TABLE_SCHEMA
OPEN triggerCursor
FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema
WHILE ( @@FETCH_STATUS = 0 )
BEGIN
SET @sql = 'ALTER TABLE ' + @tableSchema + '.[' + @tableName + '] '
IF @disable = 1
SET @sql = @sql + ' DISABLE TRIGGER ALL'
ELSE
SET @sql = @sql + ' ENABLE TRIGGER ALL'
PRINT 'Executing Statement - ' + @sql
EXECUTE ( @sql )
FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema
END
CLOSE triggerCursor
DEALLOCATE triggerCursor
First, the foreignKeyCursor cursor is declared as the SELECT statement that gathers the list of foreign keys and their table names. Next, the cursor is opened and the initial FETCH statement is executed. This FETCH statement will read the first row's data into the local variables @foreignKeyName and @tableName. When looping through a cursor, you can check the @@FETCH_STATUS for a value of 0, which indicates that the fetch was successful. This means the loop will continue to move forward so it can get each successive foreign key from the rowset. @@FETCH_STATUS is available to all cursors on the connection. So if you are looping through multiple cursors, it is important to check the value of @@FETCH_STATUS in the statement immediately following the FETCH statement. @@FETCH_STATUS will reflect the status for the most recent FETCH operation on the connection. Valid values for @@FETCH_STATUS are:
0 = FETCH was successful
-1 = FETCH was unsuccessful
-2 = the row that was fetched is missingInside the loop, the code builds the ALTER TABLE command differently depending on whether the intention is to disable or enable the foreign key constraint (using the CHECK or NOCHECK keyword). The statement is then printed as a message so its progress can be observed and then the statement is executed. Finally, when all rows have been iterated through, the stored procedure closes and deallocates the cursor.
Why don't you just save/serve the CSS file as UTF-8?
nav a:hover:after {
content: "?";
}
If that's not good enough, and you want to keep it all-ASCII:
nav a:hover:after {
content: "\2193";
}
The general format for a Unicode character inside a string is \000000
to \FFFFFF
– a backslash followed by six hexadecimal digits. You can leave out leading 0
digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.
Relevant part of the CSS2 spec:
Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:
- with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
- by providing exactly 6 hexadecimal digits: "\000026B" ("&B")
In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.
If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).
- Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
The identifier "te\st" is exactly the same identifier as "test".
Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).
I modified the /etc/sysconfig/ip6tables-config
file changing:
IP6TABLES_SAVE_ON_STOP="no"
To:
IP6TABLES_SAVE_ON_STOP="yes"
And this:
IP6TABLES_SAVE_ON_RESTART="no"
To:
IP6TABLES_SAVE_ON_RESTART="yes"
This seemed to save the changes I made using the iptables commands through a reboot.
The way to make this work is to iterate over the list and cast the elements. This can be done using ConvertAll:
List<A> listOfA = new List<C>().ConvertAll(x => (A)x);
You could also use Linq:
List<A> listOfA = new List<C>().Cast<A>().ToList();
This should be the Unix load average. Wikipedia has a nice article about this.
The numbers show the average load of the CPU in different time intervals. From left to right: last minute/last five minutes/last fifteen minutes
My impression is that R CMD BATCH
is a bit of a relict. In any case, the more recent Rscript
executable (available on all platforms), together with commandArgs()
makes processing command line arguments pretty easy.
As an example, here is a little script -- call it "myScript.R"
:
## myScript.R
args <- commandArgs(trailingOnly = TRUE)
rnorm(n=as.numeric(args[1]), mean=as.numeric(args[2]))
And here is what invoking it from the command line looks like
> Rscript myScript.R 5 100
[1] 98.46435 100.04626 99.44937 98.52910 100.78853
Edit:
Not that I'd recommend it, but ... using a combination of source()
and sink()
, you could get Rscript
to produce an .Rout
file like that produced by R CMD BATCH
. One way would be to create a little R script -- call it RscriptEcho.R
-- which you call directly with Rscript. It might look like this:
## RscriptEcho.R
args <- commandArgs(TRUE)
srcFile <- args[1]
outFile <- paste0(make.names(date()), ".Rout")
args <- args[-1]
sink(outFile, split = TRUE)
source(srcFile, echo = TRUE)
To execute your actual script, you would then do:
Rscript RscriptEcho.R myScript.R 5 100
[1] 98.46435 100.04626 99.44937 98.52910 100.78853
which will execute myScript.R
with the supplied arguments and sink interleaved input, output, and messages to a uniquely named .Rout
.
Edit2:
You can run Rscript verbosely and place the verbose output in a file.
Rscript --verbose myScript.R 5 100 > myScript.Rout
Just delete /etc/ImageMagick/policy.xml
file. E.g.
rm /etc/<ImageMagick_PATH>/policy.xml
For ImageMagick 6, it's:
sudo rm /etc/ImageMagick-6/policy.xml
like this
\begin{align}
x_{\rm L} & = L \int{\cos\theta\left(\xi\right) d\xi}, \label{eq_1} \\\\
y_{\rm L} & = L \int{\sin\theta\left(\xi\right) d\xi}, \nonumber
\end{align}
You can put your string into viewdata in controller like this :
ViewData["string"] = DBstring;
And then call that viewdata in view like this :
@Html.Raw(ViewData["string"].ToString())
Just another bit. in some case i found no result on all_tab_privs! i found it indeed on dba_tab_privs. I think so that this last table is better to check for any grant available on an object (in case of impact analysis). The statement becomes:
select * from dba_tab_privs where table_name = 'sequence_name';
Delete origin and anchor will be more regular picture
var icon = {
url: "image path", // url
scaledSize: new google.maps.Size(50, 50), // size
};
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, long),
map: map,
icon: icon
});
using Newtonsoft.Json;
Class1 obj1 = new Class1();
Class2 obj2 = JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj1));
public class Class1
{
public static explicit operator Class2(Class1 obj)
{
return JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj));
}
}
Which then allows you to do something like
Class1 obj1 = new Class1();
Class2 obj2 = (Class2)obj1;
To solve this issue:
Rebuilding git with openssl instead of gnutls fixed my problem.
I followed these instructions
No way to do that other than validate file extension with JavaScript when input path is populated by the file picker. To implement anything fancier you need to write your own component for whichever browser you want (activeX or XUL)
There's an "accept" attribute in HTML4.01 but I'm not aware of any browser supporting it - e.g. accept="image/gif,image/jpeg
- so it's a neat but impractical spec
For playing sound in java, you can refer to the following code.
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
import javax.swing.*;
// To play sound using Clip, the process need to be alive.
// Hence, we use a Swing application.
public class SoundClipTest extends JFrame {
public SoundClipTest() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Test Sound Clip");
this.setSize(300, 200);
this.setVisible(true);
try {
// Open an audio input stream.
URL url = this.getClass().getClassLoader().getResource("gameover.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new SoundClipTest();
}
}
I had the same problem for Visual Studio 2019 v16.8.6. It was fixed after repair Visual Studio from Visual Studio Installer.
When you are creating an object of intent, you can take advantage of following two methods for passing objects between two activities.
You can have your class implement either Parcelable or Serializable. Then you can pass around your custom classes across activities. I have found this very useful.
Here is a small snippet of code I am using
CustomListing currentListing = new CustomListing();
Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelable(Constants.CUSTOM_LISTING, currentListing);
i.putExtras(b);
i.setClass(this, SearchDetailsActivity.class);
startActivity(i);
And in newly started activity code will be something like this...
Bundle b = this.getIntent().getExtras();
if (b != null)
mCurrentListing = b.getParcelable(Constants.CUSTOM_LISTING);
Example using GPS latitude/longitude of 2 points.
var latitude1 = 39.46;
var longitude1 = -0.36;
var latitude2 = 40.40;
var longitude2 = -3.68;
var distance = google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(latitude1, longitude1), new google.maps.LatLng(latitude2, longitude2));
NOTE calling parent method via super will only work on parent class,
If your parent is interface, and wants to call the default methods then need to add interfaceName before super like IfscName.super.method();
interface Vehicle {
//Non abstract method
public default void printVehicleTypeName() { //default keyword can be used only in interface.
System.out.println("Vehicle");
}
}
class FordFigo extends FordImpl implements Vehicle, Ford {
@Override
public void printVehicleTypeName() {
System.out.println("Figo");
Vehicle.super.printVehicleTypeName();
}
}
Interface name is needed because same default methods can be available in multiple interface name that this class extends. So explicit call to a method is required.
This works fine int i = (int) dbl;
Can you please test this structure. If I remember correct you can use it this way:
{
"applesRequest": {
"applesDO": [
{
"apple": "Green Apple"
},
{
"apple": "Red Apple"
}
]
}
}
Second, please add default constructor to each class it also might help.
for a non-generic, simple solution to your exact problem:
homes.sort(
function(a, b) {
if (a.city === b.city) {
// Price is only important when cities are the same
return b.price - a.price;
}
return a.city > b.city ? 1 : -1;
});
I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
I was faces this issue but after change object into str, problem solved. str(fname).isalpha():
This happened to me. And, in my case I need Android SDK Platform 29 because I am using react native 0.63 and Android 10 (Q). I had to uninstall Android SDK Platform 28 because it was the one that caused the warning. I found this video See Here explaining the process.
With this I was able eliminate the warning.
Just use .contains
. For example, if you were checking if an ArrayList arr
contains a value val
, you would simply run arr.contains(val)
, which would return a boolean representing if the value is contained. For more information, see the docs for .contains
.
Maybe help, if you want to add some filter:
context.Persons
.Where(c => c.state == myState)
.Select(c => c.age)
.DefaultIfEmpty(0)
.Max();
Add a WHERE
clause
UPDATE dbo.TestStudents
SET LASTNAME = CASE
WHEN LASTNAME = 'AAA' THEN 'BBB'
WHEN LASTNAME = 'CCC' THEN 'DDD'
WHEN LASTNAME = 'EEE' THEN 'FFF'
ELSE LASTNAME
END
WHERE LASTNAME IN ('AAA', 'CCC', 'EEE')
for ubuntu this work for me, you can take a screenshot of select window with this:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gdk
from gi.repository import GdkPixbuf
import numpy as np
from Xlib.display import Display
#define the window name
window_name = 'Spotify'
#define xid of your select 'window'
def locate_window(stack,window):
disp = Display()
NET_WM_NAME = disp.intern_atom('_NET_WM_NAME')
WM_NAME = disp.intern_atom('WM_NAME')
name= []
for i, w in enumerate(stack):
win_id =w.get_xid()
window_obj = disp.create_resource_object('window', win_id)
for atom in (NET_WM_NAME, WM_NAME):
window_name=window_obj.get_full_property(atom, 0)
name.append(window_name.value)
for l in range(len(stack)):
if(name[2*l]==window):
return stack[l]
window = Gdk.get_default_root_window()
screen = window.get_screen()
stack = screen.get_window_stack()
myselectwindow = locate_window(stack,window_name)
img_pixbuf = Gdk.pixbuf_get_from_window(myselectwindow,*myselectwindow.get_geometry())
to transform pixbuf into array
def pixbuf_to_array(p):
w,h,c,r=(p.get_width(), p.get_height(), p.get_n_channels(), p.get_rowstride())
assert p.get_colorspace() == GdkPixbuf.Colorspace.RGB
assert p.get_bits_per_sample() == 8
if p.get_has_alpha():
assert c == 4
else:
assert c == 3
assert r >= w * c
a=np.frombuffer(p.get_pixels(),dtype=np.uint8)
if a.shape[0] == w*c*h:
return a.reshape( (h, w, c) )
else:
b=np.zeros((h,w*c),'uint8')
for j in range(h):
b[j,:]=a[r*j:r*j+w*c]
return b.reshape( (h, w, c) )
beauty_print = pixbuf_to_array(img_pixbuf)
You need to use the method equals()
when comparing a string, otherwise you're just comparing the object references to each other, so in your case you want:
if (!statusCheck.equals("success")) {
Try the below code snippet
<!doctype html>
<html>
<head>
<title>Audio</title>
</head>
<body>
<script>
function play() {
var audio = document.getElementById("audio");
audio.play();
}
</script>
<input type="button" value="PLAY" onclick="play()">
<audio id="audio" src="http://dev.interactive-creation-works.net/1/1.ogg"></audio>
</body>
</html>
Here is nice documentation on APIs,
https://developer.chrome.com/apps/notifications
And, official video explanation by Google,
You can import these js Files. It worked fine for me.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" ></script>
Chrome - Press CTRL + L while focusing the console input.
Firefox - clear()
in console input.
Internet Explorer - Press CTRL + L while focusing the console input.
Edge - Press CTRL + L while focusing the console input.
Have a good day!
There is a way to get a range of values in a single query, but its a bit slow. It can be sped up by using cache tables.
assume you want a select with a range of all BOOLEAN values:
SELECT 0 as b UNION SELECT 1 as b;
we can make a view
CREATE VIEW ViewBoolean AS SELECT 0 as b UNION SELECT 1 as b;
then you can do a Byte by
CREATE VIEW ViewByteValues AS
SELECT b0.b + b1.b*2 + b2.b*4 + b3.b*8 + b4.b*16 + b5.b*32 + b6.b*64 + b7.b*128 as v FROM
ViewBoolean b0,ViewBoolean b1,ViewBoolean b2,ViewBoolean b3,ViewBoolean b4,ViewBoolean b5,ViewBoolean b6,ViewBoolean b7;
then you can do a
CREATE VIEW ViewInt16 AS
SELECT b0.v + b1.v*256 as v FROM
ViewByteValues b0,ViewByteValues b1;
then you can do a
SELECT v+MIN as x FROM ViewInt16 WHERE v<MAX-MIN;
To speed this up I skipped the auto-calculation of byte values and made myself a
CREATE VIEW ViewByteValues AS
SELECT 0 as v UNION SELECT 1 as v UNION SELECT ...
...
...254 as v UNION SELECT 255 as v;
If you need a range of dates you can do.
SELECT DATE_ADD('start_date',v) as day FROM ViewInt16 WHERE v<NumDays;
or
SELECT DATE_ADD('start_date',v) as day FROM ViewInt16 WHERE day<'end_date';
you might be able to speed this up with the slightly faster MAKEDATE function
SELECT MAKEDATE(start_year,1+v) as day FRON ViewInt16 WHERE day>'start_date' AND day<'end_date';
Please note that this tricks are VERY SLOW and only allow the creation of FINITE sequences in a pre-defined domain (for example int16 = 0...65536 )
I am sure you can modify the queries a bit to speed things up by hinting to MySQL where to stop calculating ;) (using ON clauses instead of WHERE clauses and stuff like that)
For example:
SELECT MIN + (b0.v + b1.v*256 + b2.v*65536 + b3.v*16777216) FROM
ViewByteValues b0,
ViewByteValues b1,
ViewByteValues b2,
ViewByteValues b3
WHERE (b0.v + b1.v*256 + b2.v*65536 + b3.v*16777216) < MAX-MIN;
will keep your SQL server busy for a few hours
However
SELECT MIN + (b0.v + b1.v*256 + b2.v*65536 + b3.v*16777216) FROM
ViewByteValues b0
INNER JOIN ViewByteValues b1 ON (b1.v*256<(MAX-MIN))
INNER JOIN ViewByteValues b2 ON (b2.v*65536<(MAX-MIN))
INNER JOIN ViewByteValues b3 ON (b3.v*16777216<(MAX-MIN)
WHERE (b0.v + b1.v*256 + b2.v*65536 + b3.v*16777216) < (MAX-MIN);
will run reasonably fast - even if MAX-MIN is huge as long as you limit the result with LIMIT 1,30 or something. a COUNT(*) however will take ages and if you make the mistake of adding ORDER BY when MAX-MIN is bigger than say 100k it will again take several seconds to calculate...
I had the same problem. And finally it was a double include. One include in a file named X. And another include in a file named Y. Knowing that in file Y I had include ('X')
You should use isinstance
isinstance(...)
isinstance(object, class-or-type-or-tuple) -> bool
Return whether an object is an instance of a class or of a subclass thereof.
With a type as second argument, return whether that is the object's type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
I've spent a good deal of time fighting with Ionic / Angular's $state & $stateParams;
To utilize $state.go() and $stateParams you must have certain things setup and other parameters must not be present.
In my app.config() I've included $stateProvider and defined within it several states:
$stateProvider
.state('home', {
templateUrl: 'home',
controller: 'homeController'
})
.state('view', {
templateUrl: 'overview',
params: ['index', 'anotherKey'],
controller: 'overviewController'
})
The params
key is especially important. As well, notice there are NO url
keys present... utilizing stateParams and URLs do NOT mix. They are mutually exclusive to each other.
In the $state.go() call, define it as such:
$state.go('view', { 'index': 123, 'anotherKey': 'This is a test' })
The index
and anotherKey
$stateParams variables will ONLY be populated if they are first listed in the $stateController params
defining key.
Within the controller, include $stateParams as illustrated:
app.controller('overviewController', function($scope, $stateParams) {
var index = $stateParams.index;
var anotherKey = $stateParams.anotherKey;
});
The passed variables should be available!
Like this :
jQuery(document).ready(function () {
var title = jQuery(this).attr('title');
});
works for IE, Firefox and Chrome.
I think you'll find your answer if you refer to this post: Deserialize JSON into C# dynamic object?
There are various ways of achieving what you want here. The System.Web.Helpers.Json approach (a few answers down) seems to be the simplest.
If you want to get a custom window title color on Windows 10, in short going from this
to this (or any other custom color for the window of your Eclipse IDE)
follow the next steps.
Go to C:\Windows\Resources\Themes\
. Duplicate the folder aero
and the file aero.theme
. If you can't duplicate the folder and the file then right click on both, Properties, Security, Modify, add your user to Permissions, and set authorizations to modify, read and write.
Rename the folder C:\Windows\Resources\Themes\aero - copy
and the file C:\Windows\Resources\Themes\aero - copy.theme
to C:\Windows\Resources\Themes\custom
and C:\Windows\Resources\Themes\custom.theme
(you can pick the name you want).
Rename C:\Windows\Resources\Themes\custom\aero.msstyles
to C:\Windows\Resources\Themes\custom.msstyles
.
Rename C:\Windows\Resources\Themes\custom\%your_locale%\aero.msstyles.mui
(%your_locale% is fr-FR in my case) to C:\Windows\Resources\Themes\custom\%your_locale%\custom.msstyles.mui
.
Edit custom.theme
with Notepad and change the PATH
variable of VisualStyles
to your custom.msstyles
.
Set your custom theme (yet unchanged) by double-clicking on custom.theme
. Then right-click on start menu button, go to Parameters -> Customize appearance -> Themes and select the second one. Go to the menu Colors
, select dark mode for every applications. Choose custom color for accent color and put it full black.
Apply your favorite dark theme (here DevStyle - Darkest dark - Deep black) to Eclipse and voilà, you have a full dark theme for Eclipse on Windows 10!
String dateStr = "2016-09-17T08:14:03+00:00";
String s = dateStr.replace("Z", "+00:00");
s = s.substring(0, 22) + s.substring(23);
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s);
Timestamp createdOn = new Timestamp(date.getTime());
mcList.setCreated_on(createdOn);
Java 7 added support for time zone descriptors according to ISO 8601. This can be use in Java 7.
What you have there will return no row at all if the user doesn't exist. Here's what you need:
SELECT CASE WHEN EXISTS (
SELECT *
FROM [User]
WHERE UserID = 20070022
)
THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END
If you have windows 64 bits, try to install oracle driver 32 bits first then 64 bits driver, thats what i do and is working
Your original code uses FileInputStream, which is for accessing file system hosted files.
The constructor you used will attempt to locate a file named a.txt in the www.somewebsite.com subfolder of the current working directory (the value of system property user.dir). The name you provide is resolved to a file using the File class.
URL objects are the generic way to solve this. You can use URLs to access local files but also network hosted resources. The URL class supports the file:// protocol besides http:// or https:// so you're good to go.
left(currentdb.Name,instr(1,currentdb.Name,dir(currentdb.Name))-1)
The Dir function will return only the file portion of the full path. Currentdb.Name is used here, but it could be any full path string.
For any char with ord($char) < 16 you get a HEX back which is only 1 long. You forgot to add 0 padding.
This should solve it:
<?php
function strToHex($string){
$hex = '';
for ($i=0; $i<strlen($string); $i++){
$ord = ord($string[$i]);
$hexCode = dechex($ord);
$hex .= substr('0'.$hexCode, -2);
}
return strToUpper($hex);
}
function hexToStr($hex){
$string='';
for ($i=0; $i < strlen($hex)-1; $i+=2){
$string .= chr(hexdec($hex[$i].$hex[$i+1]));
}
return $string;
}
// Tests
header('Content-Type: text/plain');
function test($expected, $actual, $success) {
if($expected !== $actual) {
echo "Expected: '$expected'\n";
echo "Actual: '$actual'\n";
echo "\n";
$success = false;
}
return $success;
}
$success = true;
$success = test('00', strToHex(hexToStr('00')), $success);
$success = test('FF', strToHex(hexToStr('FF')), $success);
$success = test('000102FF', strToHex(hexToStr('000102FF')), $success);
$success = test('???§P?§P ?§T?§?', hexToStr(strToHex('???§P?§P ?§T?§?')), $success);
echo $success ? "Success" : "\nFailed";
import pytest
class Test:
@pytest.fixture()
def setUp(self):
print("setup")
yield "resource"
print("teardown")
def test_that_depends_on_resource(self, setUp):
print("testing {}".format(setUp))
In order to run:
pytest nam_of_the_module.py -v
For a single style attribute, you can use the following syntax:
<div [style.background-color]="style1 ? 'red' : (style2 ? 'blue' : null)">
I assumed that the background color should not be set if neither style1
nor style2
is true
.
Since the question title mentions ngStyle
, here is the equivalent syntax with that directive:
<div [ngStyle]="{'background-color': style1 ? 'red' : (style2 ? 'blue' : null) }">
MongoDB aggregation not allowed to change existing data type of given fields. In this case you should create some programming code to convert string
to int
. Check below code
db.collectionName.find().forEach(function(data) {
db.collectionName.update({
"_id": data._id,
"moop": data.moop
}, {
"$set": {
"PartnerID": parseInt(data.PartnerID)
}
});
})
If your collections size more then above script will slow down the performance, for perfomace mongo provide mongo bulk operations, using mongo bulk operations also updated data type
var bulk = db.collectionName.initializeOrderedBulkOp();
var counter = 0;
db.collectionName.find().forEach(function(data) {
var updoc = {
"$set": {}
};
var myKey = "PartnerID";
updoc["$set"][myKey] = parseInt(data.PartnerID);
// queue the update
bulk.find({
"_id": data._id
}).update(updoc);
counter++;
// Drain and re-initialize every 1000 update statements
if (counter % 1000 == 0) {
bulk.execute();
bulk = db.collectionName.initializeOrderedBulkOp();
}
})
// Add the rest in the queue
if (counter % 1000 != 0) bulk.execute();
This basically reduces the amount of operations statements sent to the sever to only sending once every 1000 queued operations.
I know this is an old question, but I shall post my answer for posterity...
It depends on the system that you are building and the particular business rules in place.
I am building a moderate to large scale CRM in MongoDb, C# (Backend API), and Angular (Frontend web app) and found ObjectId utterly terrible for use in Angular Routing for selecting particular entities. Same with API Controller routing.
The suggestion above worked perfectly for my project.
db.contacts.insert({
"id":db.contacts.find().Count()+1,
"name":"John Doe",
"emails":[
"[email protected]",
"[email protected]"
],
"phone":"555111322",
"status":"Active"
});
The reason it is perfect for my case, but not all cases is that as the above comment states, if you delete 3 records from the collection, you will get collisions.
My business rules state that due to our in house SLA's, we are not allowed to delete correspondence data or clients records for longer than the potential lifespan of the application I'm writing, and therefor, I simply mark records with an enum "Status" which is either "Active" or "Deleted". You can delete something from the UI, and it will say "Contact has been deleted" but all the application has done is change the status of the contact to "Deleted" and when the app calls the respository for a list of contacts, I filter out deleted records before pushing the data to the client app.
Therefore, db.collection.find().count() + 1 is a perfect solution for me...
It won't work for everyone, but if you will not be deleting data, it works fine.
Generate a protected application for Mac or Windows from your Excel spreadsheet using OfficeProtect with either AppProtect or QuickLicense/AddLicense. There is a demonstation video called "Protect Excel Spreedsheet" at www.excelsoftware.com/videos.
Kind of an old topic, but this one might be useful for someone:
As someone mentioned above - you can use a dummy form. I had to overcome this issue some time ago. At first, I totally forgot about this HTML restriction and just added the nested forms. The result was interesting - I lost my first form from the nested. Then it turned out to be some kind of a "trick" to simply add a dummy form (that will be removed from the browser) before the actual nested forms.
In my case it looks like this:
<form id="Main">
<form></form> <!--this is the dummy one-->
<input...><form id="Nested 1> ... </form>
<input...><form id="Nested 1> ... </form>
<input...><form id="Nested 1> ... </form>
<input...><form id="Nested 1> ... </form>
......
</form>
Works fine with Chrome, Firefox, and Safari. IE up to 9 (not sure about 10) and Opera does not detect parameters in the main form. The $_REQUEST global is empty, regardless of the inputs. Inner forms seem to work fine everywhere.
Haven't tested another suggestion described here - fieldset around nested forms.
EDIT: Frameset didn't work! I simply added the Main form after the others (no more nested forms) and used jQuery's "clone" to duplicate inputs in the form on button click. Added .hide() to each of the cloned inputs to keep layout unchanged and now it works like a charm.
As simple as this...
setSize(220, 400);
setLocationRelativeTo(null);
or if you are using a frame then set the frame to
frame.setSize(220, 400);
frame.setLocationRelativeTo(null);
For clarification, from the docs:
If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen.
clear_btm=Button(master,text="Clear") #this button will delete the widgets
clear_btm["command"] = lambda one = button1, two = text1, three = entry1: clear(one,two,three) #pass the widgets
clear_btm.pack()
def clear(*widgets):
for widget in widgets:
widget.destroy() #finally we are deleting the widgets.
You can pass the necessary variables from the parent scope into the closure with the use
keyword.
For example:
DB::table('users')->where(function ($query) use ($activated) {
$query->where('activated', '=', $activated);
})->get();
More on that here.
PHP 7.4 (will be released at November 28, 2019) introduces a shorter variation of the anonymous functions called arrow functions which makes this a bit less verbose.
An example using PHP 7.4 which is functionally nearly equivalent (see the 3rd bullet point below):
DB::table('users')->where(fn($query) => $query->where('activated', '=', $activated))->get();
Differences compared to the regular syntax:
fn
keyword instead of function
.use
keyword in the latter example.void
return type when declaring them.return
keyword must be omitted.If developing with your own NuGet server, make sure the assembly versions are all the same:
[assembly: AssemblyVersion("0.2.6")]
[assembly: AssemblyFileVersion("0.2.6")]
[assembly: AssemblyInformationalVersion("0.2.6")]
In the debugger you don't need to add back slashes, the input field understands the special chars.
In java code you need to escape the special chars
I was trying to up the limit Wordpress sets on media uploads. I followed advice from some blog I’m not going to mention to raise the limit from 64MB to 2GB.
I did the following:
Created a (php.ini) file in WP ADMIN with the following integers:
upload_max_filesize = 2000MB
post_max_size = 2100MV
memory_limit = 2300MB
I immediately received this error when trying to log into my Wordpress dashboard to check if it worked:
“Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)"
The above information in this chain helped me tremendously. (Stack usually does BTW)
I modified the PHP.ini file to the following:
upload_max_filesize = 2000M
post_max_size = 2100M
memory_limit = 536870912M
The major difference was only use M, not MB, and set that memory limit high.
As soon as I saved the changed the PHP.ini file, I saved it, went to login again and the login screen reappeared.
I went in and checked media uploads, ands bang:
I haven't restarted Apache yet… but all looks good.
Thanks everyone.
i know another solution, that work with weight:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="10"
android:gravity="center_horizontal">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="7">
</LinearLayout>
</LinearLayout>
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.vehicals_details_row, parent, false);
Button deleteImageView = (Button) row.findViewById(R.id.DeleteImageView);
deleteImageView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//...
}
});
}
But you can get an issue - listView row not clickable. Solution:
android:focusable="true"
android:focusable="false"