qid
int64
1
74.6M
question
stringlengths
45
24.2k
date
stringlengths
10
10
metadata
stringlengths
101
178
response_j
stringlengths
32
23.2k
response_k
stringlengths
21
13.2k
300,008
Is there a practical reason that the roles of the primary and secondary of a simple single-phase transformer cannot be swapped? Say you have a transformer (from the old vacuum tube days) that has rated for primary 120 VAC 1 A and secondary 12.6 VAC 10 A (so there is about 0.120 kVA for this transformer). Is there any reason that one cannot take that transformer and drive the secondary with 12.6 VAC and up to 10 A and get from the primary power at 120 VAC up to 1 A? I cannot imagine a reason that, as long as the specs on the windings are kept that the roles of the primary and secondary windings of a simple power transformer cannot be swapped. But I would be happy to learn differently.
2017/04/17
['https://electronics.stackexchange.com/questions/300008', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/89489/']
You can do exactly that. Respect the maximum voltage on each winding. Transformers cannot be over-volted and still behave themselves. Due to the various small non-idealities, winding resistance and leakage inductance being the major ones, you will notice that the voltage ratio one way when under load is slightly less than the reciprocal of the ratio the other way.
A simple answer is not always right. The first problem you have is your quoted ratings. 120 V @ 1 A - 120 VA. If the load is entirely resistive, ie, there is no reactive load, then the maximum you can get out of the secondary will be about 12.6 V @ 9 A, if the efficiency is 95% - not 10 A. Brian Drummond's answer is correct. I have designed transformers and been a production manager in a transformer manufacturing plant. I know what he and I are talking about - and he's correct. There will always be losses that the primary is designed to handle. So, if you reverse feed your transformer, the previously dedicated secondary will have to cover the magnetising, copper and eddy losses. So, you will get less power out of the 120 Vac winding. However, there is one more point: the primary winding will generally have a higher insulation from the core of the transformer, than the secondary. So, you need to consider carefully the source of the power you feed into the previous secondary.
300,008
Is there a practical reason that the roles of the primary and secondary of a simple single-phase transformer cannot be swapped? Say you have a transformer (from the old vacuum tube days) that has rated for primary 120 VAC 1 A and secondary 12.6 VAC 10 A (so there is about 0.120 kVA for this transformer). Is there any reason that one cannot take that transformer and drive the secondary with 12.6 VAC and up to 10 A and get from the primary power at 120 VAC up to 1 A? I cannot imagine a reason that, as long as the specs on the windings are kept that the roles of the primary and secondary windings of a simple power transformer cannot be swapped. But I would be happy to learn differently.
2017/04/17
['https://electronics.stackexchange.com/questions/300008', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/89489/']
Yes, that'll work - with one caveat. A carefully designed transformer will take into account the internal losses, to minimise them while reducing cost. So the primary may be wound with slightly thicker wire for lower resistance than in an "ideal" transformer, or the secondary with slightly thinner wire because it only has to handle the output power, minus the losses. Driving a transformer backwards, these changes work against you, so I would de-rate it to 90% - or maybe 80% - of its rated power to be on the safe side - that is, 120V at 0.8 or 0.9A rather than 1A - and as Neil says you may also observe a minor discrepancy in the voltage ratios.
A simple answer is not always right. The first problem you have is your quoted ratings. 120 V @ 1 A - 120 VA. If the load is entirely resistive, ie, there is no reactive load, then the maximum you can get out of the secondary will be about 12.6 V @ 9 A, if the efficiency is 95% - not 10 A. Brian Drummond's answer is correct. I have designed transformers and been a production manager in a transformer manufacturing plant. I know what he and I are talking about - and he's correct. There will always be losses that the primary is designed to handle. So, if you reverse feed your transformer, the previously dedicated secondary will have to cover the magnetising, copper and eddy losses. So, you will get less power out of the 120 Vac winding. However, there is one more point: the primary winding will generally have a higher insulation from the core of the transformer, than the secondary. So, you need to consider carefully the source of the power you feed into the previous secondary.
27,641,563
I am using MyBatis 3.2.8 in a Play Framework 2.3.6 Java project. I've been struggling for several days with iterating over a list of integers that is passed to a MyBatis mapper within a complex object parameter. Here is my setup: I have a class called EventFilter in EventFilter.java: ``` public class EventFilter { private String beginDate; private String endDate; private List<Integer> closestCountry; private List<Integer> territorialWaterStatus; private List<Integer> vesselCountry; private String closestCountryInClause; private String territorialWaterStatusInClause; private String vesselCountryInClause; public EventFilter() { } public EventFilter(JsonNode jsonNode){ this.beginDate = jsonNode.get("beginDate").asText(); this.endDate = jsonNode.get("endDate").asText(); this.closestCountry = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get("closestCountry")); this.territorialWaterStatus = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get("territorialWaterStatus")); this.vesselCountry = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get("vesselCountry")); } public String getBeginDate() { return beginDate; } public void setBeginDate(String beginDate) { this.beginDate = beginDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public List<Integer> getTerritorialWaterStatus() { if(this.territorialWaterStatus.size() > 0) { return territorialWaterStatus; } else { return null; } } public void setTerritorialWaterStatus(List<Integer> territorialWaterStatus) { this.territorialWaterStatus = territorialWaterStatus; } public List<Integer> getClosestCountry() { if(this.closestCountry.size() > 0) { return closestCountry; } else { return null; } } public void setClosestCountry(List<Integer> closestCountry) { this.closestCountry = closestCountry; } public List<Integer> getVesselCountry() { if(this.vesselCountry.size() > 0) { return vesselCountry; } else { return null; } } public void setVesselCountry(List<Integer> vesselCountry) { this.vesselCountry = vesselCountry; } ``` } This is referenced as a type alias in my mybatis config file: ``` <configuration> <typeAliases> <typeAlias type="models.Event" alias="Event"/> <typeAlias type="models.EventFilter" alias="EventFilter"/> <typeAlias type="models.Country" alias="Country"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="org.postgresql.Driver"/> <property name="url" value="jdbc:postgresql://localhost:5432/mpmap"/> <property name="username" value="postgres"/> <property name="password" value="dbpw"/> </dataSource> </environment> </environments> <mappers> <mapper resource="EventMapper.xml"/> </mappers> </configuration> ``` I have a mapper that takes an EventFilter object as its parameter. It should then check if the beginDate, endDate, closestCountry, vesselCountry, and territorialWaterStatus are set. If they are it uses them for the WHERE clause: ``` <select id="getEventsWithFilter" resultType="Event" resultMap="EventResult"> SELECT ev.id, to_char(ev.occurred_on, 'YYYY-MM-DD') AS occurred_on_date, to_char(ev.occurred_on, 'HH24:MI:SS') AS occurred_on_time, ST_X(ev.location) AS longitude, ST_Y(ev.location) AS latitude, COALESCE(co01.name, 'Unspecified') AS closest_country, COALESCE(co02.name, 'Unspecified') AS territorial_water_status, COALESCE(co03.name, 'Unspecified') AS vessel_flag_country FROM event AS ev LEFT JOIN country AS co01 ON co01.cow_id = ev.location_closest_country_id LEFT JOIN country AS co02 ON co02.cow_id = ev.location_water_status_country_id LEFT JOIN country AS co03 ON co03.cow_id = ev.vessel_flag_country_id <where> <if test="#{eventFilter.beginDate} != null and #{eventFilter.endDate} != null"> ev.occurred_on &gt;= #{eventFilter.beginDate}::timestamp AND ev.occurred_on &lt;= #{eventFilter.endDate}::timestamp </if> <if test="#{eventFilter.closestCountry} != null"> AND ev.location_closest_country_id IN <foreach item="id" index="index" collection="#{eventFilter.closestCountry}" open="(" separator="," close=")"> #{id} </foreach> </if> <if test="#{eventFilter.territorialWaterStatus} != null"> AND ev.location_water_status_country_id IN <foreach item="id" index="index" collection="#{eventFilter.territorialWaterStatus}" open="(" separator="," close=")"> #{id} </foreach> </if> <if test="#{eventFilter.vesselCountry} != null"> AND ev.vessel_flag_country_id IN <foreach item="id" index="index" collection="#{eventFilter.vesselCountry}" open="(" separator="," close=")"> #{id} </foreach> </if> </where> ORDER BY ev.occurred_on ASC; </select> ``` I have the mapper linked into an interface as follows: ``` public List<Event> getEventsWithFilter(@Param("eventFilter") EventFilter eventFilter); ``` And I am calling it with a MybatisMapper helper class that generates my session as follows: ``` public static List<Event> getEvents(EventFilter eventFilter) { MybatisMapper mapper = new MybatisMapper(); SqlSession session = mapper.getSession(); EventMapper eventMapper = session.getMapper(EventMapper.class); List<Event> events; List<Integer> li = eventFilter.getClosestCountry(); try { events = eventMapper.getEventsWithFilter(eventFilter); } finally { session.close(); } return events; } ``` **The Problem(s):** The beginDate and endDate work completely fine by themselves. But I'm having the following problems with the integer lists: 1. The if statement checking if the list is null seems to be getting ignored, or evaluating to true when it should be false. 2. The integer lists are appearing to be passed as null into the IN clauses. 3. If I comment out the integer list IN clauses, and just to beginDate and endDate, it works completely fine. However, if I leave the integer list IN clauses, the query doesn't fail, but it returns an empty set, as if to say "WHERE column IN ()". Here is the console logging printed by Play and Mybatis when the mapper/query are executed, along with the EventFilter printing its contents. They're a little lengthy so I put them in pastebin: * When I pass three countries for each of the three integer lists: <http://pastebin.com/aWcXyikh> * When I pass only the beginDate and endDate: <http://pastebin.com/CeCv256g> This became a little longer than I wanted it to, but thanks in advance for any help or suggestions.
2014/12/24
['https://Stackoverflow.com/questions/27641563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1695454/']
I finally got it working. The only thing I ended up having to change was addressing the parameter lists in my XML mapper without the surrounding curly braces. So instead of: ``` <if test="#{eventFilter.closestCountry} != null"> AND ev.location_closest_country_id IN <foreach item="id" index="index" collection="#{eventFilter.closestCountry}" open="(" separator="," close=")"> #{id} </foreach> </if> ``` It should be: ``` <if test="eventFilter.closestCountry != null"> AND ev.location_closest_country_id IN <foreach item="id" index="index" collection="eventFilter.closestCountry" open="(" separator="," close=")"> #{id} </foreach> </if> ``` Which is odd, because addressing strings in the passed object works with either method - i.e. #{eventFilter.beginDate} is the same as eventFilter.beginDate. A very subtle difference, but I hope it helps someone save some time in the future.
try this ``` <if test="eventFilter.closestCountry != null"> AND ev.location_closest_country_id IN <foreach item="id" index="index" collection="eventFilter.closestCountry" open="(" separator="," close=")"> ${id} </foreach> </if> ```
27,641,563
I am using MyBatis 3.2.8 in a Play Framework 2.3.6 Java project. I've been struggling for several days with iterating over a list of integers that is passed to a MyBatis mapper within a complex object parameter. Here is my setup: I have a class called EventFilter in EventFilter.java: ``` public class EventFilter { private String beginDate; private String endDate; private List<Integer> closestCountry; private List<Integer> territorialWaterStatus; private List<Integer> vesselCountry; private String closestCountryInClause; private String territorialWaterStatusInClause; private String vesselCountryInClause; public EventFilter() { } public EventFilter(JsonNode jsonNode){ this.beginDate = jsonNode.get("beginDate").asText(); this.endDate = jsonNode.get("endDate").asText(); this.closestCountry = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get("closestCountry")); this.territorialWaterStatus = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get("territorialWaterStatus")); this.vesselCountry = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get("vesselCountry")); } public String getBeginDate() { return beginDate; } public void setBeginDate(String beginDate) { this.beginDate = beginDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public List<Integer> getTerritorialWaterStatus() { if(this.territorialWaterStatus.size() > 0) { return territorialWaterStatus; } else { return null; } } public void setTerritorialWaterStatus(List<Integer> territorialWaterStatus) { this.territorialWaterStatus = territorialWaterStatus; } public List<Integer> getClosestCountry() { if(this.closestCountry.size() > 0) { return closestCountry; } else { return null; } } public void setClosestCountry(List<Integer> closestCountry) { this.closestCountry = closestCountry; } public List<Integer> getVesselCountry() { if(this.vesselCountry.size() > 0) { return vesselCountry; } else { return null; } } public void setVesselCountry(List<Integer> vesselCountry) { this.vesselCountry = vesselCountry; } ``` } This is referenced as a type alias in my mybatis config file: ``` <configuration> <typeAliases> <typeAlias type="models.Event" alias="Event"/> <typeAlias type="models.EventFilter" alias="EventFilter"/> <typeAlias type="models.Country" alias="Country"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="org.postgresql.Driver"/> <property name="url" value="jdbc:postgresql://localhost:5432/mpmap"/> <property name="username" value="postgres"/> <property name="password" value="dbpw"/> </dataSource> </environment> </environments> <mappers> <mapper resource="EventMapper.xml"/> </mappers> </configuration> ``` I have a mapper that takes an EventFilter object as its parameter. It should then check if the beginDate, endDate, closestCountry, vesselCountry, and territorialWaterStatus are set. If they are it uses them for the WHERE clause: ``` <select id="getEventsWithFilter" resultType="Event" resultMap="EventResult"> SELECT ev.id, to_char(ev.occurred_on, 'YYYY-MM-DD') AS occurred_on_date, to_char(ev.occurred_on, 'HH24:MI:SS') AS occurred_on_time, ST_X(ev.location) AS longitude, ST_Y(ev.location) AS latitude, COALESCE(co01.name, 'Unspecified') AS closest_country, COALESCE(co02.name, 'Unspecified') AS territorial_water_status, COALESCE(co03.name, 'Unspecified') AS vessel_flag_country FROM event AS ev LEFT JOIN country AS co01 ON co01.cow_id = ev.location_closest_country_id LEFT JOIN country AS co02 ON co02.cow_id = ev.location_water_status_country_id LEFT JOIN country AS co03 ON co03.cow_id = ev.vessel_flag_country_id <where> <if test="#{eventFilter.beginDate} != null and #{eventFilter.endDate} != null"> ev.occurred_on &gt;= #{eventFilter.beginDate}::timestamp AND ev.occurred_on &lt;= #{eventFilter.endDate}::timestamp </if> <if test="#{eventFilter.closestCountry} != null"> AND ev.location_closest_country_id IN <foreach item="id" index="index" collection="#{eventFilter.closestCountry}" open="(" separator="," close=")"> #{id} </foreach> </if> <if test="#{eventFilter.territorialWaterStatus} != null"> AND ev.location_water_status_country_id IN <foreach item="id" index="index" collection="#{eventFilter.territorialWaterStatus}" open="(" separator="," close=")"> #{id} </foreach> </if> <if test="#{eventFilter.vesselCountry} != null"> AND ev.vessel_flag_country_id IN <foreach item="id" index="index" collection="#{eventFilter.vesselCountry}" open="(" separator="," close=")"> #{id} </foreach> </if> </where> ORDER BY ev.occurred_on ASC; </select> ``` I have the mapper linked into an interface as follows: ``` public List<Event> getEventsWithFilter(@Param("eventFilter") EventFilter eventFilter); ``` And I am calling it with a MybatisMapper helper class that generates my session as follows: ``` public static List<Event> getEvents(EventFilter eventFilter) { MybatisMapper mapper = new MybatisMapper(); SqlSession session = mapper.getSession(); EventMapper eventMapper = session.getMapper(EventMapper.class); List<Event> events; List<Integer> li = eventFilter.getClosestCountry(); try { events = eventMapper.getEventsWithFilter(eventFilter); } finally { session.close(); } return events; } ``` **The Problem(s):** The beginDate and endDate work completely fine by themselves. But I'm having the following problems with the integer lists: 1. The if statement checking if the list is null seems to be getting ignored, or evaluating to true when it should be false. 2. The integer lists are appearing to be passed as null into the IN clauses. 3. If I comment out the integer list IN clauses, and just to beginDate and endDate, it works completely fine. However, if I leave the integer list IN clauses, the query doesn't fail, but it returns an empty set, as if to say "WHERE column IN ()". Here is the console logging printed by Play and Mybatis when the mapper/query are executed, along with the EventFilter printing its contents. They're a little lengthy so I put them in pastebin: * When I pass three countries for each of the three integer lists: <http://pastebin.com/aWcXyikh> * When I pass only the beginDate and endDate: <http://pastebin.com/CeCv256g> This became a little longer than I wanted it to, but thanks in advance for any help or suggestions.
2014/12/24
['https://Stackoverflow.com/questions/27641563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1695454/']
I finally got it working. The only thing I ended up having to change was addressing the parameter lists in my XML mapper without the surrounding curly braces. So instead of: ``` <if test="#{eventFilter.closestCountry} != null"> AND ev.location_closest_country_id IN <foreach item="id" index="index" collection="#{eventFilter.closestCountry}" open="(" separator="," close=")"> #{id} </foreach> </if> ``` It should be: ``` <if test="eventFilter.closestCountry != null"> AND ev.location_closest_country_id IN <foreach item="id" index="index" collection="eventFilter.closestCountry" open="(" separator="," close=")"> #{id} </foreach> </if> ``` Which is odd, because addressing strings in the passed object works with either method - i.e. #{eventFilter.beginDate} is the same as eventFilter.beginDate. A very subtle difference, but I hope it helps someone save some time in the future.
I'm using MyBatis v. 3.4.6. My case: ``` @Mapper public interface CorsoMapper { List<CorsoEntity> elenco(Filtro filtro); } public class Filtro implements Serializable { private static final long serialVersionUID = -8357822764110641974L; private String codice; private List<String> codici; public String getCodice() { return codice; } public void setCodice(String codice) { this.codice = codice; } public List<String> getCodici() { return codici; } public void setCodici(List<String> codici) { this.codici = codici; } } ``` SQL: ``` <select id="elencoCorsi" parameterType="it.blabla.Filtro" resultMap="corsoMap"> AND CODICI IN <foreach item="c" collection="codici" open="(" separator="," close=")"> #{c} </foreach> </select> ``` It works without using "index" attribute.
27,641,563
I am using MyBatis 3.2.8 in a Play Framework 2.3.6 Java project. I've been struggling for several days with iterating over a list of integers that is passed to a MyBatis mapper within a complex object parameter. Here is my setup: I have a class called EventFilter in EventFilter.java: ``` public class EventFilter { private String beginDate; private String endDate; private List<Integer> closestCountry; private List<Integer> territorialWaterStatus; private List<Integer> vesselCountry; private String closestCountryInClause; private String territorialWaterStatusInClause; private String vesselCountryInClause; public EventFilter() { } public EventFilter(JsonNode jsonNode){ this.beginDate = jsonNode.get("beginDate").asText(); this.endDate = jsonNode.get("endDate").asText(); this.closestCountry = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get("closestCountry")); this.territorialWaterStatus = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get("territorialWaterStatus")); this.vesselCountry = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get("vesselCountry")); } public String getBeginDate() { return beginDate; } public void setBeginDate(String beginDate) { this.beginDate = beginDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public List<Integer> getTerritorialWaterStatus() { if(this.territorialWaterStatus.size() > 0) { return territorialWaterStatus; } else { return null; } } public void setTerritorialWaterStatus(List<Integer> territorialWaterStatus) { this.territorialWaterStatus = territorialWaterStatus; } public List<Integer> getClosestCountry() { if(this.closestCountry.size() > 0) { return closestCountry; } else { return null; } } public void setClosestCountry(List<Integer> closestCountry) { this.closestCountry = closestCountry; } public List<Integer> getVesselCountry() { if(this.vesselCountry.size() > 0) { return vesselCountry; } else { return null; } } public void setVesselCountry(List<Integer> vesselCountry) { this.vesselCountry = vesselCountry; } ``` } This is referenced as a type alias in my mybatis config file: ``` <configuration> <typeAliases> <typeAlias type="models.Event" alias="Event"/> <typeAlias type="models.EventFilter" alias="EventFilter"/> <typeAlias type="models.Country" alias="Country"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="org.postgresql.Driver"/> <property name="url" value="jdbc:postgresql://localhost:5432/mpmap"/> <property name="username" value="postgres"/> <property name="password" value="dbpw"/> </dataSource> </environment> </environments> <mappers> <mapper resource="EventMapper.xml"/> </mappers> </configuration> ``` I have a mapper that takes an EventFilter object as its parameter. It should then check if the beginDate, endDate, closestCountry, vesselCountry, and territorialWaterStatus are set. If they are it uses them for the WHERE clause: ``` <select id="getEventsWithFilter" resultType="Event" resultMap="EventResult"> SELECT ev.id, to_char(ev.occurred_on, 'YYYY-MM-DD') AS occurred_on_date, to_char(ev.occurred_on, 'HH24:MI:SS') AS occurred_on_time, ST_X(ev.location) AS longitude, ST_Y(ev.location) AS latitude, COALESCE(co01.name, 'Unspecified') AS closest_country, COALESCE(co02.name, 'Unspecified') AS territorial_water_status, COALESCE(co03.name, 'Unspecified') AS vessel_flag_country FROM event AS ev LEFT JOIN country AS co01 ON co01.cow_id = ev.location_closest_country_id LEFT JOIN country AS co02 ON co02.cow_id = ev.location_water_status_country_id LEFT JOIN country AS co03 ON co03.cow_id = ev.vessel_flag_country_id <where> <if test="#{eventFilter.beginDate} != null and #{eventFilter.endDate} != null"> ev.occurred_on &gt;= #{eventFilter.beginDate}::timestamp AND ev.occurred_on &lt;= #{eventFilter.endDate}::timestamp </if> <if test="#{eventFilter.closestCountry} != null"> AND ev.location_closest_country_id IN <foreach item="id" index="index" collection="#{eventFilter.closestCountry}" open="(" separator="," close=")"> #{id} </foreach> </if> <if test="#{eventFilter.territorialWaterStatus} != null"> AND ev.location_water_status_country_id IN <foreach item="id" index="index" collection="#{eventFilter.territorialWaterStatus}" open="(" separator="," close=")"> #{id} </foreach> </if> <if test="#{eventFilter.vesselCountry} != null"> AND ev.vessel_flag_country_id IN <foreach item="id" index="index" collection="#{eventFilter.vesselCountry}" open="(" separator="," close=")"> #{id} </foreach> </if> </where> ORDER BY ev.occurred_on ASC; </select> ``` I have the mapper linked into an interface as follows: ``` public List<Event> getEventsWithFilter(@Param("eventFilter") EventFilter eventFilter); ``` And I am calling it with a MybatisMapper helper class that generates my session as follows: ``` public static List<Event> getEvents(EventFilter eventFilter) { MybatisMapper mapper = new MybatisMapper(); SqlSession session = mapper.getSession(); EventMapper eventMapper = session.getMapper(EventMapper.class); List<Event> events; List<Integer> li = eventFilter.getClosestCountry(); try { events = eventMapper.getEventsWithFilter(eventFilter); } finally { session.close(); } return events; } ``` **The Problem(s):** The beginDate and endDate work completely fine by themselves. But I'm having the following problems with the integer lists: 1. The if statement checking if the list is null seems to be getting ignored, or evaluating to true when it should be false. 2. The integer lists are appearing to be passed as null into the IN clauses. 3. If I comment out the integer list IN clauses, and just to beginDate and endDate, it works completely fine. However, if I leave the integer list IN clauses, the query doesn't fail, but it returns an empty set, as if to say "WHERE column IN ()". Here is the console logging printed by Play and Mybatis when the mapper/query are executed, along with the EventFilter printing its contents. They're a little lengthy so I put them in pastebin: * When I pass three countries for each of the three integer lists: <http://pastebin.com/aWcXyikh> * When I pass only the beginDate and endDate: <http://pastebin.com/CeCv256g> This became a little longer than I wanted it to, but thanks in advance for any help or suggestions.
2014/12/24
['https://Stackoverflow.com/questions/27641563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1695454/']
try this ``` <if test="eventFilter.closestCountry != null"> AND ev.location_closest_country_id IN <foreach item="id" index="index" collection="eventFilter.closestCountry" open="(" separator="," close=")"> ${id} </foreach> </if> ```
I'm using MyBatis v. 3.4.6. My case: ``` @Mapper public interface CorsoMapper { List<CorsoEntity> elenco(Filtro filtro); } public class Filtro implements Serializable { private static final long serialVersionUID = -8357822764110641974L; private String codice; private List<String> codici; public String getCodice() { return codice; } public void setCodice(String codice) { this.codice = codice; } public List<String> getCodici() { return codici; } public void setCodici(List<String> codici) { this.codici = codici; } } ``` SQL: ``` <select id="elencoCorsi" parameterType="it.blabla.Filtro" resultMap="corsoMap"> AND CODICI IN <foreach item="c" collection="codici" open="(" separator="," close=")"> #{c} </foreach> </select> ``` It works without using "index" attribute.
53,867,961
There is a GlobalSign CA. In most cases its root certificate is already exists in the Windows Certificates storage. But sometimes (especially on old Windows versions) the storage doesn't contain the certificate. I need to check if the certificate exists and import it if does not. I exported the certificate to a file and imported it using the code below: ``` public void ImportCertificate(StoreName storeName, StoreLocation location, byte[] certificateData) { X509Store x509Store = new X509Store(storeName, location); X509Certificate2 certificate = new X509Certificate2(certificateData); x509Store.Open(OpenFlags.ReadWrite); x509Store.Add(certificate); x509Store.Close(); } ``` The code adds the certificate but all certificate purposes are checked: [![Result](https://i.stack.imgur.com/NfPuo.png)](https://i.stack.imgur.com/NfPuo.png) I don't want to add extra purposes to the certificate just want to set those ones which have other root CAs like below: [![Expect](https://i.stack.imgur.com/tAXRR.png)](https://i.stack.imgur.com/tAXRR.png) How to do it programatically?
2018/12/20
['https://Stackoverflow.com/questions/53867961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4675884/']
DEPRECATED: As mentioned on this answer ([How can I run commands in a running container in AWS ECS using Fargate](https://stackoverflow.com/questions/51570928/how-can-i-run-commands-in-a-running-container-in-aws-ecs-using-fargate)) you cannot do it due to the fact AWS doesn't give you access to the underlying infrastructure. UPDATE: Pierre below mentions an announcement from AWS allowing to do just that.
As i know and having experience on ECS you are not allowed to do it. aws does not give you access to the underlying resources. if you are using fargate + EC2 Configuration then also it is not to access EC2.
53,867,961
There is a GlobalSign CA. In most cases its root certificate is already exists in the Windows Certificates storage. But sometimes (especially on old Windows versions) the storage doesn't contain the certificate. I need to check if the certificate exists and import it if does not. I exported the certificate to a file and imported it using the code below: ``` public void ImportCertificate(StoreName storeName, StoreLocation location, byte[] certificateData) { X509Store x509Store = new X509Store(storeName, location); X509Certificate2 certificate = new X509Certificate2(certificateData); x509Store.Open(OpenFlags.ReadWrite); x509Store.Add(certificate); x509Store.Close(); } ``` The code adds the certificate but all certificate purposes are checked: [![Result](https://i.stack.imgur.com/NfPuo.png)](https://i.stack.imgur.com/NfPuo.png) I don't want to add extra purposes to the certificate just want to set those ones which have other root CAs like below: [![Expect](https://i.stack.imgur.com/tAXRR.png)](https://i.stack.imgur.com/tAXRR.png) How to do it programatically?
2018/12/20
['https://Stackoverflow.com/questions/53867961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4675884/']
DEPRECATED: As mentioned on this answer ([How can I run commands in a running container in AWS ECS using Fargate](https://stackoverflow.com/questions/51570928/how-can-i-run-commands-in-a-running-container-in-aws-ecs-using-fargate)) you cannot do it due to the fact AWS doesn't give you access to the underlying infrastructure. UPDATE: Pierre below mentions an announcement from AWS allowing to do just that.
I don't know if this is what you are trying to achieve, but if you want you can run a command on a new container that you instantiate for the occasion through a CloudWatch Rule It will be enough to create a new task definition and indicate the command to execute (in the example executing a Laravel command) ``` ECSReputationSchedulerTask: Type: AWS::ECS::TaskDefinition Properties: Cpu: 256 ExecutionRoleArn: !ImportValue ECSTaskExecutionRole Family: TaskDefinitionFamily Memory: 512 NetworkMode: awsvpc RequiresCompatibilities: - FARGATE ContainerDefinitions: - Command: - "php" - "/home/application/artisan" - "execute:operation" Name: 'MySchedulerContainer' ... ``` and then reference it into a CloudWatch rule (unfortunately this can't be done via CloudFormation yet)
53,867,961
There is a GlobalSign CA. In most cases its root certificate is already exists in the Windows Certificates storage. But sometimes (especially on old Windows versions) the storage doesn't contain the certificate. I need to check if the certificate exists and import it if does not. I exported the certificate to a file and imported it using the code below: ``` public void ImportCertificate(StoreName storeName, StoreLocation location, byte[] certificateData) { X509Store x509Store = new X509Store(storeName, location); X509Certificate2 certificate = new X509Certificate2(certificateData); x509Store.Open(OpenFlags.ReadWrite); x509Store.Add(certificate); x509Store.Close(); } ``` The code adds the certificate but all certificate purposes are checked: [![Result](https://i.stack.imgur.com/NfPuo.png)](https://i.stack.imgur.com/NfPuo.png) I don't want to add extra purposes to the certificate just want to set those ones which have other root CAs like below: [![Expect](https://i.stack.imgur.com/tAXRR.png)](https://i.stack.imgur.com/tAXRR.png) How to do it programatically?
2018/12/20
['https://Stackoverflow.com/questions/53867961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4675884/']
DEPRECATED: As mentioned on this answer ([How can I run commands in a running container in AWS ECS using Fargate](https://stackoverflow.com/questions/51570928/how-can-i-run-commands-in-a-running-container-in-aws-ecs-using-fargate)) you cannot do it due to the fact AWS doesn't give you access to the underlying infrastructure. UPDATE: Pierre below mentions an announcement from AWS allowing to do just that.
You may be able to script your container to execute a cli command, but you cannot ssh into the container though. If you can invoke a `.sh` file from the `CMD` command in the Dockerfile, the cli command will get executed as long as you have aws-cli installed on the docker image. In the Dockerfile make sure to run `pip3 install awscli --upgrade --user` before you invoke your script that contains cli commands. As an alternative, you can use [boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) for Python or the [AWS SDK for JavaScript](https://docs.amazonaws.cn/AWSJavaScriptSDK/latest/), which both have comprehensive documentation and enable you to run all the commands you could have run via cli
53,867,961
There is a GlobalSign CA. In most cases its root certificate is already exists in the Windows Certificates storage. But sometimes (especially on old Windows versions) the storage doesn't contain the certificate. I need to check if the certificate exists and import it if does not. I exported the certificate to a file and imported it using the code below: ``` public void ImportCertificate(StoreName storeName, StoreLocation location, byte[] certificateData) { X509Store x509Store = new X509Store(storeName, location); X509Certificate2 certificate = new X509Certificate2(certificateData); x509Store.Open(OpenFlags.ReadWrite); x509Store.Add(certificate); x509Store.Close(); } ``` The code adds the certificate but all certificate purposes are checked: [![Result](https://i.stack.imgur.com/NfPuo.png)](https://i.stack.imgur.com/NfPuo.png) I don't want to add extra purposes to the certificate just want to set those ones which have other root CAs like below: [![Expect](https://i.stack.imgur.com/tAXRR.png)](https://i.stack.imgur.com/tAXRR.png) How to do it programatically?
2018/12/20
['https://Stackoverflow.com/questions/53867961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4675884/']
As i know and having experience on ECS you are not allowed to do it. aws does not give you access to the underlying resources. if you are using fargate + EC2 Configuration then also it is not to access EC2.
I don't know if this is what you are trying to achieve, but if you want you can run a command on a new container that you instantiate for the occasion through a CloudWatch Rule It will be enough to create a new task definition and indicate the command to execute (in the example executing a Laravel command) ``` ECSReputationSchedulerTask: Type: AWS::ECS::TaskDefinition Properties: Cpu: 256 ExecutionRoleArn: !ImportValue ECSTaskExecutionRole Family: TaskDefinitionFamily Memory: 512 NetworkMode: awsvpc RequiresCompatibilities: - FARGATE ContainerDefinitions: - Command: - "php" - "/home/application/artisan" - "execute:operation" Name: 'MySchedulerContainer' ... ``` and then reference it into a CloudWatch rule (unfortunately this can't be done via CloudFormation yet)
53,867,961
There is a GlobalSign CA. In most cases its root certificate is already exists in the Windows Certificates storage. But sometimes (especially on old Windows versions) the storage doesn't contain the certificate. I need to check if the certificate exists and import it if does not. I exported the certificate to a file and imported it using the code below: ``` public void ImportCertificate(StoreName storeName, StoreLocation location, byte[] certificateData) { X509Store x509Store = new X509Store(storeName, location); X509Certificate2 certificate = new X509Certificate2(certificateData); x509Store.Open(OpenFlags.ReadWrite); x509Store.Add(certificate); x509Store.Close(); } ``` The code adds the certificate but all certificate purposes are checked: [![Result](https://i.stack.imgur.com/NfPuo.png)](https://i.stack.imgur.com/NfPuo.png) I don't want to add extra purposes to the certificate just want to set those ones which have other root CAs like below: [![Expect](https://i.stack.imgur.com/tAXRR.png)](https://i.stack.imgur.com/tAXRR.png) How to do it programatically?
2018/12/20
['https://Stackoverflow.com/questions/53867961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4675884/']
As i know and having experience on ECS you are not allowed to do it. aws does not give you access to the underlying resources. if you are using fargate + EC2 Configuration then also it is not to access EC2.
You may be able to script your container to execute a cli command, but you cannot ssh into the container though. If you can invoke a `.sh` file from the `CMD` command in the Dockerfile, the cli command will get executed as long as you have aws-cli installed on the docker image. In the Dockerfile make sure to run `pip3 install awscli --upgrade --user` before you invoke your script that contains cli commands. As an alternative, you can use [boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) for Python or the [AWS SDK for JavaScript](https://docs.amazonaws.cn/AWSJavaScriptSDK/latest/), which both have comprehensive documentation and enable you to run all the commands you could have run via cli
53,867,961
There is a GlobalSign CA. In most cases its root certificate is already exists in the Windows Certificates storage. But sometimes (especially on old Windows versions) the storage doesn't contain the certificate. I need to check if the certificate exists and import it if does not. I exported the certificate to a file and imported it using the code below: ``` public void ImportCertificate(StoreName storeName, StoreLocation location, byte[] certificateData) { X509Store x509Store = new X509Store(storeName, location); X509Certificate2 certificate = new X509Certificate2(certificateData); x509Store.Open(OpenFlags.ReadWrite); x509Store.Add(certificate); x509Store.Close(); } ``` The code adds the certificate but all certificate purposes are checked: [![Result](https://i.stack.imgur.com/NfPuo.png)](https://i.stack.imgur.com/NfPuo.png) I don't want to add extra purposes to the certificate just want to set those ones which have other root CAs like below: [![Expect](https://i.stack.imgur.com/tAXRR.png)](https://i.stack.imgur.com/tAXRR.png) How to do it programatically?
2018/12/20
['https://Stackoverflow.com/questions/53867961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4675884/']
AWS have now launched Amazon ECS Exec, which allows you to directly interact with containers: <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-exec.html>.
As i know and having experience on ECS you are not allowed to do it. aws does not give you access to the underlying resources. if you are using fargate + EC2 Configuration then also it is not to access EC2.
53,867,961
There is a GlobalSign CA. In most cases its root certificate is already exists in the Windows Certificates storage. But sometimes (especially on old Windows versions) the storage doesn't contain the certificate. I need to check if the certificate exists and import it if does not. I exported the certificate to a file and imported it using the code below: ``` public void ImportCertificate(StoreName storeName, StoreLocation location, byte[] certificateData) { X509Store x509Store = new X509Store(storeName, location); X509Certificate2 certificate = new X509Certificate2(certificateData); x509Store.Open(OpenFlags.ReadWrite); x509Store.Add(certificate); x509Store.Close(); } ``` The code adds the certificate but all certificate purposes are checked: [![Result](https://i.stack.imgur.com/NfPuo.png)](https://i.stack.imgur.com/NfPuo.png) I don't want to add extra purposes to the certificate just want to set those ones which have other root CAs like below: [![Expect](https://i.stack.imgur.com/tAXRR.png)](https://i.stack.imgur.com/tAXRR.png) How to do it programatically?
2018/12/20
['https://Stackoverflow.com/questions/53867961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4675884/']
AWS have now launched Amazon ECS Exec, which allows you to directly interact with containers: <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-exec.html>.
I don't know if this is what you are trying to achieve, but if you want you can run a command on a new container that you instantiate for the occasion through a CloudWatch Rule It will be enough to create a new task definition and indicate the command to execute (in the example executing a Laravel command) ``` ECSReputationSchedulerTask: Type: AWS::ECS::TaskDefinition Properties: Cpu: 256 ExecutionRoleArn: !ImportValue ECSTaskExecutionRole Family: TaskDefinitionFamily Memory: 512 NetworkMode: awsvpc RequiresCompatibilities: - FARGATE ContainerDefinitions: - Command: - "php" - "/home/application/artisan" - "execute:operation" Name: 'MySchedulerContainer' ... ``` and then reference it into a CloudWatch rule (unfortunately this can't be done via CloudFormation yet)
53,867,961
There is a GlobalSign CA. In most cases its root certificate is already exists in the Windows Certificates storage. But sometimes (especially on old Windows versions) the storage doesn't contain the certificate. I need to check if the certificate exists and import it if does not. I exported the certificate to a file and imported it using the code below: ``` public void ImportCertificate(StoreName storeName, StoreLocation location, byte[] certificateData) { X509Store x509Store = new X509Store(storeName, location); X509Certificate2 certificate = new X509Certificate2(certificateData); x509Store.Open(OpenFlags.ReadWrite); x509Store.Add(certificate); x509Store.Close(); } ``` The code adds the certificate but all certificate purposes are checked: [![Result](https://i.stack.imgur.com/NfPuo.png)](https://i.stack.imgur.com/NfPuo.png) I don't want to add extra purposes to the certificate just want to set those ones which have other root CAs like below: [![Expect](https://i.stack.imgur.com/tAXRR.png)](https://i.stack.imgur.com/tAXRR.png) How to do it programatically?
2018/12/20
['https://Stackoverflow.com/questions/53867961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4675884/']
AWS have now launched Amazon ECS Exec, which allows you to directly interact with containers: <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-exec.html>.
You may be able to script your container to execute a cli command, but you cannot ssh into the container though. If you can invoke a `.sh` file from the `CMD` command in the Dockerfile, the cli command will get executed as long as you have aws-cli installed on the docker image. In the Dockerfile make sure to run `pip3 install awscli --upgrade --user` before you invoke your script that contains cli commands. As an alternative, you can use [boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) for Python or the [AWS SDK for JavaScript](https://docs.amazonaws.cn/AWSJavaScriptSDK/latest/), which both have comprehensive documentation and enable you to run all the commands you could have run via cli
31,441,040
I'm trying to retain the selected value of a dropdownlist once the user change the dropdownlist item but its not working as expected what I wanted is to retain the selected item in the dropdownlist but its it defaulted to the `Select Company` everytime i select the item from dropdownlist, once the user change it postback the page (i know there is no postback in the MVC) What I'm doing wrong here? ``` <div class="form-group"> @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @id = "form_dropdown" })) { @Html.DropDownListFor(m => m.ListOfCompanies, new SelectList((System.Collections.IEnumerable)Model.ListOfCompanies, "Value", "Text"), "Select Company", new { @class = "form-control", Name = "sel" }) } ``` ``` [HttpPost] public ActionResult Index(string sel) { var vModel = new EmployeeViewModel(); vModel = _db.GetEmployee.ToList(); //load list of companies: var company = _db.LoadComapny.ToList(); IEnumerable<SelectListItem> result = model.Select(b => new SelectListItem { Value = b.Value, Text = b.Text, Selected = b.Text == sel }).ToList(); vModel.ListOfCompanies = company; vModel.SELECTED_COMPANY = sel; return View(vModel); } ``` Model: ``` public class EmployeeViewModel { public IEnumerable<SelectListItem> ListOfCompanies { get; set; } public string SELECTED_COMPANY { get; set; } //other props } ```
2015/07/15
['https://Stackoverflow.com/questions/31441040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/275390/']
As I wrote in the comment section, it's really unclear to me what you're asking. However, looking at your code examples, it seems to me that `trait A` isn't really required. You can use the types that already come with the Scala SDK: ``` object B extends (()=>Unit) { def apply() { /* implementation */ } } ``` Or, as a variant: ``` object B { val aType:()=>Unit = {() => /* implementation */ } } ``` In the first case, you can access the singleton instance with `B`, in the second case with `B.aType`. In the second case, no explicit declaration of the `apply` method is needed. Pick what you like. The essential message is: You don't need a trait if you just define one simple method. That's what Scala functions are for. The list type might look like this: ``` private val aList:ListBuffer[()=>Unit] = ??? ``` (By the way: Why not declare it as `Seq[()=>Unit]`? Is it important to the caller that it is a `ListBuffer` and not some other kind of sequence?) Your worker might then look like this: ``` abstract class Worker { def aType:()=>Unit // no need for the `get` prefix here, or the empty parameter list def do() {aType()} } ``` Note that now the `Worker` type has become a class that offers a method that invokes a function. So, there is really no need to have a `Worker` class. You can just take the function (`aType`) directly and invoke it, just so. If you always want to call the implementation in `object B`, well - just do that then. There is no need to wrap the call in instances of other types. Your example class `B` just forwards the call to the `B` object, which is really unnecessary. There is no need to even create an instance of `B`. It does have the private member variable `creator`, but since it's never used, it will never be accessed in any way. So, I would recommend to completely remove the `class B`. All you need is the type `()=>Unit`, which is exactly what you need: A function that takes no parameters and returns nothing. If you get tired of writing `()=>Unit` all the time, you can define a type alias, for example inside the package object. Here is my recommentation: ``` type SideEffect = ()=>Unit ``` Then you can use `SideEffect` as an alias for `()=>Unit`. That's all I can make of it. It looks to me that this is probably not what you were looking for. But maybe this will help you a little bit along the way. If you want to have a more concrete answer, it would be nice if you would clarify the question.
`object B` doesn't really have much to do with `class B` aside from some special rules. If you wish to reuse that `doSomething` method you should just reuse the implementation from the object: ``` class B { def doSomething() = B.doSomething() } ``` If you want to specify `object B` as a specific instance of `class B` then you should do the following: ``` object B extends B("some particular creator") { ... } ``` You also do not need `override` modifiers although they can be handy for compiler checks.
31,441,040
I'm trying to retain the selected value of a dropdownlist once the user change the dropdownlist item but its not working as expected what I wanted is to retain the selected item in the dropdownlist but its it defaulted to the `Select Company` everytime i select the item from dropdownlist, once the user change it postback the page (i know there is no postback in the MVC) What I'm doing wrong here? ``` <div class="form-group"> @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @id = "form_dropdown" })) { @Html.DropDownListFor(m => m.ListOfCompanies, new SelectList((System.Collections.IEnumerable)Model.ListOfCompanies, "Value", "Text"), "Select Company", new { @class = "form-control", Name = "sel" }) } ``` ``` [HttpPost] public ActionResult Index(string sel) { var vModel = new EmployeeViewModel(); vModel = _db.GetEmployee.ToList(); //load list of companies: var company = _db.LoadComapny.ToList(); IEnumerable<SelectListItem> result = model.Select(b => new SelectListItem { Value = b.Value, Text = b.Text, Selected = b.Text == sel }).ToList(); vModel.ListOfCompanies = company; vModel.SELECTED_COMPANY = sel; return View(vModel); } ``` Model: ``` public class EmployeeViewModel { public IEnumerable<SelectListItem> ListOfCompanies { get; set; } public string SELECTED_COMPANY { get; set; } //other props } ```
2015/07/15
['https://Stackoverflow.com/questions/31441040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/275390/']
As I wrote in the comment section, it's really unclear to me what you're asking. However, looking at your code examples, it seems to me that `trait A` isn't really required. You can use the types that already come with the Scala SDK: ``` object B extends (()=>Unit) { def apply() { /* implementation */ } } ``` Or, as a variant: ``` object B { val aType:()=>Unit = {() => /* implementation */ } } ``` In the first case, you can access the singleton instance with `B`, in the second case with `B.aType`. In the second case, no explicit declaration of the `apply` method is needed. Pick what you like. The essential message is: You don't need a trait if you just define one simple method. That's what Scala functions are for. The list type might look like this: ``` private val aList:ListBuffer[()=>Unit] = ??? ``` (By the way: Why not declare it as `Seq[()=>Unit]`? Is it important to the caller that it is a `ListBuffer` and not some other kind of sequence?) Your worker might then look like this: ``` abstract class Worker { def aType:()=>Unit // no need for the `get` prefix here, or the empty parameter list def do() {aType()} } ``` Note that now the `Worker` type has become a class that offers a method that invokes a function. So, there is really no need to have a `Worker` class. You can just take the function (`aType`) directly and invoke it, just so. If you always want to call the implementation in `object B`, well - just do that then. There is no need to wrap the call in instances of other types. Your example class `B` just forwards the call to the `B` object, which is really unnecessary. There is no need to even create an instance of `B`. It does have the private member variable `creator`, but since it's never used, it will never be accessed in any way. So, I would recommend to completely remove the `class B`. All you need is the type `()=>Unit`, which is exactly what you need: A function that takes no parameters and returns nothing. If you get tired of writing `()=>Unit` all the time, you can define a type alias, for example inside the package object. Here is my recommentation: ``` type SideEffect = ()=>Unit ``` Then you can use `SideEffect` as an alias for `()=>Unit`. That's all I can make of it. It looks to me that this is probably not what you were looking for. But maybe this will help you a little bit along the way. If you want to have a more concrete answer, it would be nice if you would clarify the question.
The notion of a *companion object* extending a trait is useful for defining behavior associated with the class itself (e.g. static methods) as opposed to instances of the class. In other words, it allows your static methods to implement interfaces. Here's an example: ``` import java.nio.ByteBuffer // a trait to be implemented by the companion object of a class // to convey the fixed size of any instance of that class trait Sized { def size: Int } // create a buffer based on the size information provided by the // companion object def createBuffer(sized: Sized): ByteBuffer = ByteBuffer.allocate(sized.size) class MyClass(x: Long) { def writeTo(buffer: ByteBuffer) { buffer.putLong(x) } } object MyClass extends Sized { def size = java.lang.Long.SIZE / java.lang.Byte.SIZE } // create a buffer with correct sizing for MyClass whose companion // object implements Sized. Note that we don't need an instance // of MyClass to obtain sizing information. val buf = createBuffer(MyClass) // write an instance of MyClass to the buffer. val c = new MyClass(42) c.writeTo(buf) ```
31,441,040
I'm trying to retain the selected value of a dropdownlist once the user change the dropdownlist item but its not working as expected what I wanted is to retain the selected item in the dropdownlist but its it defaulted to the `Select Company` everytime i select the item from dropdownlist, once the user change it postback the page (i know there is no postback in the MVC) What I'm doing wrong here? ``` <div class="form-group"> @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @id = "form_dropdown" })) { @Html.DropDownListFor(m => m.ListOfCompanies, new SelectList((System.Collections.IEnumerable)Model.ListOfCompanies, "Value", "Text"), "Select Company", new { @class = "form-control", Name = "sel" }) } ``` ``` [HttpPost] public ActionResult Index(string sel) { var vModel = new EmployeeViewModel(); vModel = _db.GetEmployee.ToList(); //load list of companies: var company = _db.LoadComapny.ToList(); IEnumerable<SelectListItem> result = model.Select(b => new SelectListItem { Value = b.Value, Text = b.Text, Selected = b.Text == sel }).ToList(); vModel.ListOfCompanies = company; vModel.SELECTED_COMPANY = sel; return View(vModel); } ``` Model: ``` public class EmployeeViewModel { public IEnumerable<SelectListItem> ListOfCompanies { get; set; } public string SELECTED_COMPANY { get; set; } //other props } ```
2015/07/15
['https://Stackoverflow.com/questions/31441040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/275390/']
`object B` doesn't really have much to do with `class B` aside from some special rules. If you wish to reuse that `doSomething` method you should just reuse the implementation from the object: ``` class B { def doSomething() = B.doSomething() } ``` If you want to specify `object B` as a specific instance of `class B` then you should do the following: ``` object B extends B("some particular creator") { ... } ``` You also do not need `override` modifiers although they can be handy for compiler checks.
The notion of a *companion object* extending a trait is useful for defining behavior associated with the class itself (e.g. static methods) as opposed to instances of the class. In other words, it allows your static methods to implement interfaces. Here's an example: ``` import java.nio.ByteBuffer // a trait to be implemented by the companion object of a class // to convey the fixed size of any instance of that class trait Sized { def size: Int } // create a buffer based on the size information provided by the // companion object def createBuffer(sized: Sized): ByteBuffer = ByteBuffer.allocate(sized.size) class MyClass(x: Long) { def writeTo(buffer: ByteBuffer) { buffer.putLong(x) } } object MyClass extends Sized { def size = java.lang.Long.SIZE / java.lang.Byte.SIZE } // create a buffer with correct sizing for MyClass whose companion // object implements Sized. Note that we don't need an instance // of MyClass to obtain sizing information. val buf = createBuffer(MyClass) // write an instance of MyClass to the buffer. val c = new MyClass(42) c.writeTo(buf) ```
2,815,373
I'm looking for the following features: 1. Scheduler uses SQL Server as the backing store 2. Tasks can be scheduled by one application and executed by another 3. I can have multiple applications, each of which handles a specific subset of tasks 4. Tasks can be triggered at specific times, now, or based on the success or failure of other tasks 5. Data can be attached to tasks There are a number of nice-to-have's, like a web management console, clustering/failover support, customizable logging, but they're not requirements. On the surface Quartz.NET has a nice interface and seems to fit the bill as it satisfies (1), (4 with some custom work) and (5), but I've been beating my head against (2) and (3) seems like I'd have to invest more effort than it's worth, especially given how convoluted the innards of it are. Any other libraries out there? Open source is preferred, with free as a close runner up. It's really hard to get management to pay for things like this when it's not their idea.
2010/05/12
['https://Stackoverflow.com/questions/2815373', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/156767/']
I hate to say it, but it sounds like you want [BizTalk](http://www.microsoft.com/biztalk/en/us/default.aspx) which is neither open source, nor free, but is ideally suited towards what you are trying to accomplish.
You could use Windows Workflow (WF), maybe along with Quartz.NET
332,362
Suppose $M$ is a $\sigma$-finite measure space, and $\Gamma$ a set of positive-measure subsets of $M$ such that every point in $M$ belongs to only finitely many members of $\Gamma$. Must $\Gamma$ be countable? (And if the answer to this question is *no* for general σ-finite measures, is it also no for, say, Lebesgue measure?) • I can see that if the conjecture that Γ has to be countable is true when $M$ has *finite* measure, it must be also be true when $M$ is σ-finite. (Just decompose $M$ into $M\_0 ∪ M\_1 ∪ \ldots$ where each $M\_i$ is finite-measure. For each $i$, only countably many of Γ will have positive measure intersection with $M\_i$; but every member of Γ must have positive-measure overlap with some $M\_i$, so Γ must be countable.) So we can focus on the case where $M$ is finite measure. • I can prove the following weaker result: suppose $M$ is finite-measure and Γ a set of positive-measure subsets of $M$ such that every point in $M$ belongs to at most $n$ members of Γ, then Γ must be countable. (For each ε>0, at most $nμ(M)/ε$ members of Γ have measure ≥ε. So we can enumerate all the members of Γ by first enumerating those with measure≥1, then those with measure ≥1/2, then those with measure ≥1/4, etc.) • Returning to the original conjecture, I can see how to prove it if only I could take it for granted that for each $i$, the set $E\_i$ of points in $M$ that belong to exactly $i$ members of Γ is measurable. In that case, I could first use the weaker result to show that for each $i$, at most countably many members of Γ have positive-measure overlap with $E\_i$, and then argue that since $M = E\_0 ∪ E\_1 ∪ \ldots$ and the $E\_i$ are measurable, every member of Γ must have positive-measure overlap with at least one of the $E\_i$, establishing that Γ is itself countable. Unfortunately this doesn't work if the $E\_i$ aren't measurable, and I don't see any way to show that they are. (This question is a follow-up to [Can an uncountable family of positive-measure sets be such that no point belongs to uncountably many of them?](https://math.stackexchange.com/questions/319358/).)
2013/03/16
['https://math.stackexchange.com/questions/332362', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4909/']
Assume a finite measure. There is an $\epsilon > 0$ and countable collection $E\_i$ with $\mu(E\_i) > \epsilon$, because the alternative is that $\lbrace E: \mu(E) > \frac 1 n \rbrace$ is finite for all $n$, which would make $\lbrace E: \mu(E) > 0 \rbrace$ countable. Let $F\_n = E\_n \cup E\_{n+1} \cup .... $. The sequence of indicators $1\_{F\_n} $ is monotone decreasing and converges to $0$ on the set where $x \in E\_i$ finitely often, and $1$ if $x \in E\_i$ infinitely often. It is also bounded by 1. By bounded convergence it converges in $ \mathbb L \_1$. But since $\int 1\_{F\_n} d\mu > \epsilon $ the same must be true of the limit.
Here is a more detailed and more elementary version of mike's proof, using continuity rather than the bounded convergence theorem, which I'm writing up mostly for my own edification. Suppose that for some finite-measure $S$ and $ε>0$, there are infinitely many $E⊂Γ$ with $μ(S∩E)≥ε$. Let $E\_0, E\_1, E\_2\ldots$ be a countable sequence of such $E$. And let $F\_n = S ∩ (E\_n ∪ E\_{n+1} ∪ E\_{n+2} ∪ \cdots)$. Clearly $μ(S) ≥ μ(F\_i) ≥ μ(S∩E\_i) ≥ ε$ for each $i$, and $F\_i ⊂ F\_j$ whenever $j<i$. So by the fact that measures are continuous from above (see <http://en.wikipedia.org/wiki/Measure_(mathematics)#Properties>), $μ(\bigcap\_{i=1}^\infty F\_i) = \lim\_{i→∞}μ(F\_i) ≥ ε$. But for any point $p$ in $S$, $p∈\bigcap\_{i=1}^\infty F\_i$ if and only if p belongs to infinitely many of the $E\_i$. Therefore there are some points in $M$ (in fact, a positive-measure set of them) that belong to infinitely many of the $E\_i$, contradicting the stipulation that each point only belongs to finitely many members of Γ. So we can conclude that for every finite-measure subset $S$ of $M$ and every $ε>0$, there are only finitely many $E∈Γ$ with $μ(S∩E)≥ε$. Then the set of $E∈Γ$ with $μ(S∩E)≥0$ is countable for every finite-measure $S$, since we can enumerate these $E$ by first listing those for which $μ(S∩E)≥1$, then those for which $μ(S∩E)≥1/2$, then those for which $μ(S∩E)≥1/3$, etc. But $M$ is σ-finite, so there is a countable collection of finite-measure sets $S\_0, S\_1, S\_2\ldots$ such that every positive-measure subset of $M$ has positive-measure overlap with at least one of $S\_0, S\_1, S\_2\ldots$. So Γ itself is countable, being the union of countably many countable sets.
201,346
We were fighting Vecna himself, and at one point had a *[prismatic wall](https://www.dndbeyond.com/spells/prismatic-wall)* up between us and Vecna. The *prismatic wall* says it creates "a vertical, opaque wall." Vecna's powers include truesight, and presumably x-ray vision as well (since the artifact *Eye of Vecna* allows its bearer to use x-ray vision), and the DM thought Vecna would be able to see through the prismatic wall and target us. A *[ring of x-ray vision](https://www.dndbeyond.com/magic-items/4738-ring-of-x-ray-vision)* states: > > While wearing this ring, you can use an action to speak its command word. When you do so, you can see into and through solid matter for 1 minute. This vision has a radius of 30 feet. To you, solid objects within that radius appear transparent and don't prevent light from passing through them. The vision can penetrate 1 foot of stone, 1 inch of common metal, or up to 3 feet of wood or dirt. Thicker substances block the vision, as does a thin sheet of lead. > > > So can someone see through a prismatic wall using truesight/x-ray vision?
2022/09/10
['https://rpg.stackexchange.com/questions/201346', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/30992/']
**Truesight does not help** - a Prismatic Wall is an Abjuration, not an Illusion, and neither involves the Ethereal plane nor shapeshifting. **X-ray vision is less clear** - Prismatic Wall is defined as one inch thick, which definitely fits within the realm of X-ray vision. However, X-ray vision states "solid objects", which I'd argue a Prismatic Wall isn't, being defined as "a shimmering, multicolored plane of light ". As Prismatic Wall is a 9th level spell, so I'd tend to argue in favor of it doing more rather than less. However, I'd say the rules are unclear enough that **a DM ruling is required**. And **Rule 0** is always a thing - if the DM wants Vecna, one of the top BBEGs in D&D, to be able to see through something, then Vecna definitely can.
*Prismatic wall*: > > A shimmering, multicolored plane of light forms a vertical opaque wall > > > Truesight: maybe indirectly --------------------------- Monster Manual (p. 9): > > A monster with truesight can, out to a specific range, see in normal and magical darkness, see invisible creatures and objects, automatically detect visual illusions and succeed on saving throws against them, and perceive the original form of a shapechanger or a creature that is transformed by magic. > > > Nothing in this implies that truesight allows one to see through an opaque wall. However, truesight also grants: > > Furthermore, the monster can see into the Ethereal Plane within the same range. > > > And here is where it gets complicated. Nothing in the description of *prismatic wall* says or implies that any layer of the wall is made of force, and thus the wall does not exist on the Ethereal plane. However, the characters are (presumably) living, and the DMG says that "[living beings] on the [Material] hamper the movement of a creature in the Border Ethereal." The [*Etherealness*](https://www.dndbeyond.com/spells/etherealness) spell states that "You can see and hear the plane you originated from, but everything there looks gray, and you can't see anything more than 60 feet away." That is, someone on the Border Ethereal can see a version of the overlapping Material plane (although the objects appear as muted gray forms) and living creatures on the Material create impassible physical barriers on the Ethereal. Thus it seems reasonable for a DM to rule that Vecna could use his truesight to see into the Border Ethereal, where projections of the characters appear in gray tones and where the wall does not block his sight. Since Border Ethereal locations 'map one to one' with the Material, it is then possible to rule that he can use this [indirect sight to target characters](https://rpg.stackexchange.com/questions/195034/can-i-target-someone-who-i-can-see-in-a-mirror?rq=1) on the material plane, since he can, in effect, 'see their location' by noting the location of their forms that are visible on the Ethereal. It is certainly not RAW, but it is also not an unreasonable interpretation. If anyone could do this, Vecna could. X-ray vision - no ----------------- The [*ring of X-ray vision*](https://www.dndbeyond.com/magic-items/4738-ring-of-x-ray-vision) says: > > When you do so, you can see into and through solid matter for 1 minute. This vision has a radius of 30 feet. To you, solid objects within that radius appear transparent and don't prevent light from passing through them. > > > The ring specifically says that it can be used to see through "solid matter [and] solid objects"; it does not impart any ability to see through opaque substances that are *not* solid. It could not be used, for example, to see through an inch thick of liquid mercury, or a dense gaseous [fog or smoke](https://rpg.stackexchange.com/q/72780/23547). While the wall is opaque, the "shimmering plane of light" is not solid in any natural English usage of the word. Creatures passing through it may trigger damage or other effects, but it does not physically block their passage. And it is certainly not an *object*; it is a magical effect. Thus the ring's ability to make "solid objects...appear transparent" simply does not apply.
201,346
We were fighting Vecna himself, and at one point had a *[prismatic wall](https://www.dndbeyond.com/spells/prismatic-wall)* up between us and Vecna. The *prismatic wall* says it creates "a vertical, opaque wall." Vecna's powers include truesight, and presumably x-ray vision as well (since the artifact *Eye of Vecna* allows its bearer to use x-ray vision), and the DM thought Vecna would be able to see through the prismatic wall and target us. A *[ring of x-ray vision](https://www.dndbeyond.com/magic-items/4738-ring-of-x-ray-vision)* states: > > While wearing this ring, you can use an action to speak its command word. When you do so, you can see into and through solid matter for 1 minute. This vision has a radius of 30 feet. To you, solid objects within that radius appear transparent and don't prevent light from passing through them. The vision can penetrate 1 foot of stone, 1 inch of common metal, or up to 3 feet of wood or dirt. Thicker substances block the vision, as does a thin sheet of lead. > > > So can someone see through a prismatic wall using truesight/x-ray vision?
2022/09/10
['https://rpg.stackexchange.com/questions/201346', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/30992/']
**Truesight does not help** - a Prismatic Wall is an Abjuration, not an Illusion, and neither involves the Ethereal plane nor shapeshifting. **X-ray vision is less clear** - Prismatic Wall is defined as one inch thick, which definitely fits within the realm of X-ray vision. However, X-ray vision states "solid objects", which I'd argue a Prismatic Wall isn't, being defined as "a shimmering, multicolored plane of light ". As Prismatic Wall is a 9th level spell, so I'd tend to argue in favor of it doing more rather than less. However, I'd say the rules are unclear enough that **a DM ruling is required**. And **Rule 0** is always a thing - if the DM wants Vecna, one of the top BBEGs in D&D, to be able to see through something, then Vecna definitely can.
RAW, vague. ----------- True sight and x-ray vision could either be *argued* to see through *Prismatic Wall* depending on various definitions of light, matter, ethereal, etc. However, D&D 5e is not a physics simulator. Neither *explicitly* states they see through 'planes of shimmering light' or w/e, yet they both talk about seeing through all kinds of stuff, so it's basically an argument either way. Whenever there's an argument about anything in D&D, it comes down to the DM's decision. That's in large part *why* you have a DM (as well as to apply structure and motivation to the story). What a DM decides is reasonable in that situation is up to the DM and their table's expectations, but, *Should* Vecna be able to see through his Prismatic Wall? --------------------------------------------------------- Yes. He is Vecna.
201,346
We were fighting Vecna himself, and at one point had a *[prismatic wall](https://www.dndbeyond.com/spells/prismatic-wall)* up between us and Vecna. The *prismatic wall* says it creates "a vertical, opaque wall." Vecna's powers include truesight, and presumably x-ray vision as well (since the artifact *Eye of Vecna* allows its bearer to use x-ray vision), and the DM thought Vecna would be able to see through the prismatic wall and target us. A *[ring of x-ray vision](https://www.dndbeyond.com/magic-items/4738-ring-of-x-ray-vision)* states: > > While wearing this ring, you can use an action to speak its command word. When you do so, you can see into and through solid matter for 1 minute. This vision has a radius of 30 feet. To you, solid objects within that radius appear transparent and don't prevent light from passing through them. The vision can penetrate 1 foot of stone, 1 inch of common metal, or up to 3 feet of wood or dirt. Thicker substances block the vision, as does a thin sheet of lead. > > > So can someone see through a prismatic wall using truesight/x-ray vision?
2022/09/10
['https://rpg.stackexchange.com/questions/201346', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/30992/']
Neither effect allows you to see through a Prismatic Wall --------------------------------------------------------- Prismatic Wall has this effect: > > A shimmering, multicolored plane of light forms a vertical opaque wall > > > ### Truesight [Truesight](https://www.dndbeyond.com/sources/basic-rules/monsters#Truesight) allows you to > > see in normal and magical darkness, see invisible creatures and objects, automatically detect visual illusions and succeed on saving throws against them, and perceive the original form of a shapechanger or a creature that is transformed by magic [...] see into the Ethereal Plane > > > It does not allow you to see through an opaque barrier. While you can see into the Ethereal Plane, what you are looking at is not not *on* the Ethereal Plane, and if you could see them *from* there does not matter, as neither are you. ### X-Ray Vision X-Ray Vision (as in the [ring](https://www.dndbeyond.com/magic-items/4738-ring-of-x-ray-vision)) allows you to > > see into and through solid matter (...) To you, solid objects within that radius appear transparent and don't prevent light from passing through them > > > The wall is not a solid object or solid matter, as it is made of insubstantial light that you can walk through, which you could not if it were solid. So X-Ray Vision does not allow you to see through it, either. ### Vecna Could you use either as a player character if you tried to look through a Prismatic Wall? No. Could Vecna? Not by the official stat block that has been printed in the [Vecna Dossier](https://www.dndbeyond.com/claim/source/vecna) (where he does not even have X-Ray Vision, as he does not have the Hand or Eye of Vecna, he is said to be questing for them). However, the lore section there states that > > More recently, Vecna decamped to the Outer Planes, where he grew so powerful that he became a god. > > > And there are no printed rules for gods. Even without invoking their right to overrule anything, the DM can rule that he could see through the wall. And even for pre-apotheosis Vecna, they of course can rule so, because it's Vecna and because of their right to overrule. Your DM in any case did rule so, so your Vecna could.
*Prismatic wall*: > > A shimmering, multicolored plane of light forms a vertical opaque wall > > > Truesight: maybe indirectly --------------------------- Monster Manual (p. 9): > > A monster with truesight can, out to a specific range, see in normal and magical darkness, see invisible creatures and objects, automatically detect visual illusions and succeed on saving throws against them, and perceive the original form of a shapechanger or a creature that is transformed by magic. > > > Nothing in this implies that truesight allows one to see through an opaque wall. However, truesight also grants: > > Furthermore, the monster can see into the Ethereal Plane within the same range. > > > And here is where it gets complicated. Nothing in the description of *prismatic wall* says or implies that any layer of the wall is made of force, and thus the wall does not exist on the Ethereal plane. However, the characters are (presumably) living, and the DMG says that "[living beings] on the [Material] hamper the movement of a creature in the Border Ethereal." The [*Etherealness*](https://www.dndbeyond.com/spells/etherealness) spell states that "You can see and hear the plane you originated from, but everything there looks gray, and you can't see anything more than 60 feet away." That is, someone on the Border Ethereal can see a version of the overlapping Material plane (although the objects appear as muted gray forms) and living creatures on the Material create impassible physical barriers on the Ethereal. Thus it seems reasonable for a DM to rule that Vecna could use his truesight to see into the Border Ethereal, where projections of the characters appear in gray tones and where the wall does not block his sight. Since Border Ethereal locations 'map one to one' with the Material, it is then possible to rule that he can use this [indirect sight to target characters](https://rpg.stackexchange.com/questions/195034/can-i-target-someone-who-i-can-see-in-a-mirror?rq=1) on the material plane, since he can, in effect, 'see their location' by noting the location of their forms that are visible on the Ethereal. It is certainly not RAW, but it is also not an unreasonable interpretation. If anyone could do this, Vecna could. X-ray vision - no ----------------- The [*ring of X-ray vision*](https://www.dndbeyond.com/magic-items/4738-ring-of-x-ray-vision) says: > > When you do so, you can see into and through solid matter for 1 minute. This vision has a radius of 30 feet. To you, solid objects within that radius appear transparent and don't prevent light from passing through them. > > > The ring specifically says that it can be used to see through "solid matter [and] solid objects"; it does not impart any ability to see through opaque substances that are *not* solid. It could not be used, for example, to see through an inch thick of liquid mercury, or a dense gaseous [fog or smoke](https://rpg.stackexchange.com/q/72780/23547). While the wall is opaque, the "shimmering plane of light" is not solid in any natural English usage of the word. Creatures passing through it may trigger damage or other effects, but it does not physically block their passage. And it is certainly not an *object*; it is a magical effect. Thus the ring's ability to make "solid objects...appear transparent" simply does not apply.
201,346
We were fighting Vecna himself, and at one point had a *[prismatic wall](https://www.dndbeyond.com/spells/prismatic-wall)* up between us and Vecna. The *prismatic wall* says it creates "a vertical, opaque wall." Vecna's powers include truesight, and presumably x-ray vision as well (since the artifact *Eye of Vecna* allows its bearer to use x-ray vision), and the DM thought Vecna would be able to see through the prismatic wall and target us. A *[ring of x-ray vision](https://www.dndbeyond.com/magic-items/4738-ring-of-x-ray-vision)* states: > > While wearing this ring, you can use an action to speak its command word. When you do so, you can see into and through solid matter for 1 minute. This vision has a radius of 30 feet. To you, solid objects within that radius appear transparent and don't prevent light from passing through them. The vision can penetrate 1 foot of stone, 1 inch of common metal, or up to 3 feet of wood or dirt. Thicker substances block the vision, as does a thin sheet of lead. > > > So can someone see through a prismatic wall using truesight/x-ray vision?
2022/09/10
['https://rpg.stackexchange.com/questions/201346', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/30992/']
Neither effect allows you to see through a Prismatic Wall --------------------------------------------------------- Prismatic Wall has this effect: > > A shimmering, multicolored plane of light forms a vertical opaque wall > > > ### Truesight [Truesight](https://www.dndbeyond.com/sources/basic-rules/monsters#Truesight) allows you to > > see in normal and magical darkness, see invisible creatures and objects, automatically detect visual illusions and succeed on saving throws against them, and perceive the original form of a shapechanger or a creature that is transformed by magic [...] see into the Ethereal Plane > > > It does not allow you to see through an opaque barrier. While you can see into the Ethereal Plane, what you are looking at is not not *on* the Ethereal Plane, and if you could see them *from* there does not matter, as neither are you. ### X-Ray Vision X-Ray Vision (as in the [ring](https://www.dndbeyond.com/magic-items/4738-ring-of-x-ray-vision)) allows you to > > see into and through solid matter (...) To you, solid objects within that radius appear transparent and don't prevent light from passing through them > > > The wall is not a solid object or solid matter, as it is made of insubstantial light that you can walk through, which you could not if it were solid. So X-Ray Vision does not allow you to see through it, either. ### Vecna Could you use either as a player character if you tried to look through a Prismatic Wall? No. Could Vecna? Not by the official stat block that has been printed in the [Vecna Dossier](https://www.dndbeyond.com/claim/source/vecna) (where he does not even have X-Ray Vision, as he does not have the Hand or Eye of Vecna, he is said to be questing for them). However, the lore section there states that > > More recently, Vecna decamped to the Outer Planes, where he grew so powerful that he became a god. > > > And there are no printed rules for gods. Even without invoking their right to overrule anything, the DM can rule that he could see through the wall. And even for pre-apotheosis Vecna, they of course can rule so, because it's Vecna and because of their right to overrule. Your DM in any case did rule so, so your Vecna could.
RAW, vague. ----------- True sight and x-ray vision could either be *argued* to see through *Prismatic Wall* depending on various definitions of light, matter, ethereal, etc. However, D&D 5e is not a physics simulator. Neither *explicitly* states they see through 'planes of shimmering light' or w/e, yet they both talk about seeing through all kinds of stuff, so it's basically an argument either way. Whenever there's an argument about anything in D&D, it comes down to the DM's decision. That's in large part *why* you have a DM (as well as to apply structure and motivation to the story). What a DM decides is reasonable in that situation is up to the DM and their table's expectations, but, *Should* Vecna be able to see through his Prismatic Wall? --------------------------------------------------------- Yes. He is Vecna.
17,724,172
How to convert the string "Thu Jul 18 13:20:12 GMT+05:30 2013" in date in android? Using DateFormatter and SimpleDateFormatter throw an exception saying cannot parse the date format while using it to convert into date.
2013/07/18
['https://Stackoverflow.com/questions/17724172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1954375/']
``` try { String dateString = "Thu Jul 18 13:20:12 GMT+05:30 2013"; SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy"); Date date = sdf.parse(dateString); } catch (ParseException e) { e.printStackTrace(); } ```
You can also do this: ``` SimpleDateFormat dateFormat = new SimpleDateFormat("DD-MM-YYYY"); Date dd = dateFormat.parse("string") ```
17,724,172
How to convert the string "Thu Jul 18 13:20:12 GMT+05:30 2013" in date in android? Using DateFormatter and SimpleDateFormatter throw an exception saying cannot parse the date format while using it to convert into date.
2013/07/18
['https://Stackoverflow.com/questions/17724172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1954375/']
``` try { String dateString = "Thu Jul 18 13:20:12 GMT+05:30 2013"; SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy"); Date date = sdf.parse(dateString); } catch (ParseException e) { e.printStackTrace(); } ```
This is how you can do: ``` try { String dateString = "Thu Jul 18 13:20:12 GMT+05:30 2013"; Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse(dateString ); } catch (ParseException e) { e.printStackTrace(); } ```
17,724,172
How to convert the string "Thu Jul 18 13:20:12 GMT+05:30 2013" in date in android? Using DateFormatter and SimpleDateFormatter throw an exception saying cannot parse the date format while using it to convert into date.
2013/07/18
['https://Stackoverflow.com/questions/17724172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1954375/']
``` SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy"); try { String dateString = "Thu Jul 18 13:20:12 GMT+05:30 2013"; Date date = formatter.parse(dateString); } catch (Exception e) { e.printStackTrace(); } ``` this is how we doing in android..but if you can post your code then can help you precisely
You can also do this: ``` SimpleDateFormat dateFormat = new SimpleDateFormat("DD-MM-YYYY"); Date dd = dateFormat.parse("string") ```
17,724,172
How to convert the string "Thu Jul 18 13:20:12 GMT+05:30 2013" in date in android? Using DateFormatter and SimpleDateFormatter throw an exception saying cannot parse the date format while using it to convert into date.
2013/07/18
['https://Stackoverflow.com/questions/17724172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1954375/']
``` SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy"); try { String dateString = "Thu Jul 18 13:20:12 GMT+05:30 2013"; Date date = formatter.parse(dateString); } catch (Exception e) { e.printStackTrace(); } ``` this is how we doing in android..but if you can post your code then can help you precisely
This is how you can do: ``` try { String dateString = "Thu Jul 18 13:20:12 GMT+05:30 2013"; Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse(dateString ); } catch (ParseException e) { e.printStackTrace(); } ```
73,306
Tables allow us to easily see how **2** variables (for example "Employee" and "Time") correlate. For me the main benefit of this view is that you can easily find answers to two kinds of questions. Like: * What is employee X been doing since he started working for us? * What is everybody doing today? My question: is there a way to create an equally easy to use view that does the same for **3** variables (for example "Employee", "Time" and "Project")?
2015/02/09
['https://ux.stackexchange.com/questions/73306', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/28176/']
While it can be computationaly and mathematically complex, the concept of heat maps can help you out here. The point of a heat map is you add a third dimension to a 2 dimensional plot not by actually having an additional axis, but by using color. For example, your X axis could be "employees", your Y axis could be "project", and time could be represented by color along the XY plane. One color could can mean "more time" while another color can mean "little time". In the fictious example below, a certain epmloyee has spent a high amount of time on a certain project, less time on closely related projects and no time on unrelated projects. ![enter image description here](https://i.stack.imgur.com/qsJwf.jpg) By using additional colors, a 4th or 5th dimension can be added. For example, all hues of blue can mean "time", whereas all hues of red could mean "resource spent". by combining these colors, you get purple. hues of purple can mean time & resources spent. In my opinion, the complexity (both for a developer as for a user) tend to increase dramatically by each additional dimension added. I don't have an official study to back up that claim, it's just my own experience.
There was a similar question posted a little bit back about visualization combinations (see [Best visualization for combinations](https://ux.stackexchange.com/questions/72605/best-visualization-for-combinations/72683#72683)). In addition to the heat map posted above you also have a couple other choices which are similar but distinct. Contour Plot ============ A contour plot is very similar to a heat map except that it displays the boundary of the regions. There is a bit of variance in whether or not folks plot the regions with color simply display the boundary. The option gets its name from topographical maps where it truly is showing the contour of the land. It works equally well for displaying 3 pieces of data that are related. * This is the stock example for d3. <http://bl.ocks.org/mbostock/4241134> * Here is a decent example of this showing how to do it in d3 and R (picture below is R). <http://vis.supstat.com/2012/11/contour-plots-with-d3-and-r/> ![enter image description here](https://i.stack.imgur.com/9S5mX.png) Standard scatter plot with variable markers =========================================== This option is just an extension of the standard 2d scatter plot. Instead of just placing a dot in the region for the data point, you encode additional information in the marker. Things that can be used include: * Color to display a continuous variable * Size to display a continuous variable (be careful with this; people can have difficulty perceiving quantitative relationships between sizes of certain objects) * Marker shape can be used to encode a discrete or categorical variable Multiple scatter plots ====================== If you are looking to show relationships between pairs of multiple variables, you can also use the matrix or multiple scatter plot approach. This works well for finding relationships between pairs of large groups of variables. * Here is an example of that done with d3. <http://benjiec.github.io/scatter-matrix/demo/demo.html> ![multiple scatter plots](https://i.stack.imgur.com/qRph6.png) Parallel Coordinates Plot ========================= The parallel coordinates plot works well when you have more than 3 variables to show, but it can work well for 3 also. Its specialty is that it allows for filtering and interaction which can be used to select data for other visualizations. It is also well geared toward encoding color and other data across the lines. It is very compact in space as well considering the number of variables that can be displayed. It is less useful for relationships unless they come in groups. * This is one of the best combo visualizations which shows the parallel coordinates and underlying data below. <http://bl.ocks.org/syntagmatic/raw/3150059/>. The source for this is coming from <https://syntagmatic.github.io/parallel-coordinates/>. ![par coords example](https://i.stack.imgur.com/ajC5P.png)
4,442,828
I'm playing with the latest Entity Framework CTP 5 release and building a simple asp.net MVC blog where I just have two tables: Post and Comments. This is done entirely in POCO, I just need help on the DbContext part, where I need it to be unit testable (using IDbSet?) and I need a simple/generic repository pattern for add, update, delete, retrieval. Any help is appreciated. Thanks.
2010/12/14
['https://Stackoverflow.com/questions/4442828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248480/']
Start with you DbContext, create a new file called Database.cs: **Database.cs** ``` public class Database : DbContext { private IDbSet<Post> _posts; public IDbSet<Post> Posts { get { return _posts ?? (_posts = DbSet<Post>()); } } public virtual IDbSet<T> DbSet<T>() where T : class { return Set<T>(); } public virtual void Commit() { base.SaveChanges(); } } ``` Define a IDatabaseFactory and implement it with DatabaseFactory: **IDatabaseFactory.cs** ``` public interface IDatabaseFactory : IDisposable { Database Get(); } ``` **DatabaseFactory.cs** ``` public class DatabaseFactory : Disposable, IDatabaseFactory { private Database _database; public Database Get() { return _database ?? (_database = new Database()); } protected override void DisposeCore() { if (_database != null) _database.Dispose(); } } ``` Disposable extension method: **Disposable.cs** ``` public class Disposable : IDisposable { private bool isDisposed; ~Disposable() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if(!isDisposed && disposing) { DisposeCore(); } isDisposed = true; } protected virtual void DisposeCore() { } } ``` Now we can define our IRepository and our RepositoryBase **IRepository.cs** ``` public interface IRepository<T> where T : class { void Add(T entity); void Delete(T entity); void Update(T entity); T GetById(long Id); IEnumerable<T> All(); IEnumerable<T> AllReadOnly(); } ``` **RepositoryBase.cs** ``` public abstract class RepositoryBase<T> where T : class { private Database _database; private readonly IDbSet<T> _dbset; protected RepositoryBase(IDatabaseFactory databaseFactory) { DatabaseFactory = databaseFactory; _dbset = Database.Set<T>(); } protected IDatabaseFactory DatabaseFactory { get; private set; } protected Database Database { get { return _database ?? (_database = DatabaseFactory.Get()); } } public virtual void Add(T entity) { _dbset.Add(entity); } public virtual void Delete(T entity) { _dbset.Remove(entity); } public virtual void Update(T entity) { _database.Entry(entity).State = EntityState.Modified; } public virtual T GetById(long id) { return _dbset.Find(id); } public virtual IEnumerable<T> All() { return _dbset.ToList(); } public virtual IEnumerable<T> AllReadOnly() { return _dbset.AsNoTracking().ToList(); } } ``` Now you can create your IPostRepository and PostRepository: **IPostRepository.cs** ``` public interface IPostRepository : IRepository<Post> { //Add custom methods here if needed Post ByTitle(string title); } ``` **PostRepository.cs** ``` public class PostRepository : RepositoryBase<Post>, IPostRepository { public PostRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } public Post ByTitle(string title) { return base.Database.Posts.Single(x => x.Title == title); } } ``` Lastly, the UoW: **IUnitOfWork.cs** ``` public interface IUnitOfWork { void Commit(); } ``` **UnitOfWork.cs** ``` private readonly IDatabaseFactory _databaseFactory; private Database _database; public UnitOfWork(IDatabaseFactory databaseFactory) { _databaseFactory = databaseFactory; } protected Database Database { get { return _database ?? (_database = _databaseFactory.Get()); } } public void Commit() { Database.Commit(); } ``` **Using in your controller:** ``` private readonly IPostRepository _postRepository; private readonly IUnitOfWork_unitOfWork; public PostController(IPostRepository postRepository, IUnitOfWork unitOfWork) { _postRepository = postRepository; _unitOfWork = unitOfWork; } public ActionResult Add(Post post) { _postRepository.Add(post); _unitOfWork.Commit(); } ``` You will need to use an IoC container like StructureMap to make this work. You can install structure map via NuGet, or if you are using MVC 3, you can install the StructureMap-MVC NuGet package. (Links Below) [Install-Package StructureMap.MVC4](http://nuget.org/List/Packages/StructureMap.MVC4) [Install-Package StructureMap.MVC3](http://nuget.org/List/Packages/StructureMap.MVC3) [Install-Package Structuremap](http://nuget.org/List/Packages/structuremap) If you have questions just let me know. Hope it helps.
The only thing I'd do differently is in the implementation, i.e. expose the IPostRepository in the service layer and have an interface field of type IPostService in the controller just as another layer of abstraction but otherwise this is a good example - nice one, Paul.
4,442,828
I'm playing with the latest Entity Framework CTP 5 release and building a simple asp.net MVC blog where I just have two tables: Post and Comments. This is done entirely in POCO, I just need help on the DbContext part, where I need it to be unit testable (using IDbSet?) and I need a simple/generic repository pattern for add, update, delete, retrieval. Any help is appreciated. Thanks.
2010/12/14
['https://Stackoverflow.com/questions/4442828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248480/']
Start with you DbContext, create a new file called Database.cs: **Database.cs** ``` public class Database : DbContext { private IDbSet<Post> _posts; public IDbSet<Post> Posts { get { return _posts ?? (_posts = DbSet<Post>()); } } public virtual IDbSet<T> DbSet<T>() where T : class { return Set<T>(); } public virtual void Commit() { base.SaveChanges(); } } ``` Define a IDatabaseFactory and implement it with DatabaseFactory: **IDatabaseFactory.cs** ``` public interface IDatabaseFactory : IDisposable { Database Get(); } ``` **DatabaseFactory.cs** ``` public class DatabaseFactory : Disposable, IDatabaseFactory { private Database _database; public Database Get() { return _database ?? (_database = new Database()); } protected override void DisposeCore() { if (_database != null) _database.Dispose(); } } ``` Disposable extension method: **Disposable.cs** ``` public class Disposable : IDisposable { private bool isDisposed; ~Disposable() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if(!isDisposed && disposing) { DisposeCore(); } isDisposed = true; } protected virtual void DisposeCore() { } } ``` Now we can define our IRepository and our RepositoryBase **IRepository.cs** ``` public interface IRepository<T> where T : class { void Add(T entity); void Delete(T entity); void Update(T entity); T GetById(long Id); IEnumerable<T> All(); IEnumerable<T> AllReadOnly(); } ``` **RepositoryBase.cs** ``` public abstract class RepositoryBase<T> where T : class { private Database _database; private readonly IDbSet<T> _dbset; protected RepositoryBase(IDatabaseFactory databaseFactory) { DatabaseFactory = databaseFactory; _dbset = Database.Set<T>(); } protected IDatabaseFactory DatabaseFactory { get; private set; } protected Database Database { get { return _database ?? (_database = DatabaseFactory.Get()); } } public virtual void Add(T entity) { _dbset.Add(entity); } public virtual void Delete(T entity) { _dbset.Remove(entity); } public virtual void Update(T entity) { _database.Entry(entity).State = EntityState.Modified; } public virtual T GetById(long id) { return _dbset.Find(id); } public virtual IEnumerable<T> All() { return _dbset.ToList(); } public virtual IEnumerable<T> AllReadOnly() { return _dbset.AsNoTracking().ToList(); } } ``` Now you can create your IPostRepository and PostRepository: **IPostRepository.cs** ``` public interface IPostRepository : IRepository<Post> { //Add custom methods here if needed Post ByTitle(string title); } ``` **PostRepository.cs** ``` public class PostRepository : RepositoryBase<Post>, IPostRepository { public PostRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } public Post ByTitle(string title) { return base.Database.Posts.Single(x => x.Title == title); } } ``` Lastly, the UoW: **IUnitOfWork.cs** ``` public interface IUnitOfWork { void Commit(); } ``` **UnitOfWork.cs** ``` private readonly IDatabaseFactory _databaseFactory; private Database _database; public UnitOfWork(IDatabaseFactory databaseFactory) { _databaseFactory = databaseFactory; } protected Database Database { get { return _database ?? (_database = _databaseFactory.Get()); } } public void Commit() { Database.Commit(); } ``` **Using in your controller:** ``` private readonly IPostRepository _postRepository; private readonly IUnitOfWork_unitOfWork; public PostController(IPostRepository postRepository, IUnitOfWork unitOfWork) { _postRepository = postRepository; _unitOfWork = unitOfWork; } public ActionResult Add(Post post) { _postRepository.Add(post); _unitOfWork.Commit(); } ``` You will need to use an IoC container like StructureMap to make this work. You can install structure map via NuGet, or if you are using MVC 3, you can install the StructureMap-MVC NuGet package. (Links Below) [Install-Package StructureMap.MVC4](http://nuget.org/List/Packages/StructureMap.MVC4) [Install-Package StructureMap.MVC3](http://nuget.org/List/Packages/StructureMap.MVC3) [Install-Package Structuremap](http://nuget.org/List/Packages/structuremap) If you have questions just let me know. Hope it helps.
I just love this in-depth article about Entity Framework 4 POCO, Repository and Specification Pattern <http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/>
4,442,828
I'm playing with the latest Entity Framework CTP 5 release and building a simple asp.net MVC blog where I just have two tables: Post and Comments. This is done entirely in POCO, I just need help on the DbContext part, where I need it to be unit testable (using IDbSet?) and I need a simple/generic repository pattern for add, update, delete, retrieval. Any help is appreciated. Thanks.
2010/12/14
['https://Stackoverflow.com/questions/4442828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248480/']
I just love this in-depth article about Entity Framework 4 POCO, Repository and Specification Pattern <http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/>
The only thing I'd do differently is in the implementation, i.e. expose the IPostRepository in the service layer and have an interface field of type IPostService in the controller just as another layer of abstraction but otherwise this is a good example - nice one, Paul.
2,441,903
factorize $$x^4+4abx^2-(a^2-b^2)^2$$ I am getting problem in factoring this. Anyone help me. I tried synthetic division but that doesn't work. Can anyone suggest me any other ways
2017/09/23
['https://math.stackexchange.com/questions/2441903', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/483811/']
$\color{red}{x^4-4abx^2}-(a^2-b^2)^2$ The red part is *almost* a square. What we need is adding $4a^2b^2$ But if we add then we modify the polynomial and this is not legal, so we must subtract the same quantity to be fair. Therefore we get $\color{red}{x^4-4abx^2+4a^2b^2}\color{blue}{-4a^2b^2-(a^2-b^2)^2}=\color{red}{x^4-4abx^2+4a^2b^2}\color{blue}{-a^4-2 a^2 b^2-b^4}=$ $=\color{red}{x^4-4abx^2+4a^2b^2}-\color{blue}{(a^4+2 a^2 b^2+b^4)}=$ The red is perfect square and the blue is a perfect square either so we can write $=\color{red}{(x^2-2ab)^2}-\color{blue}{(a^2+b^2)^2}=$ Now remember the basic $P^2-Q^2=(P+Q)(P-Q)$ here $P\to x^2-2ab$ and $Q\to a^2+b^2$ so we have $(\color{red}{(x^2-2ab)}+\color{blue}{(a^2+b^2)})(\color{red}{(x^2-2ab)}-\color{blue}{(a^2+b^2)})=\\=(x^2-2ab+a^2+b^2)(x^2-2ab-a^2-b^2)$ We are almost done The second parenthesis can be written in this way $x^2-(2ab+a^2+b^2)=x^2-(a+b)^2=(x+a+b)(x-a-b)$ Now the factoring is complete $$x^4-4abx^2-(a^2-b^2)^2=(x^2-2ab+a^2+b^2)(x+a+b)(x-a-b)$$ I tried to explain best than I could Hope it is useful
HINT: $$x=a+b$$ and $$x=-(a+b)$$ are two Solutions and now you can divide your equation $$x^4-4abx^2-(a^2-b^2)^2$$ by $$x^2+(a+b)^2$$ note that your equation can factorized into $$- \left( {a}^{2}-2\,ab+{b}^{2}+{x}^{2} \right) \left( b+a+x \right) \left( b+a-x \right) $$
20,254,346
I'm trying to save my list of images to a folder determined by the user, in this case I have this list. ``` List<System.Drawing.Image> ListOfSystemDrawingImage = new List<System.Drawing.Image>(); ListOfSystemDrawingImage.Add(MatrizWPF.Properties.Resources.Earth); ListOfSystemDrawingImage.Add(MatrizWPF.Properties.Resources.Grass); ListOfSystemDrawingImage.Add(MatrizWPF.Properties.Resources.Rabbit); ListOfSystemDrawingImage.Add(MatrizWPF.Properties.Resources.Wolf); ``` Where Earth, Grass, Rabbit and Wolf are PNG images called the same way. My question is, How can I store my ``` List<System.Drawing.Image> listOfSystemDrawingImage = new List<System.Drawing.Image>(); ``` To a folder determined by the user?
2013/11/27
['https://Stackoverflow.com/questions/20254346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3023107/']
You can use `System.Windows.Forms.FolderBrowserDialog` for the user to pick the destination folder and use the `Image.Save` to save the image in the format of your chioce Example: ``` List<System.Drawing.Image> listOfSystemDrawingImage = new List<System.Drawing.Image>(); System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog(); if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { int index = 0; foreach (var image in listOfSystemDrawingImage) { image.Save(string.Format("{0}\\Image{1}.png", dialog.SelectedPath, index), System.Drawing.Imaging.ImageFormat.Png); index++; } } ``` **However, I do not recommend mixing Window.Forms and System.Drawing with WPF,**
If you have the names you can just convert the image to a byte array and then use `File.WriteAllBytes`. Make sure the file name you pass toe `WriteAllBytes` has a .png extension. There's probably a simpler way but I don't really deal with media like that as much as raw data so this is what comes to mind for me.
20,254,346
I'm trying to save my list of images to a folder determined by the user, in this case I have this list. ``` List<System.Drawing.Image> ListOfSystemDrawingImage = new List<System.Drawing.Image>(); ListOfSystemDrawingImage.Add(MatrizWPF.Properties.Resources.Earth); ListOfSystemDrawingImage.Add(MatrizWPF.Properties.Resources.Grass); ListOfSystemDrawingImage.Add(MatrizWPF.Properties.Resources.Rabbit); ListOfSystemDrawingImage.Add(MatrizWPF.Properties.Resources.Wolf); ``` Where Earth, Grass, Rabbit and Wolf are PNG images called the same way. My question is, How can I store my ``` List<System.Drawing.Image> listOfSystemDrawingImage = new List<System.Drawing.Image>(); ``` To a folder determined by the user?
2013/11/27
['https://Stackoverflow.com/questions/20254346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3023107/']
You can use `System.Windows.Forms.FolderBrowserDialog` for the user to pick the destination folder and use the `Image.Save` to save the image in the format of your chioce Example: ``` List<System.Drawing.Image> listOfSystemDrawingImage = new List<System.Drawing.Image>(); System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog(); if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { int index = 0; foreach (var image in listOfSystemDrawingImage) { image.Save(string.Format("{0}\\Image{1}.png", dialog.SelectedPath, index), System.Drawing.Imaging.ImageFormat.Png); index++; } } ``` **However, I do not recommend mixing Window.Forms and System.Drawing with WPF,**
You can save the list of `System.Drawing.Image` this way: ``` string folder = @"C:\temp"; int count = 1; foreach(Image image in listOfSystemDrawingImage) { string path = Path.Combine(folder, String.Format("image{0}.png", count)); image.Save(path); count++; } ``` I don't know where you store the image names, so I just called them image1.png, image2.png, and so on.
81,063
I submitted an article around 11 months ago to a SCI journal and another article around 5 months ago in another SCI journal. The second article cited the first article which was under review for 6 months at the time of submission of second article. Recently, we got acceptance letter for 2nd article while 1st article is still under review. What action should we take? remove the citation in 2nd article and cite the 2nd article in 1st article or we stay with the current situation. but what if our 1st article got rejection?
2016/12/05
['https://academia.stackexchange.com/questions/81063', 'https://academia.stackexchange.com', 'https://academia.stackexchange.com/users/9709/']
If I understand correctly, this is your situation: * Paper 1 was submitted for review 11 months ago * Paper 2 was submitted for review six months later. * Paper 2 was accepted for publication. Paper 1 is still under review. Presumably, Paper 2 cites Paper 1 as being "submitted". The present version of Paper 1 does not cite Paper 2 because Paper 2 was not in existence when Paper 1 was submitted. Are these correct? If so, here are some thoughts about your questions: **Should you continue to cite Paper 1 in Paper 2?** I would. The fact that Paper 1 is still under review is out of your control. In fact, its final disposition is also up in the air. Nevertheless, Paper 2 uses information derived from Paper 1, hence the need to cite it. That Paper 2 was accepted with the citation to Paper 1 is important evidence that the reviewers and the editors thought that it was appropriate, despite the "submitted" tag. **Should you remove the citation of Paper 1 in Paper 2?** I wouldn't do this, unless there was a material change in your manuscript. If the parts of Paper 2 that depend on Paper 1 were lost in revision, then fine. However, it is not a good idea to eliminate references simply because of publication status. **Should you cite Paper 2 in Paper 1?** You should only cite papers that support your statements. Frivolously citing one paper of yours just because it was published is a rather trivial reason. However, if you genuinely feel that Paper 2 has substantial contributions to Paper 1, then this should be fine. You would do this in the revision stage. Be aware, though, that alert editorial staff may review this change with skepticism. **If you retain the citation of Paper 1 in Paper 2 and Paper 1 gets rejected, then what happens?** Generally, there's nothing you can do about this. Journals still operate as if the manuscripts were static entities. That is to say, once a final version has been approved at the galley stage, no changes can be made. Paper 1 will always be cited in Paper 2 as being "submitted" in perpetuity. There are some publishing models now that account for this fluidity in publication status, although there are not widespread, and rather experimental. Say, for example, that you cited the work of Doorman (2014) and your work was published in 2015. In 2016, Doorman was found to have committed research misconduct and his 2014 publication was retracted because all the data were fabricated. Well, your 2015 publication would still cite Doorman 2014. There are no easy solutions to this issue as yet. Good luck.
If the second article depends in some substantive way in the material from the first, the second should cite the first, according to the journal's policy for material under review. (Different journals tend to handle such matters in different ways.) If there is no real dependence, I would suggest omitting the citation, and having the first paper, when it gets published, cite the second. Having each paper cite the others might be deemed less than optimal, but that does happen. If you don't have a problem with the circular citation arrangement, I would include a citation to the second, published article in the first, even if the second already cites the first.
81,063
I submitted an article around 11 months ago to a SCI journal and another article around 5 months ago in another SCI journal. The second article cited the first article which was under review for 6 months at the time of submission of second article. Recently, we got acceptance letter for 2nd article while 1st article is still under review. What action should we take? remove the citation in 2nd article and cite the 2nd article in 1st article or we stay with the current situation. but what if our 1st article got rejection?
2016/12/05
['https://academia.stackexchange.com/questions/81063', 'https://academia.stackexchange.com', 'https://academia.stackexchange.com/users/9709/']
If the second article depends in some substantive way in the material from the first, the second should cite the first, according to the journal's policy for material under review. (Different journals tend to handle such matters in different ways.) If there is no real dependence, I would suggest omitting the citation, and having the first paper, when it gets published, cite the second. Having each paper cite the others might be deemed less than optimal, but that does happen. If you don't have a problem with the circular citation arrangement, I would include a citation to the second, published article in the first, even if the second already cites the first.
The traditional method to avoid these messes was to refer to any work as ***forthcoming*** until such a time as the work having definitely and definitively entered the literature. So yes, it did happen that certain papers were eternally immortalised as "forthcoming" - and as a reader you could be in for a bit of detective work (this was back when you had to physically schlepp to an actual brick and mortar library). A fun and not infrequent intermediate case arose when a promise was made or a claim was staked for the forthcoming paper, which, once it did come forth, was never made good on! Preprints were always a patchwork solution (as physical copies could be hard to track down), but luckily now we have archiv, BioArchiv and the like. Authors' personal webpages may help, but beware, as different authors may link to different versions of the work.
81,063
I submitted an article around 11 months ago to a SCI journal and another article around 5 months ago in another SCI journal. The second article cited the first article which was under review for 6 months at the time of submission of second article. Recently, we got acceptance letter for 2nd article while 1st article is still under review. What action should we take? remove the citation in 2nd article and cite the 2nd article in 1st article or we stay with the current situation. but what if our 1st article got rejection?
2016/12/05
['https://academia.stackexchange.com/questions/81063', 'https://academia.stackexchange.com', 'https://academia.stackexchange.com/users/9709/']
If I understand correctly, this is your situation: * Paper 1 was submitted for review 11 months ago * Paper 2 was submitted for review six months later. * Paper 2 was accepted for publication. Paper 1 is still under review. Presumably, Paper 2 cites Paper 1 as being "submitted". The present version of Paper 1 does not cite Paper 2 because Paper 2 was not in existence when Paper 1 was submitted. Are these correct? If so, here are some thoughts about your questions: **Should you continue to cite Paper 1 in Paper 2?** I would. The fact that Paper 1 is still under review is out of your control. In fact, its final disposition is also up in the air. Nevertheless, Paper 2 uses information derived from Paper 1, hence the need to cite it. That Paper 2 was accepted with the citation to Paper 1 is important evidence that the reviewers and the editors thought that it was appropriate, despite the "submitted" tag. **Should you remove the citation of Paper 1 in Paper 2?** I wouldn't do this, unless there was a material change in your manuscript. If the parts of Paper 2 that depend on Paper 1 were lost in revision, then fine. However, it is not a good idea to eliminate references simply because of publication status. **Should you cite Paper 2 in Paper 1?** You should only cite papers that support your statements. Frivolously citing one paper of yours just because it was published is a rather trivial reason. However, if you genuinely feel that Paper 2 has substantial contributions to Paper 1, then this should be fine. You would do this in the revision stage. Be aware, though, that alert editorial staff may review this change with skepticism. **If you retain the citation of Paper 1 in Paper 2 and Paper 1 gets rejected, then what happens?** Generally, there's nothing you can do about this. Journals still operate as if the manuscripts were static entities. That is to say, once a final version has been approved at the galley stage, no changes can be made. Paper 1 will always be cited in Paper 2 as being "submitted" in perpetuity. There are some publishing models now that account for this fluidity in publication status, although there are not widespread, and rather experimental. Say, for example, that you cited the work of Doorman (2014) and your work was published in 2015. In 2016, Doorman was found to have committed research misconduct and his 2014 publication was retracted because all the data were fabricated. Well, your 2015 publication would still cite Doorman 2014. There are no easy solutions to this issue as yet. Good luck.
The traditional method to avoid these messes was to refer to any work as ***forthcoming*** until such a time as the work having definitely and definitively entered the literature. So yes, it did happen that certain papers were eternally immortalised as "forthcoming" - and as a reader you could be in for a bit of detective work (this was back when you had to physically schlepp to an actual brick and mortar library). A fun and not infrequent intermediate case arose when a promise was made or a claim was staked for the forthcoming paper, which, once it did come forth, was never made good on! Preprints were always a patchwork solution (as physical copies could be hard to track down), but luckily now we have archiv, BioArchiv and the like. Authors' personal webpages may help, but beware, as different authors may link to different versions of the work.
114,561
I am a GIS beginner, and I have a question about how to get the distance between two points in meters instead of decimal degree. In QGIS 2.4 I have a project with two point layers (in WGS84). From both layers I used I wanted to have the distance in meters between the two closest point between the layers. So what I did: Vector -> analyse tools -> distance Matrix, ticked the box "only nearest (k) target points: 1". This created a CSV file with all the distances, but in the wrong units. So I looked it up on the internet and I found out two things: * I have to set my CRV in a projected coordinate system (like a UTM zone). * And I have to tick or untick the box with "on the fly" --> which I cannot find in QGIS2.4 Project --> project setting --> CRS. I tried the first option. I tried to set the layers in UTM 29 ZONE IRENET95, EPSG: 2158 by "save as" --> add new vector layer. It still gives the distance in the wrong units. My project only contains point in southwest Ireland, so that is why I picked this projection. Or should I project it in a different projection? I also tried to find a converter to convert the decimal degree outcome to meters, but I did not find any. I guess there is none. Am I right? For me it seems like there must me an easy solution, but I did not manage to find one. I think I am doing something wrong with setting the layers in a different projection.
2014/09/21
['https://gis.stackexchange.com/questions/114561', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/37252/']
gdal\_Calc.py can do that, a reclass Something like.. gdal\_calc.py -A filename.tiff --outfile=filename.tiff --calc="A\*(A>3)" --NoDataValue=0 --calc="1\*(A<3) See this one [gdal\_calc.py raster reclass equivalent of ArcGIS reclass or r.reclass in grass](https://gis.stackexchange.com/questions/100348/gdal-calc-py-raster-reclass-equivalent-of-arcgis-reclass-or-r-reclass-in-grass)
If the min value is consistent - like a no data value, you might be able to use the snodata option and specify the value you want ignore. As listed in the doc for [gdal\_contour](http://www.gdal.org/gdal_contour.html)
2,127,460
Prove $$I=\int\_0^\infty {\frac{x}{{\left( {x + 1} \right)\sqrt {4{x^4} + 8{x^3} + 12{x^2} + 8x + 1} }}dx} = \frac{{\ln 3}}{2} - \frac{{\ln 2}}{3}.$$ First note that $$4{x^4} + 8{x^3} + 12{x^2} + 8x + 1 = 4{\left( {{x^2} + x + 1} \right)^2} - 3,$$ we let $${x^2} + x + 1 = \frac{{\sqrt 3 }}{{2\cos \theta }} \Rightarrow x = \sqrt { - \frac{3}{4} + \frac{{\sqrt 3 }}{{2\cos \theta }}} - \frac{1}{2},$$ then $$I=\frac{1}{2}\int\_{\frac{\pi }{6}}^{\frac{\pi }{2}} {\frac{{\left( {\sqrt {2\sqrt 3 \sec \theta - 3} - 1} \right)\sec \theta }}{{\left( {\sqrt {2\sqrt 3 \sec \theta - 3} + 1} \right)\sqrt {2\sqrt 3 \sec \theta - 3} }}d\theta } .$$ we have \begin{align\*} &\frac{{\left( {\sqrt {2\sqrt 3 \sec \theta - 3} - 1} \right)\sec \theta }}{{\left( {\sqrt {2\sqrt 3 \sec \theta - 3} + 1} \right)\sqrt {2\sqrt 3 \sec \theta - 3} }} = \frac{{{{\left( {\sqrt {2\sqrt 3 \sec \theta - 3} - 1} \right)}^2}\sec \theta }}{{\left( {2\sqrt 3 \sec \theta - 4} \right)\sqrt {2\sqrt 3 \sec \theta - 3} }}\\ =& \frac{{\left( {2\sqrt 3 \sec \theta - 2 - 2\sqrt {2\sqrt 3 \sec \theta - 3} } \right)\sec \theta }}{{\left( {2\sqrt 3 \sec \theta - 4} \right)\sqrt {2\sqrt 3 \sec \theta - 3} }} = \frac{{\left( {\sqrt 3 \sec \theta - 1 - \sqrt {2\sqrt 3 \sec \theta - 3} } \right)\sec \theta }}{{\left( {\sqrt 3 \sec \theta - 2} \right)\sqrt {2\sqrt 3 \sec \theta - 3} }}\\ = &\frac{{\left( {\sqrt 3 \sec \theta - 1} \right)\sec \theta }}{{\left( {\sqrt 3 \sec \theta - 2} \right)\sqrt {2\sqrt 3 \sec \theta - 3} }} - \frac{{\sec \theta }}{{\sqrt 3 \sec \theta - 2}}. \end{align\*} and $$\int {\frac{{\sec \theta }}{{\sqrt 3 \sec \theta - 2}}d\theta } = \ln \frac{{\left( {2 + \sqrt 3 } \right)\tan \frac{\theta }{2} - 1}}{{\left( {2 + \sqrt 3 } \right)\tan \frac{\theta }{2} + 1}}+ C.$$ while \begin{align\*}&\int {\frac{{\left( {\sqrt 3 \sec \theta - 1} \right)\sec \theta }}{{\left( {\sqrt 3 \sec \theta - 2} \right)\sqrt {2\sqrt 3 \sec \theta - 3} }}d\theta } = \int {\frac{{\sqrt 3 - \cos \theta }}{{\left( {\sqrt 3 - 2\cos \theta } \right)\sqrt {2\sqrt 3 \cos \theta - 3{{\left( {\cos \theta } \right)}^2}} }}d\theta } \\ = &\frac{1}{2}\int {\frac{1}{{\sqrt {2\sqrt 3 \cos \theta - 3{{\left( {\cos \theta } \right)}^2}} }}d\theta } + \frac{{\sqrt 3 }}{2}\int {\frac{1}{{\left( {\sqrt 3 - 2\cos \theta } \right)\sqrt {2\sqrt 3 \cos \theta - 3{{\left( {\cos \theta } \right)}^2}} }}d\theta } . \end{align\*} But how can we continue? It is related to elliptic integral.
2017/02/03
['https://math.stackexchange.com/questions/2127460', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/165013/']
This is a pseudo-elliptic integral, it has an elementary anti-derivative: $$\int \frac{x}{(x+1)\sqrt{4x^4+8x^3+12x^2+8x+1}} dx = \frac{\ln\left[P(x)+Q(x)\sqrt{4x^4+8x^3+12x^2+8x+1}\right]}{6} - \ln(x+1) + C$$ where $$P(x) = 112x^6+360x^5+624x^4+772x^3+612x^2+258x+43$$ and $$Q(x) = 52x^4+92x^3+30x^2-22x-11$$ To obtain this answer, just follow the systematic method of symbolic integration over simple algebraic extension. Alternatively, you can throw it to a CAS with Risch algorithm implemented (**not Mathematica**), a convenient software is the online **Axiom sandbox**.
**HINT 1** $$x=2x+1-(x+1),$$ so $$I=\frac12\int\_0^\infty\frac{(2x+1)dx}{(x+1)\sqrt{(x^2+x+1)^2-\frac34}} - \frac12\int\_0^\infty\frac{(2x+1)dx}{(2x+1)\sqrt{(x^2+x+1)^2-\frac34}}.$$ **HINT 2** $$(2x+1)dx = d(x^2+x+1) = \frac{\sqrt3}2d\sec\theta$$
2,514
I am trying to start `carthagenet.sh` in RPC mode on Ubuntu 18.04 ``` $ ./carthagenet.sh start --rpc-port 8732 ``` It appears to start fine: ``` v7.0: Pulling from tezos/tezos Digest: sha256:da126e8d6bf137a9b326c3992c0e464622b94e2ee42b7d311df158212b8ae153 Status: Image is up to date for tezos/tezos:v7.0 docker.io/tezos/tezos:v7.0 Creating network "carthagenet_default" with the default driver Creating carthagenet_node_1 ... done Creating carthagenet_upgrader_1 ... done Creating carthagenet_baker-006-PsCARTHA-test_1 ... done Creating carthagenet_endorser-alpha-test_1 ... done Creating carthagenet_endorser-006-PsCARTHA_1 ... done Creating carthagenet_baker-006-PsCARTHA_1 ... done Creating carthagenet_accuser-alpha_1 ... done Creating carthagenet_accuser-006-PsCARTHA-test_1 ... done Creating carthagenet_accuser-alpha-test_1 ... done Creating carthagenet_endorser-006-PsCARTHA-test_1 ... done Creating carthagenet_baker-alpha-test_1 ... done Creating carthagenet_endorser-alpha_1 ... done Creating carthagenet_baker-alpha_1 ... done Creating carthagenet_accuser-006-PsCARTHA_1 ... done ``` However, as soon as I run any command I get an error: ``` $ ./carthagenet.sh client list known addresses Error response from daemon: Container 9920d6b346868d3d5491c0cd88eee100189c470d2107fa49cde6086568ec1383 is restarting, wait until the container is running ``` I used the following command to debug issues with the docker container: ``` docker logs --tail 50 --follow --timestamps 9920d6b346868d3d5491c0cd88eee100189c470d21 ``` It appears the docker container keeps trying to restart with this error message: ``` 2020-05-14T07:02:29.592446544Z Current public chain: 2018-06-30T16:07:32Z. 2020-05-14T07:02:29.593149945Z Local chain data: 2018-06-30T16:07:32Z. 2020-05-14T07:02:29.593724545Z Updating the node configuration... 2020-05-14T07:02:29.666034593Z tezos-node: unknown option `--rpc-port'. 2020-05-14T07:02:29.666059993Z Usage: tezos-node config [OPTION]... [OPERATION] 2020-05-14T07:02:29.666064593Z Try `tezos-node config --help' or `tezos-node --help' for more information. ``` All documentation I find seems to suggest --rpc-port is the correct option. Where could I be having issues?
2020/05/14
['https://tezos.stackexchange.com/questions/2514', 'https://tezos.stackexchange.com', 'https://tezos.stackexchange.com/users/4999/']
First off, never risk more than you can afford. Secondly, your funds are not stuck. If you look at your address, <https://tzstats.com/tz1WBKfsPLp94D7wscTRn8KFt9pBfEopdUYr>, everything is still there. As the operation shows, the operation backtracked so, no, nothing transfered. Restart your trezor and try the transfer again. Remember, your tokens are stored on the chain, not in the device.
I have the exact same problem except a small amount. I transferred a small amount of XTZ from my coinbase account to simplestaking via my Trezor T. That went fine. Then a couple of days later, I tried to send the XTZ back to coinbase. The same thing happened that you described. I opened a chat with simplestaking to ask what the problem is. According to them, it is a known issue that is related to the latest Trezor connect update. They said they are working on a fix. They didn't tell me what will happen when they fix the bug. So I don't know if the transaction will eventually go through or it will just be canceled and the fee returned. My guess it will just be canceled and I will have to transfer later. The reason I was doing this small transfer of XTZ to/from coinbase was to test simplestaking to decide if I wanted to move all my XTZ there....LOL However, whenever I plan on transferring a large amount of anything, I always first transfer a small amount to ensure it transfers as expected. This bug reinforces in me why I do this. I would rather pay a small extra fee then have an unnerving situation occur with a large amount. Update: I went back on simplestaking a week later and the transaction was voided and the XTZ back in the wallet. However, I see they still charged the transfer 0.010 fee. I don't think they should be charging the fee with something like that. Does anyone know if this bug has been fixed yet? I don't want to try again until I hear it's fixed.
37,563,013
I have some variable like this; ``` <?php the_field('reviews'); ?> ``` This variable prints; ``` Some text 1 Some text 2 Some text 3 Some text 4 ``` source code is here: [![](https://i.stack.imgur.com/9vm5Q.jpg)](https://i.stack.imgur.com/9vm5Q.jpg) and look like this [![](https://i.stack.imgur.com/vj98f.jpg)](https://i.stack.imgur.com/vj98f.jpg) Now, i want to convert **br** tag to **hr** like this [![enter image description here](https://i.stack.imgur.com/OLgCz.jpg)](https://i.stack.imgur.com/OLgCz.jpg) I tried the following ***[nospor](https://stackoverflow.com/users/6356056/nospor)***'s codes but not worked. ``` $change = the_field('reviews'); $change = str_replace(array('<br>', '</br>'), array('', '<hr>'), $change); echo $change; ``` How can i change that **br** tags to **hr** tag with PHP?
2016/06/01
['https://Stackoverflow.com/questions/37563013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2745938/']
`<br>Some text 1</br>` - wow.... who wrote that? Anyway... do it as simple as possible ;) ``` $change = the_field('reviews'); $change = str_replace(array('<br>', '</br>'), array('', '<hr>'), $change); echo $change; ``` edit: Probably instead of `the_field` you should use `get_field` because first one displays it and second returns.
``` $string= the_field('reviews'); $change = str_replace( array('<br>', '</br>'), array('<hr>', ''), $string ); echo $change; ``` Use simple php str\_replace function
37,563,013
I have some variable like this; ``` <?php the_field('reviews'); ?> ``` This variable prints; ``` Some text 1 Some text 2 Some text 3 Some text 4 ``` source code is here: [![](https://i.stack.imgur.com/9vm5Q.jpg)](https://i.stack.imgur.com/9vm5Q.jpg) and look like this [![](https://i.stack.imgur.com/vj98f.jpg)](https://i.stack.imgur.com/vj98f.jpg) Now, i want to convert **br** tag to **hr** like this [![enter image description here](https://i.stack.imgur.com/OLgCz.jpg)](https://i.stack.imgur.com/OLgCz.jpg) I tried the following ***[nospor](https://stackoverflow.com/users/6356056/nospor)***'s codes but not worked. ``` $change = the_field('reviews'); $change = str_replace(array('<br>', '</br>'), array('', '<hr>'), $change); echo $change; ``` How can i change that **br** tags to **hr** tag with PHP?
2016/06/01
['https://Stackoverflow.com/questions/37563013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2745938/']
`<br>Some text 1</br>` - wow.... who wrote that? Anyway... do it as simple as possible ;) ``` $change = the_field('reviews'); $change = str_replace(array('<br>', '</br>'), array('', '<hr>'), $change); echo $change; ``` edit: Probably instead of `the_field` you should use `get_field` because first one displays it and second returns.
[Above answer](https://stackoverflow.com/a/37563100/3536236) is exactly correct. You should use `str_replace` the different between `str_replace` and `preg_replace` ``` $string = "foo fighters"; $str_replace = str_replace('foo','bar',$string); $preg_replace = preg_replace('/f.{2}/','bar',$string); echo 'str_replace: ' . $str_replace . ', preg_replace: ' . $preg_replace; ``` the output will be: ``` str_replace: bar fighters, preg_replace: bar barhters ```
37,563,013
I have some variable like this; ``` <?php the_field('reviews'); ?> ``` This variable prints; ``` Some text 1 Some text 2 Some text 3 Some text 4 ``` source code is here: [![](https://i.stack.imgur.com/9vm5Q.jpg)](https://i.stack.imgur.com/9vm5Q.jpg) and look like this [![](https://i.stack.imgur.com/vj98f.jpg)](https://i.stack.imgur.com/vj98f.jpg) Now, i want to convert **br** tag to **hr** like this [![enter image description here](https://i.stack.imgur.com/OLgCz.jpg)](https://i.stack.imgur.com/OLgCz.jpg) I tried the following ***[nospor](https://stackoverflow.com/users/6356056/nospor)***'s codes but not worked. ``` $change = the_field('reviews'); $change = str_replace(array('<br>', '</br>'), array('', '<hr>'), $change); echo $change; ``` How can i change that **br** tags to **hr** tag with PHP?
2016/06/01
['https://Stackoverflow.com/questions/37563013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2745938/']
`<br>Some text 1</br>` - wow.... who wrote that? Anyway... do it as simple as possible ;) ``` $change = the_field('reviews'); $change = str_replace(array('<br>', '</br>'), array('', '<hr>'), $change); echo $change; ``` edit: Probably instead of `the_field` you should use `get_field` because first one displays it and second returns.
`<br> </br>` is incorrect. **HTML** `<br>` is an empty tag,so there is no end tag. **XHTML** `<br />` then you can use function `str_replace` to relace "br" by "hr" ``` $tag_br = array( "<br>", "</br>" ); $tag_hr = array( "<hr>", "" ); $change = str_replace($tag_br,$tag_hr ,$change); ```
37,563,013
I have some variable like this; ``` <?php the_field('reviews'); ?> ``` This variable prints; ``` Some text 1 Some text 2 Some text 3 Some text 4 ``` source code is here: [![](https://i.stack.imgur.com/9vm5Q.jpg)](https://i.stack.imgur.com/9vm5Q.jpg) and look like this [![](https://i.stack.imgur.com/vj98f.jpg)](https://i.stack.imgur.com/vj98f.jpg) Now, i want to convert **br** tag to **hr** like this [![enter image description here](https://i.stack.imgur.com/OLgCz.jpg)](https://i.stack.imgur.com/OLgCz.jpg) I tried the following ***[nospor](https://stackoverflow.com/users/6356056/nospor)***'s codes but not worked. ``` $change = the_field('reviews'); $change = str_replace(array('<br>', '</br>'), array('', '<hr>'), $change); echo $change; ``` How can i change that **br** tags to **hr** tag with PHP?
2016/06/01
['https://Stackoverflow.com/questions/37563013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2745938/']
[Above answer](https://stackoverflow.com/a/37563100/3536236) is exactly correct. You should use `str_replace` the different between `str_replace` and `preg_replace` ``` $string = "foo fighters"; $str_replace = str_replace('foo','bar',$string); $preg_replace = preg_replace('/f.{2}/','bar',$string); echo 'str_replace: ' . $str_replace . ', preg_replace: ' . $preg_replace; ``` the output will be: ``` str_replace: bar fighters, preg_replace: bar barhters ```
``` $string= the_field('reviews'); $change = str_replace( array('<br>', '</br>'), array('<hr>', ''), $string ); echo $change; ``` Use simple php str\_replace function
37,563,013
I have some variable like this; ``` <?php the_field('reviews'); ?> ``` This variable prints; ``` Some text 1 Some text 2 Some text 3 Some text 4 ``` source code is here: [![](https://i.stack.imgur.com/9vm5Q.jpg)](https://i.stack.imgur.com/9vm5Q.jpg) and look like this [![](https://i.stack.imgur.com/vj98f.jpg)](https://i.stack.imgur.com/vj98f.jpg) Now, i want to convert **br** tag to **hr** like this [![enter image description here](https://i.stack.imgur.com/OLgCz.jpg)](https://i.stack.imgur.com/OLgCz.jpg) I tried the following ***[nospor](https://stackoverflow.com/users/6356056/nospor)***'s codes but not worked. ``` $change = the_field('reviews'); $change = str_replace(array('<br>', '</br>'), array('', '<hr>'), $change); echo $change; ``` How can i change that **br** tags to **hr** tag with PHP?
2016/06/01
['https://Stackoverflow.com/questions/37563013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2745938/']
`<br> </br>` is incorrect. **HTML** `<br>` is an empty tag,so there is no end tag. **XHTML** `<br />` then you can use function `str_replace` to relace "br" by "hr" ``` $tag_br = array( "<br>", "</br>" ); $tag_hr = array( "<hr>", "" ); $change = str_replace($tag_br,$tag_hr ,$change); ```
``` $string= the_field('reviews'); $change = str_replace( array('<br>', '</br>'), array('<hr>', ''), $string ); echo $change; ``` Use simple php str\_replace function
37,563,013
I have some variable like this; ``` <?php the_field('reviews'); ?> ``` This variable prints; ``` Some text 1 Some text 2 Some text 3 Some text 4 ``` source code is here: [![](https://i.stack.imgur.com/9vm5Q.jpg)](https://i.stack.imgur.com/9vm5Q.jpg) and look like this [![](https://i.stack.imgur.com/vj98f.jpg)](https://i.stack.imgur.com/vj98f.jpg) Now, i want to convert **br** tag to **hr** like this [![enter image description here](https://i.stack.imgur.com/OLgCz.jpg)](https://i.stack.imgur.com/OLgCz.jpg) I tried the following ***[nospor](https://stackoverflow.com/users/6356056/nospor)***'s codes but not worked. ``` $change = the_field('reviews'); $change = str_replace(array('<br>', '</br>'), array('', '<hr>'), $change); echo $change; ``` How can i change that **br** tags to **hr** tag with PHP?
2016/06/01
['https://Stackoverflow.com/questions/37563013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2745938/']
`<br> </br>` is incorrect. **HTML** `<br>` is an empty tag,so there is no end tag. **XHTML** `<br />` then you can use function `str_replace` to relace "br" by "hr" ``` $tag_br = array( "<br>", "</br>" ); $tag_hr = array( "<hr>", "" ); $change = str_replace($tag_br,$tag_hr ,$change); ```
[Above answer](https://stackoverflow.com/a/37563100/3536236) is exactly correct. You should use `str_replace` the different between `str_replace` and `preg_replace` ``` $string = "foo fighters"; $str_replace = str_replace('foo','bar',$string); $preg_replace = preg_replace('/f.{2}/','bar',$string); echo 'str_replace: ' . $str_replace . ', preg_replace: ' . $preg_replace; ``` the output will be: ``` str_replace: bar fighters, preg_replace: bar barhters ```
58,054,390
I have a program written in C that traverses a tree in reverse pre-order, reverse in-order, and reverse post-order whose individual functions rely heavily on recursion. How would I go about modifying these functions so that they perform the exact same task but without using any sort of recursion? I've spent many hours trying to figure that out by using variables that temporarily store values but I keep drawing a blank unfortunately. I'm using the GCC compiler on Ubuntu Linux BTW. Here is my code: ``` #include <stdio.h> #include <stdlib.h> struct node { int data; struct node* left; struct node* right; }; struct node* newNode(int data) { struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node); } void reversePostOrder(struct node* node) { if (node == NULL) return; reversePostOrder(node->right); reversePostOrder(node->left); printf("%d ", node->data); } void reverseInOrder(struct node* node) { if (node == NULL) return; reverseInOrder(node->right); printf("%d ", node->data); reverseInOrder(node->left); } void reversePreOrder(struct node* node) { if (node == NULL) return; printf("%d ", node->data); reversePreOrder(node->right); reversePreOrder(node->left); } int main() { struct node *root = newNode(1); root->left = newNode(-2); root->right = newNode(-3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left =newNode(6); root->right->right=newNode(7); root->left->right->left=newNode(-8); root->left->right->right=newNode(-9); root->right->right->left=newNode(10); root->right->right->right=newNode(11); root->right->right->right->left=newNode(-12); root->right->right->right->right=newNode(-13); root->right->right->right->right->left=newNode(14); printf("\nReverse Preorder traversal of binary tree is \n"); reversePreOrder(root); printf("\nReverse Inorder traversal of binary tree is \n"); reverseInOrder(root); printf("\nReverse Postorder traversal of binary tree is \n"); reversePostOrder(root); getchar(); return 0; } ```
2019/09/23
['https://Stackoverflow.com/questions/58054390', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12076645/']
The problem is made difficult because your list nodes do not have pointers to their parents. When an iterative/imperative procedure marches down the left or right link of the current node to navigate to another node, it has no reverse path. There are two general approaches to the problem: 1. Maintain an explicit stack which enables the procedure to navigate to the parent. 2. Mutate the tree itself temporarily to provide a return path. That is to say, overwrite the `left` and `right` links with reverse pointers to the parent temporarily; then restore the values when returning up the tree. If the tree is a balanced tree with a guaranteed maximum depth, then (1) can be implemented with a reasonably small, fixed-size array.
you can use a stack to store the parent and an array if a node was previously processed or not before. example for inorder ``` push(root) while stack is not empty() parent=stack.top() if parent->left and done[parent->left]==false left=parent->left push(parent) done[left]=true continue if done[parent]==false process(parent) done[parent]=true if parent->right and done[parent->right]==false right=parent->right push(right) done[right]=true continue stack.pop() ```
37,918,148
I'm building a simple shopping cart for a site and have been working on the `add to cart`action. While I have ti working I feel there is probably a simple more elegant way of doing it. This is the starting state: ``` start_state = { inventory: [ {sku: "product_1", price: 600, name: "Product 1"}, {sku: "product_2", price: 800, name: "Product 2"} ], cart: [] } ``` And this is the desired end state: ``` start_state = { inventory: [ {sku: "product_1", price: 600, name: "Product 1"}, {sku: "product_2", price: 800, name: "Product 2"} ], cart: [ {sku: "product_1", quantity: 2}, {sku: "product_2", quantity: 1} ] } ``` And this is the function Im triggering to take it from the initial state to new final\_state, the `sku` argument is the item from the state that is passed in when the action is called: ``` addToCart: function (sku) { let currentCart = this.state.cart let itemInCart = _.findIndex(currentCart, ['sku', sku]) let newItem = { sku: sku } if (itemInCart !== -1) { let newQuantity = currentCart[itemInCart].quantity newItem.quantity = newQuantity + 1 } else { newItem.quantity = 1 } let filteredCart = _.filter(currentCart, (item) => { return item.sku !== sku }) let newCart = _.concat(filteredCart, newItem) this.setState({cart: newCart}) }, ```
2016/06/20
['https://Stackoverflow.com/questions/37918148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1945168/']
Since you are using ES6, you can use some of its new features like `findIndex` and `Object.assign` to achieve what you want. ``` addToCart: function(product) { let index = this.state.cart.findIndex((x) => x.sku === product.sku); if(index === -1) { let newProduct = {sku: product.sku, quantity:1} this.setState({cart : this.state.cart.concat([newProduct])}) } else { let newCart = Object.assign([], this.state.cart); newCart[index].quantity = newCart[index].quantity+1; this.setState({cart: newCart}); } } ``` [full working example](http://jsfiddle.net/jwm6k66c/638/)
I think this way is better: ``` function getCardWithIncItem(currentCart, itemInCart) { return [ ...currentCart.slice(0, itemInCart), Object.assign({}, currentCart[itemInCart], { quantity: currentCart[itemInCart].quantity + 1, }), ...currentCart.slice(itemInCart + 1), ]; } function getCardWithNewItem(currentCart, sku) { return [ ...currentCart, { sku: sku, quantity: 1, } ]; } const currentCart = this.state.cart; const itemInCart = _.findIndex(currentCart, ['sku', sku]); const newCart = (itemInCart !== -1) ? getCardWithIncItem(currentCart, itemInCart) : getCardWithIncItem(currentCart, sku); this.setState({ cart: newCart, }) ```
35,624,113
I am trying to transfer data between controllers. So this is my first controller that fetches data first when page loads using http- ``` function GetController($scope, $http) { $http.defaults.useXDomain = true; $http({ method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: { 'Authorization': apiKey }, data: { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" } }).then(function successCallback(response) { $scope.products = response.data; }).then(function errorCallback(error) { }) } ``` the view looks like- ``` <div ng-controller="GetController"> <div class="mdl-cell" ng-repeat="product in products"> <img src="{{product.largeImage}}" /> <div class="mdl-card__title"> <h6 class="mdl-card__title-text">{{product.name}}</h6> </div> </div> </div> </div> ``` Where now my need is to rebind this HTML with the same request but different parameters. So I created another controller for this job- ``` function searchProductsController($scope, $http) { $http.defaults.useXDomain = true; $scope.searchText = ""; $scope.submit = function () { $http({ method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: { 'Authorization': apiKey }, data: { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" } }).then(function successCallback(response) { $scope.products = response.data; //how to bind this with GetController's $scope.products?? }).then(function errorCallback(error) { }); } }; ``` **What is needed-** I want to bind `$scope.products` of `searchProductsController` to `GetController's` `$scope.products` so that it renders in view. I don't have any idea how to do this at the moment as I am very new to angular. However, I've given a try to create service for transferring purpose but don't really have idea how to integrate it with it. **Edit-** I've edited controller methods as @Varkal suggested using service, Still couldn't get the problem resolved. ``` var app = angular.module("productsApp", []) .service("serviceProvider", function ($http) { this.getDatas = function getDatas(data) { return $http({ method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: { 'Authorization': apiKey }, data: data }) } return this }); function GetController($scope, serviceProvider) { var data = { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }; serviceProvider.getDatas(data).then(function (response) { $scope.products = response.data.data; }); } function searchProductsController($scope, serviceProvider) { var data = { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }; $scope.submit = function () { serviceProvider.getDatas(data).then(function (response) { console.log(response.data.data); $scope.products = response.data.data; }); } }; ```
2016/02/25
['https://Stackoverflow.com/questions/35624113', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1982631/']
When you need to share things betweens controller, those things should be in a [service](https://docs.angularjs.org/guide/services) For example : ``` angular.service("datasService", function ($http) { this.getDatas = function getDatas() { return $http({ method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: { 'Authorization': apiKey }, data: { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" } }) } return this }); ``` And in your controller : ``` function GetController($scope, datasService) { datasService.getDatas().then(function(){ $scope.products = response.data } } ``` This is a very simple example : you can also store your datas in the service, so call $http only once, and add a method to refresh the product list This is the most "Angular-ly" way of share datas between controllers, but you can also use localStorage ([ngStorage](https://github.com/gsklee/ngStorage) can help you here)
If you have 2 `views` with 2 `controllers`, it is possible to share the `$scope` variables(data) between controllers through services and factory.But, the `$scope` variables are local to the controller itself so set the data to the service or factory to know about that particular variable.I prefer using factory, easy and smooth as butter. If you are using the `service` or `factory` in a separate file you need to include the file in `index.html`. ``` app.controller('Ctrl1', function($scope, myService, $state) { $scope.variable1 = "One"; myService.set($scope.variable1); $state.go('app.thepagewhereyouwanttoshare'); //go to the page where you want to share that variable. }); app.controller('Ctrl2', function($scope, myService) { console.log("shared variable " + myService.get()); }); .factory('myService', function() { function set(data) { products = data; } function get() { return products; } return { set: set, get: get } }) ``` Also, you can use `localstorage` for the purpose of sharing data.`localStorage` comes with `angularjs` so no need to inject any additional dependency in the controller or app. In the controller which has to pass data: ``` localStorage.setItem("products",$scope.products); ``` In the controller where you to access data: ``` localStorage.getItem("products"); ``` **In your case:** ``` function GetController($scope, $http) { $http.defaults.useXDomain = true; $http({ method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: { 'Authorization': apiKey }, data: { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" } }).then(function successCallback(response) { $scope.products = response.data; localStorage.setItem("products",$scope.products); }).then(function errorCallback(error) { }) } function searchProductsController($scope, $http) { $http.defaults.useXDomain = true; $scope.searchText = ""; $scope.submit = function () { $http({ method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: { 'Authorization': apiKey }, data: { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" } }).then(function successCallback(response) { $scope.products = response.data; //how to bind this with GetController's $scope.products?? $scope.productsFromGetController = localStorage.getItem("products"); }).then(function errorCallback(error) { }); } }; ``` Using the `factory`, you need to navigate to the page where you want to get the data after you set it since the data set can be overwritten by another set in another views. **FINAL UPDATE: Using service and factory** ``` <html> <head> <title>Angular JS Controller</title> <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "app" > <div ng-controller="searchProductsController"> <input ng-model="searchText"/> <button ng-click="setPlace(searchText)">Enter Search id</button> </div> <div ng-controller="GetController"> <div ng-repeat="product in products"> <h3>{{product.name}}</h3> </div> </div> </div> <script> var app = angular.module('app', []); app.factory("Service", function () { var data; function getdata() { return data; } function setdata(newdata) { data = newdata; } return { getdata: getdata, setdata: setdata, } }).factory("dataService",function($http){ return{ getComments:function (roomid){ if(roomid==1){ var data = [{"name":"alex","place":"kathmandu"},{"name":"god","place":"seattle"}]; return data; } if(roomid==2) { var newdata = [{"name":"newname","place":"kathmandu"},{"name":"newname2","place":"seattle"}]; return newdata; } } } }); app.controller('searchProductsController',function($scope, Service,$http,dataService) { var data = dataService.getComments(1); Service.setdata(data); $scope.setPlace = function (searchText) { var newdata = dataService.getComments(searchText); Service.setdata(newdata); } }) .controller('GetController',function($scope, Service) { $scope.$watch(function () { return Service.getdata(); }, function (value) { $scope.products = value; }); }) </script> </body> </html> ``` **Update regarding your unworking plunker:** It is closest i can get with the mock of your `controller`: <http://plnkr.co/edit/p9qY1IIWyzYGLehsIOPr?p=preview>
15,982,291
I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! The errors: ``` 1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main 1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals ``` I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. I am using the following code: ``` #include <visa.h> #include "stdafx.h" #include <stdio.h> #include <memory.h> int main(int argc, char* argv[]) { ViSession rm = VI_NULL, vi = VI_NULL; ViStatus status; ViChar buffer[256]; ViUInt32 retCnt; // Open a default session status = viOpenDefaultRM(&rm); if (status < VI_SUCCESS) goto error; // Open the GPIB device at primary address 1, GPIB board 8 status = viOpen(rm, "USB::0x0699::0x0377::C011104::INSTR", VI_NULL, VI_NULL, &vi); if (status < VI_SUCCESS) goto error; // Send an ID query. status = viWrite(vi, (ViBuf) "*idn?", 5, &retCnt); if (status < VI_SUCCESS) goto error; // Clear the buffer and read the response memset(buffer, 0, sizeof(buffer)); status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); if (status < VI_SUCCESS) goto error; // Print the response printf("id: %s\n", buffer); // Clean up viClose(vi); // Not needed, but makes things a bit more // understandable viClose(rm); // Closes resource manager and any sessions // opened with it return 0; error: // Report error and clean up viStatusDesc(vi, status, buffer); fprintf(stderr, "failure: %s\n", buffer); if (rm != VI_NULL) { viClose(rm); } return 1; } ```
2013/04/12
['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']
You could use the [`zero?`](http://ruby-doc.org/core-2.0/File.html#method-c-zero-3F) method: ``` File.zero?("test.rb") ```
One different approach is to iterate over each line and do stuff for each iteration. 0 lines = 0 iterations = no extra code needed.
15,982,291
I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! The errors: ``` 1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main 1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals ``` I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. I am using the following code: ``` #include <visa.h> #include "stdafx.h" #include <stdio.h> #include <memory.h> int main(int argc, char* argv[]) { ViSession rm = VI_NULL, vi = VI_NULL; ViStatus status; ViChar buffer[256]; ViUInt32 retCnt; // Open a default session status = viOpenDefaultRM(&rm); if (status < VI_SUCCESS) goto error; // Open the GPIB device at primary address 1, GPIB board 8 status = viOpen(rm, "USB::0x0699::0x0377::C011104::INSTR", VI_NULL, VI_NULL, &vi); if (status < VI_SUCCESS) goto error; // Send an ID query. status = viWrite(vi, (ViBuf) "*idn?", 5, &retCnt); if (status < VI_SUCCESS) goto error; // Clear the buffer and read the response memset(buffer, 0, sizeof(buffer)); status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); if (status < VI_SUCCESS) goto error; // Print the response printf("id: %s\n", buffer); // Clean up viClose(vi); // Not needed, but makes things a bit more // understandable viClose(rm); // Closes resource manager and any sessions // opened with it return 0; error: // Report error and clean up viStatusDesc(vi, status, buffer); fprintf(stderr, "failure: %s\n", buffer); if (rm != VI_NULL) { viClose(rm); } return 1; } ```
2013/04/12
['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']
You could use the [`zero?`](http://ruby-doc.org/core-2.0/File.html#method-c-zero-3F) method: ``` File.zero?("test.rb") ```
`File.size?('test.rb')` evaluates to `nil` if the file is empty `or` it does not exist. `File.zero?('test.rb')` will return true is the file is empty, but it will return false if the file is not found. Depending on your particular needs you should be careful to use the correct method. As an example in the topic creator's question they specifically asked, "What is the best way to check in Ruby that a file is empty?" The accepted answer does this correctly and will raise a `No such file or directory` error message if the file does not exist. In some situations we may consider the lack of a file to be "equivalent" to an empty file.
15,982,291
I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! The errors: ``` 1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main 1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals ``` I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. I am using the following code: ``` #include <visa.h> #include "stdafx.h" #include <stdio.h> #include <memory.h> int main(int argc, char* argv[]) { ViSession rm = VI_NULL, vi = VI_NULL; ViStatus status; ViChar buffer[256]; ViUInt32 retCnt; // Open a default session status = viOpenDefaultRM(&rm); if (status < VI_SUCCESS) goto error; // Open the GPIB device at primary address 1, GPIB board 8 status = viOpen(rm, "USB::0x0699::0x0377::C011104::INSTR", VI_NULL, VI_NULL, &vi); if (status < VI_SUCCESS) goto error; // Send an ID query. status = viWrite(vi, (ViBuf) "*idn?", 5, &retCnt); if (status < VI_SUCCESS) goto error; // Clear the buffer and read the response memset(buffer, 0, sizeof(buffer)); status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); if (status < VI_SUCCESS) goto error; // Print the response printf("id: %s\n", buffer); // Clean up viClose(vi); // Not needed, but makes things a bit more // understandable viClose(rm); // Closes resource manager and any sessions // opened with it return 0; error: // Report error and clean up viStatusDesc(vi, status, buffer); fprintf(stderr, "failure: %s\n", buffer); if (rm != VI_NULL) { viClose(rm); } return 1; } ```
2013/04/12
['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']
You could use the [`zero?`](http://ruby-doc.org/core-2.0/File.html#method-c-zero-3F) method: ``` File.zero?("test.rb") ```
As of Ruby 2.4.0, there is [File.empty?](https://ruby-doc.org/core-2.4.0/File.html#method-c-empty-3F). (Note that it always returns `false` if you pass it a directory, whether that directory is empty or not: `File.empty?('/') # => false`. So use [Dir.empty?](https://ruby-doc.org/core-2.4.0/Dir.html#method-c-empty-3F) for that instead, or [Pathname#empty?](https://ruby-doc.org/stdlib-2.4.0/libdoc/pathname/rdoc/Pathname.html#method-i-empty-3F) which works for both files and directories.)
15,982,291
I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! The errors: ``` 1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main 1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals ``` I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. I am using the following code: ``` #include <visa.h> #include "stdafx.h" #include <stdio.h> #include <memory.h> int main(int argc, char* argv[]) { ViSession rm = VI_NULL, vi = VI_NULL; ViStatus status; ViChar buffer[256]; ViUInt32 retCnt; // Open a default session status = viOpenDefaultRM(&rm); if (status < VI_SUCCESS) goto error; // Open the GPIB device at primary address 1, GPIB board 8 status = viOpen(rm, "USB::0x0699::0x0377::C011104::INSTR", VI_NULL, VI_NULL, &vi); if (status < VI_SUCCESS) goto error; // Send an ID query. status = viWrite(vi, (ViBuf) "*idn?", 5, &retCnt); if (status < VI_SUCCESS) goto error; // Clear the buffer and read the response memset(buffer, 0, sizeof(buffer)); status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); if (status < VI_SUCCESS) goto error; // Print the response printf("id: %s\n", buffer); // Clean up viClose(vi); // Not needed, but makes things a bit more // understandable viClose(rm); // Closes resource manager and any sessions // opened with it return 0; error: // Report error and clean up viStatusDesc(vi, status, buffer); fprintf(stderr, "failure: %s\n", buffer); if (rm != VI_NULL) { viClose(rm); } return 1; } ```
2013/04/12
['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']
You could use the [`zero?`](http://ruby-doc.org/core-2.0/File.html#method-c-zero-3F) method: ``` File.zero?("test.rb") ```
I think should check like this: ``` def file_empty?(file_path) !(File.file?(file_path) && !File.zero?(file_path)) end ``` so we do not need to worry about file exist or not. File.zero?('test.rb') return false if file not exist
15,982,291
I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! The errors: ``` 1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main 1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals ``` I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. I am using the following code: ``` #include <visa.h> #include "stdafx.h" #include <stdio.h> #include <memory.h> int main(int argc, char* argv[]) { ViSession rm = VI_NULL, vi = VI_NULL; ViStatus status; ViChar buffer[256]; ViUInt32 retCnt; // Open a default session status = viOpenDefaultRM(&rm); if (status < VI_SUCCESS) goto error; // Open the GPIB device at primary address 1, GPIB board 8 status = viOpen(rm, "USB::0x0699::0x0377::C011104::INSTR", VI_NULL, VI_NULL, &vi); if (status < VI_SUCCESS) goto error; // Send an ID query. status = viWrite(vi, (ViBuf) "*idn?", 5, &retCnt); if (status < VI_SUCCESS) goto error; // Clear the buffer and read the response memset(buffer, 0, sizeof(buffer)); status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); if (status < VI_SUCCESS) goto error; // Print the response printf("id: %s\n", buffer); // Clean up viClose(vi); // Not needed, but makes things a bit more // understandable viClose(rm); // Closes resource manager and any sessions // opened with it return 0; error: // Report error and clean up viStatusDesc(vi, status, buffer); fprintf(stderr, "failure: %s\n", buffer); if (rm != VI_NULL) { viClose(rm); } return 1; } ```
2013/04/12
['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']
`File.size?('test.rb')` evaluates to `nil` if the file is empty `or` it does not exist. `File.zero?('test.rb')` will return true is the file is empty, but it will return false if the file is not found. Depending on your particular needs you should be careful to use the correct method. As an example in the topic creator's question they specifically asked, "What is the best way to check in Ruby that a file is empty?" The accepted answer does this correctly and will raise a `No such file or directory` error message if the file does not exist. In some situations we may consider the lack of a file to be "equivalent" to an empty file.
One different approach is to iterate over each line and do stuff for each iteration. 0 lines = 0 iterations = no extra code needed.
15,982,291
I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! The errors: ``` 1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main 1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals ``` I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. I am using the following code: ``` #include <visa.h> #include "stdafx.h" #include <stdio.h> #include <memory.h> int main(int argc, char* argv[]) { ViSession rm = VI_NULL, vi = VI_NULL; ViStatus status; ViChar buffer[256]; ViUInt32 retCnt; // Open a default session status = viOpenDefaultRM(&rm); if (status < VI_SUCCESS) goto error; // Open the GPIB device at primary address 1, GPIB board 8 status = viOpen(rm, "USB::0x0699::0x0377::C011104::INSTR", VI_NULL, VI_NULL, &vi); if (status < VI_SUCCESS) goto error; // Send an ID query. status = viWrite(vi, (ViBuf) "*idn?", 5, &retCnt); if (status < VI_SUCCESS) goto error; // Clear the buffer and read the response memset(buffer, 0, sizeof(buffer)); status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); if (status < VI_SUCCESS) goto error; // Print the response printf("id: %s\n", buffer); // Clean up viClose(vi); // Not needed, but makes things a bit more // understandable viClose(rm); // Closes resource manager and any sessions // opened with it return 0; error: // Report error and clean up viStatusDesc(vi, status, buffer); fprintf(stderr, "failure: %s\n", buffer); if (rm != VI_NULL) { viClose(rm); } return 1; } ```
2013/04/12
['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']
One different approach is to iterate over each line and do stuff for each iteration. 0 lines = 0 iterations = no extra code needed.
I think should check like this: ``` def file_empty?(file_path) !(File.file?(file_path) && !File.zero?(file_path)) end ``` so we do not need to worry about file exist or not. File.zero?('test.rb') return false if file not exist
15,982,291
I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! The errors: ``` 1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main 1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals ``` I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. I am using the following code: ``` #include <visa.h> #include "stdafx.h" #include <stdio.h> #include <memory.h> int main(int argc, char* argv[]) { ViSession rm = VI_NULL, vi = VI_NULL; ViStatus status; ViChar buffer[256]; ViUInt32 retCnt; // Open a default session status = viOpenDefaultRM(&rm); if (status < VI_SUCCESS) goto error; // Open the GPIB device at primary address 1, GPIB board 8 status = viOpen(rm, "USB::0x0699::0x0377::C011104::INSTR", VI_NULL, VI_NULL, &vi); if (status < VI_SUCCESS) goto error; // Send an ID query. status = viWrite(vi, (ViBuf) "*idn?", 5, &retCnt); if (status < VI_SUCCESS) goto error; // Clear the buffer and read the response memset(buffer, 0, sizeof(buffer)); status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); if (status < VI_SUCCESS) goto error; // Print the response printf("id: %s\n", buffer); // Clean up viClose(vi); // Not needed, but makes things a bit more // understandable viClose(rm); // Closes resource manager and any sessions // opened with it return 0; error: // Report error and clean up viStatusDesc(vi, status, buffer); fprintf(stderr, "failure: %s\n", buffer); if (rm != VI_NULL) { viClose(rm); } return 1; } ```
2013/04/12
['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']
`File.size?('test.rb')` evaluates to `nil` if the file is empty `or` it does not exist. `File.zero?('test.rb')` will return true is the file is empty, but it will return false if the file is not found. Depending on your particular needs you should be careful to use the correct method. As an example in the topic creator's question they specifically asked, "What is the best way to check in Ruby that a file is empty?" The accepted answer does this correctly and will raise a `No such file or directory` error message if the file does not exist. In some situations we may consider the lack of a file to be "equivalent" to an empty file.
As of Ruby 2.4.0, there is [File.empty?](https://ruby-doc.org/core-2.4.0/File.html#method-c-empty-3F). (Note that it always returns `false` if you pass it a directory, whether that directory is empty or not: `File.empty?('/') # => false`. So use [Dir.empty?](https://ruby-doc.org/core-2.4.0/Dir.html#method-c-empty-3F) for that instead, or [Pathname#empty?](https://ruby-doc.org/stdlib-2.4.0/libdoc/pathname/rdoc/Pathname.html#method-i-empty-3F) which works for both files and directories.)
15,982,291
I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! The errors: ``` 1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main 1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals ``` I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. I am using the following code: ``` #include <visa.h> #include "stdafx.h" #include <stdio.h> #include <memory.h> int main(int argc, char* argv[]) { ViSession rm = VI_NULL, vi = VI_NULL; ViStatus status; ViChar buffer[256]; ViUInt32 retCnt; // Open a default session status = viOpenDefaultRM(&rm); if (status < VI_SUCCESS) goto error; // Open the GPIB device at primary address 1, GPIB board 8 status = viOpen(rm, "USB::0x0699::0x0377::C011104::INSTR", VI_NULL, VI_NULL, &vi); if (status < VI_SUCCESS) goto error; // Send an ID query. status = viWrite(vi, (ViBuf) "*idn?", 5, &retCnt); if (status < VI_SUCCESS) goto error; // Clear the buffer and read the response memset(buffer, 0, sizeof(buffer)); status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); if (status < VI_SUCCESS) goto error; // Print the response printf("id: %s\n", buffer); // Clean up viClose(vi); // Not needed, but makes things a bit more // understandable viClose(rm); // Closes resource manager and any sessions // opened with it return 0; error: // Report error and clean up viStatusDesc(vi, status, buffer); fprintf(stderr, "failure: %s\n", buffer); if (rm != VI_NULL) { viClose(rm); } return 1; } ```
2013/04/12
['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']
`File.size?('test.rb')` evaluates to `nil` if the file is empty `or` it does not exist. `File.zero?('test.rb')` will return true is the file is empty, but it will return false if the file is not found. Depending on your particular needs you should be careful to use the correct method. As an example in the topic creator's question they specifically asked, "What is the best way to check in Ruby that a file is empty?" The accepted answer does this correctly and will raise a `No such file or directory` error message if the file does not exist. In some situations we may consider the lack of a file to be "equivalent" to an empty file.
I think should check like this: ``` def file_empty?(file_path) !(File.file?(file_path) && !File.zero?(file_path)) end ``` so we do not need to worry about file exist or not. File.zero?('test.rb') return false if file not exist
15,982,291
I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! The errors: ``` 1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main 1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main 1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals ``` I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. I am using the following code: ``` #include <visa.h> #include "stdafx.h" #include <stdio.h> #include <memory.h> int main(int argc, char* argv[]) { ViSession rm = VI_NULL, vi = VI_NULL; ViStatus status; ViChar buffer[256]; ViUInt32 retCnt; // Open a default session status = viOpenDefaultRM(&rm); if (status < VI_SUCCESS) goto error; // Open the GPIB device at primary address 1, GPIB board 8 status = viOpen(rm, "USB::0x0699::0x0377::C011104::INSTR", VI_NULL, VI_NULL, &vi); if (status < VI_SUCCESS) goto error; // Send an ID query. status = viWrite(vi, (ViBuf) "*idn?", 5, &retCnt); if (status < VI_SUCCESS) goto error; // Clear the buffer and read the response memset(buffer, 0, sizeof(buffer)); status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); if (status < VI_SUCCESS) goto error; // Print the response printf("id: %s\n", buffer); // Clean up viClose(vi); // Not needed, but makes things a bit more // understandable viClose(rm); // Closes resource manager and any sessions // opened with it return 0; error: // Report error and clean up viStatusDesc(vi, status, buffer); fprintf(stderr, "failure: %s\n", buffer); if (rm != VI_NULL) { viClose(rm); } return 1; } ```
2013/04/12
['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']
As of Ruby 2.4.0, there is [File.empty?](https://ruby-doc.org/core-2.4.0/File.html#method-c-empty-3F). (Note that it always returns `false` if you pass it a directory, whether that directory is empty or not: `File.empty?('/') # => false`. So use [Dir.empty?](https://ruby-doc.org/core-2.4.0/Dir.html#method-c-empty-3F) for that instead, or [Pathname#empty?](https://ruby-doc.org/stdlib-2.4.0/libdoc/pathname/rdoc/Pathname.html#method-i-empty-3F) which works for both files and directories.)
I think should check like this: ``` def file_empty?(file_path) !(File.file?(file_path) && !File.zero?(file_path)) end ``` so we do not need to worry about file exist or not. File.zero?('test.rb') return false if file not exist
54,004,943
I am using <https://docs.expo.io/versions/latest/sdk/facebook-ads> for adding Facebook ads to my app. I am following the documentation properly, but Facebook ads are not visible on my app home screen. BottomBannerAd.js ``` import React from 'react'; import { FacebookAds } from 'expo'; const { AdIconView, AdMediaView } = FacebookAds; class AdComponent extends React.Component { render() { return ( <View> <AdMediaView /> <AdTriggerView> <Text>{this.props.nativeAd.bodyText}</Text> </AdTriggerView> </View> ); } } export default FacebookAds.withNativeAd(AdComponent); ``` HomeScreen.js ``` import React from 'react'; import { Image, TextInput, FlatList, StyleSheet, Text, View, TouchableOpacity, ActivityIndicator, Platform } from 'react-native'; import { NavigationEvents } from 'react-navigation'; import { FacebookAds } from 'expo'; import AdComponent from '../components/BottomBannerAd'; const adsManager = new FacebookAds.NativeAdsManager('xxxxxxxxxxx', 10); import { AdMobBanner, AdMobInterstitial, AdMobRewarded } from "expo"; export default class HomeScreen extends React.Component { render(){ return ( <View style={styles.container}> ... <View style={styles.tabBarInfoContainer}> <AdComponent adsManager={adsManager} /> </View> </View> ) } } ``` I have a view component that holds the ad component. That view component works well when I add Google ads, but not working for Facebook ads.
2019/01/02
['https://Stackoverflow.com/questions/54004943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10825278/']
One solution is to enter an actual device ID for testing, I wasn't able to get it working otherwise. [![setting up ID](https://i.stack.imgur.com/ojpl0.png)](https://i.stack.imgur.com/ojpl0.png) Your code above should generate something like this (attachment below), but only on the active device. [![enter image description here](https://i.stack.imgur.com/h1jn3.png)](https://i.stack.imgur.com/h1jn3.png) The normal way of testing should be by adding a `FacebookAds.AdSettings.addTestDevice(FacebookAds.AdSettings.currentDeviceHash);` to your code, but it didn't work (for me at least). To get an IDFA id on an iPhone, download DeviceId (by AppsFlyer) from the AppStore and also disable Limit Ad Tracking in your Privacy > Advertising settings. Hope it helps.
Check this out - [react-native with expo problem with facebook ads](https://stackoverflow.com/questions/53836535/react-native-with-expo-problem-with-facebook-ads) I'm having the same issue. It appears FB ads are broken in the current expo builds.
346,122
Let $M$, $N$ be $n$-dimensional real manifolds. Does $M\times N$ admits a complex structure? If not, are there known condidtions ensuring that $M\times N$ admits a complex structure?
2019/11/15
['https://mathoverflow.net/questions/346122', 'https://mathoverflow.net', 'https://mathoverflow.net/users/147073/']
I assume you are asking if $M \times N$ admits a complex structure. I believe that there is no result known on this question, although we might have something to say about the existence of an almost complex structure for which both factors are totally real. Once again we can quote [Gromov](https://www.ihes.fr/~gromov/wp-content/uploads/2018/08/SpacesandQuestions.pdf): Page 30. "How much do we gain in global understanding of a compact $(V, J)$ by assuming that the structure $J$ is integrable (i.e. complex)? It seems nothing at all: there is no single result concerning all compact complex manifolds".
[EDIT: I started to write this answer, and then realized it doesn't really answers the question - I leave it here anyway, just in case] Let $X=M\times N$, and let $E=\pi\_M^\*TM$ and $F=\pi\_N^\*TN$. Note that $TX=E\oplus F$. As suggested in Ben McKay's answer, you could first look for the existence of an almost complex structure $J\in End(TX)$, $J^2=-Id$, for which both projections $\pi\_M$ and $\pi\_N$ have totally real fibers. This may exist or not. It does for instance under the assumption that there exists an isomorphism of vector bundles $\phi:E\to F$. In that case, define $$ J:=\left(\matrix{0 &\phi^{-1} \\ -\phi & 0}\right) $$ In this situation the eigenbundle $T^{1,0}X$ corresponding to $+i$ is isomorphic to $E^{\mathbb{C}}$ in the following way: $$ E^{\mathbb{C}}\to T^{1,0}X\quad;\quad v\mapsto v+i\phi(v) $$ You may want to look for conditions on $\phi$ for $J$ to be integrable.
346,122
Let $M$, $N$ be $n$-dimensional real manifolds. Does $M\times N$ admits a complex structure? If not, are there known condidtions ensuring that $M\times N$ admits a complex structure?
2019/11/15
['https://mathoverflow.net/questions/346122', 'https://mathoverflow.net', 'https://mathoverflow.net/users/147073/']
I'm going to take $M$ and $N$ to be connected. Note that they cannot have boundary. Furthermore, as complex manifolds are orientable, $M$ and $N$ must also be orientable. If $n = 1$, then $M, N \in \{\mathbb{R}, S^1\}$. Note that $\mathbb{R}\times\mathbb{R}$ has a complex structure, in fact, precisely two: $\mathbb{D}$ and $\mathbb{C}$. In addition, $\mathbb{R}\times S^1 = S^1\times \mathbb{R}$ and $S^1\times S^1$ have uncountably many complex structures (annuli and tori respectively). If $n = 2$, then $M$ and $N$ are orientable surfaces. These always admit complex structures, and therefore, so do their products. Already for $n = 3$, we do not have a complete answer. In this case, the manifold $M\times N$ always admits an almost complex structure, but it is not clear when it admits an integrable one (i.e. a complex structure). This is a major open problem in complex geometry: > > If a manifold admits an almost complex structure, does it admit a complex structure? > > > The answer is known to be false in real dimension four, but completely open in higher dimensions. For $n = 4$, the manifold $M\times N$ may not even admit an almost complex structure. For example, $M = N = S^4$. Theorem 1 of [this paper](https://www.sciencedirect.com/science/article/pii/0040938370900315) of Heaps completely characterises which closed eight-manifolds admit an almost complex structure. In principle, this could be used to determine what $M$ and $N$ could be, at least in the compact case.
I assume you are asking if $M \times N$ admits a complex structure. I believe that there is no result known on this question, although we might have something to say about the existence of an almost complex structure for which both factors are totally real. Once again we can quote [Gromov](https://www.ihes.fr/~gromov/wp-content/uploads/2018/08/SpacesandQuestions.pdf): Page 30. "How much do we gain in global understanding of a compact $(V, J)$ by assuming that the structure $J$ is integrable (i.e. complex)? It seems nothing at all: there is no single result concerning all compact complex manifolds".
346,122
Let $M$, $N$ be $n$-dimensional real manifolds. Does $M\times N$ admits a complex structure? If not, are there known condidtions ensuring that $M\times N$ admits a complex structure?
2019/11/15
['https://mathoverflow.net/questions/346122', 'https://mathoverflow.net', 'https://mathoverflow.net/users/147073/']
I'm going to take $M$ and $N$ to be connected. Note that they cannot have boundary. Furthermore, as complex manifolds are orientable, $M$ and $N$ must also be orientable. If $n = 1$, then $M, N \in \{\mathbb{R}, S^1\}$. Note that $\mathbb{R}\times\mathbb{R}$ has a complex structure, in fact, precisely two: $\mathbb{D}$ and $\mathbb{C}$. In addition, $\mathbb{R}\times S^1 = S^1\times \mathbb{R}$ and $S^1\times S^1$ have uncountably many complex structures (annuli and tori respectively). If $n = 2$, then $M$ and $N$ are orientable surfaces. These always admit complex structures, and therefore, so do their products. Already for $n = 3$, we do not have a complete answer. In this case, the manifold $M\times N$ always admits an almost complex structure, but it is not clear when it admits an integrable one (i.e. a complex structure). This is a major open problem in complex geometry: > > If a manifold admits an almost complex structure, does it admit a complex structure? > > > The answer is known to be false in real dimension four, but completely open in higher dimensions. For $n = 4$, the manifold $M\times N$ may not even admit an almost complex structure. For example, $M = N = S^4$. Theorem 1 of [this paper](https://www.sciencedirect.com/science/article/pii/0040938370900315) of Heaps completely characterises which closed eight-manifolds admit an almost complex structure. In principle, this could be used to determine what $M$ and $N$ could be, at least in the compact case.
[EDIT: I started to write this answer, and then realized it doesn't really answers the question - I leave it here anyway, just in case] Let $X=M\times N$, and let $E=\pi\_M^\*TM$ and $F=\pi\_N^\*TN$. Note that $TX=E\oplus F$. As suggested in Ben McKay's answer, you could first look for the existence of an almost complex structure $J\in End(TX)$, $J^2=-Id$, for which both projections $\pi\_M$ and $\pi\_N$ have totally real fibers. This may exist or not. It does for instance under the assumption that there exists an isomorphism of vector bundles $\phi:E\to F$. In that case, define $$ J:=\left(\matrix{0 &\phi^{-1} \\ -\phi & 0}\right) $$ In this situation the eigenbundle $T^{1,0}X$ corresponding to $+i$ is isomorphic to $E^{\mathbb{C}}$ in the following way: $$ E^{\mathbb{C}}\to T^{1,0}X\quad;\quad v\mapsto v+i\phi(v) $$ You may want to look for conditions on $\phi$ for $J$ to be integrable.
35,950,535
I have a function I've written to handle calculations of percent reductions with significant digits, and I'm having a problem with keeping trailing zeroes. The function: ``` Function RegexReduction(IValue As Double, EValue As Double) As String Dim TempPercent As Double Dim TempString As String Dim NumFormat As String Dim DecPlaces As Long Dim regex As Object Dim rxMatches As Object TempPercent = (1 - EValue / IValue) NumFormat = "0" Set regex = CreateObject("VBScript.RegExp") With regex .Pattern = "([^1-8])*[0-8]{1}[0-9]?" .Global = False End With Set rxMatches = regex.Execute(CStr(TempPercent)) If rxMatches.Count <> 0 Then TempString = rxMatches.Item(0) DecPlaces = Len(Split(TempString, ".")(1)) - 2 If DecPlaces > 0 Then NumFormat = NumFormat & "." & String(DecPlaces, "0") End If RegexReduction = Format(TempPercent, NumFormat & "%") End Function ``` This trims percentages to two digits after any leading zeroes or nines: ``` 99.999954165% -> 99.99954% 34.564968% -> 35% 0.000516% -> 0.00052% ``` The one problem I've found isn't related to the regex, but to Excel's rounding: ``` 99.50% -> 99.5% ``` Is there a solution that will save trailing zeroes that could be implemented here?
2016/03/11
['https://Stackoverflow.com/questions/35950535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4747836/']
You had several bugs. The first root loop was wrong, so with `-np 2` you would send to rank 2. The second root loop was wrong -- it should match the corrected first loop. A third bug, that only shows up with `-np` greater than 2 is that the root `MPI_Recv` is wrong. The program will hang. I've corrected the program and annotated the source. I moved the essential code to a function. Each time I made a fix I added a new function with the fix so you can see the history of the debug process. Since you also wanted help with debugging, I've added debugging code that I used to find the problems. I've used this sort of code many times before. I've also added the output trace files at the bottom. **Update:** There is a fourth bug. If the `-np` value minus 1 does *not* divide `SIZE` evenly, some of the last elements will not be summed (e.g. `-np 7`). I've added more annotation and added an additional function that fixes this. Anyway, here's the code [please pardon the gratuitous style cleanup]: ``` //array parallel #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <unistd.h> #include <time.h> #include <mpi.h> typedef long long s64; double tvzero; // initial start time int opt_debug; // 1=trace int opt_run; // version to run int size; // MPI size int rank; // MPI rank of current process int proc; // number of child processes int chunksize; // size of chunk MPI_Status status; #define TVSEC 1000000000 // tvget -- get time in nanoseconds s64 tvget(void) { struct timespec ts; s64 nsec; clock_gettime(CLOCK_REALTIME,&ts); nsec = ts.tv_sec; nsec *= TVSEC; nsec += ts.tv_nsec; return nsec; } // tvgetf -- get time in fractional seconds double tvgetf(void) { struct timespec ts; double sec; clock_gettime(CLOCK_REALTIME,&ts); sec = ts.tv_nsec; sec /= TVSEC; sec += ts.tv_sec; return sec; } void _dbgprt(int lno,const char *fmt,...) __attribute__((__format__(__printf__,2,3))); #define dbgprt(_lvl,_fmt...) \ do { \ if (opt_debug >= _lvl) \ _dbgprt(__LINE__,_fmt); \ } while (0) void _dbgprt(int lno,const char *fmt,...) { va_list ap; double tvnow; char *bp; char bf[1000]; bp = bf; tvnow = tvgetf(); tvnow -= tvzero; bp += sprintf(bp,"[%.9f/R:%d/L:%d] ",tvnow,rank,lno); va_start(ap,fmt); bp += vsprintf(bp,fmt,ap); va_end(ap); fputs(bf,stdout); } // _dbgptr -- interpret pointer char * _dbgptr(const void *ptr,const char *sym,MPI_Datatype typ) { char *bp; static char bf[100]; bp = bf; *bp = 0; do { bp += sprintf(bp,"%s=",sym); if (typ == MPI_INT) { bp += sprintf(bp,"%d",*(int *) ptr); break; } bp += sprintf(bp,"%p",ptr); } while (0); return bf; } #define xMPI_Send(_ptr,_cnt,_typ,_torank,_tag,_comm) \ do { \ dbgprt(2,"MPI_Send ptr=[%s] cnt=%d typ=%s torank=%d tag=%d comm=%s\n", \ _dbgptr(_ptr,#_ptr,_typ),_cnt,#_typ,_torank,_tag,#_comm); \ MPI_Send(_ptr,_cnt,_typ,_torank,_tag,_comm); \ } while (0) #define xMPI_Recv(_ptr,_cnt,_typ,_fmrank,_tag,_comm,_status) \ do { \ dbgprt(2,"MPI_Recv ptr=%p cnt=%d typ=%s fmrank=%d tag=%d comm=%s\n", \ _ptr,_cnt,#_typ,_fmrank,_tag,#_comm); \ MPI_Recv(_ptr,_cnt,_typ,_fmrank,_tag,_comm,_status); \ } while (0) #define xMPI_Finalize() \ do { \ dbgprt(1,"MPI_Finalize\n"); \ MPI_Finalize(); \ } while (0) #define SIZE 50000 int data1[SIZE]; int data2[SIZE]; // init -- initialize array and return sum int init(void) { int i; int Tsum; for (i = 0; i < SIZE; ++i) data1[i] = i + 1; Tsum = 0; for (i = 0; i < SIZE; ++i) Tsum += data1[i]; printf("Total Sum: %d \n",Tsum); return Tsum; } // run_orig -- original code with all bugs noted void run_orig(void) { int i; int dest; int source; int Tsum; int Rsum; int sum; int index; // BUG(1a): this should be one less (e.g. for -np 2, root=0, child=1) proc = size; // BUG(4): if SIZE is not a multiple of proc, the last few elements will // _not_ be processed -- the last child must get a larger chunk size, so in // addition to sending the index to each child, we must send it a custom // chunk size chunksize = SIZE / proc; if (rank == 0) { Tsum = init(); // send split of array to children // BUG(1b): this loop goes one beyond the last child and caused the send // to blow up index = 0; for (dest = 1; dest <= proc; ++dest) { xMPI_Send(&index,1,MPI_INT,dest,0,MPI_COMM_WORLD); xMPI_Send(&data1[index],chunksize,MPI_INT,dest,0,MPI_COMM_WORLD); index = index + chunksize; } // collect sum of children // BUG(2): this for loop is wrong -- it should match the one above Rsum = 0; for (i = 0; i < proc; ++i) { // BUG(3): source should be "i" source = 1; xMPI_Recv(&sum,1,MPI_INT,source,0,MPI_COMM_WORLD,&status); Rsum = Rsum + sum; printf("- - - - - - - - - - - - - -\n"); printf("Received from process %d, Sum: %d \n",source,sum); } printf("Total Sum received: %d -- %s\n", Rsum,(Rsum == Tsum) ? "PASS" : "FAIL"); } else { xMPI_Recv(&index,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); xMPI_Recv(&data2[index],chunksize,MPI_INT,0,0,MPI_COMM_WORLD,&status); sum = 0; for (i = index; i < index + chunksize; ++i) sum += data2[i]; xMPI_Send(&sum,1,MPI_INT,0,0,MPI_COMM_WORLD); } } // run_edit1 -- no changes to original void run_edit1(void) { int i; int cldno; int Tsum; int Rsum; int sum; int index; int source; proc = size; chunksize = SIZE / proc; if (rank == 0) { Tsum = init(); // send split of array to children index = 0; for (cldno = 1; cldno <= proc; ++cldno) { xMPI_Send(&index,1,MPI_INT,cldno,0,MPI_COMM_WORLD); xMPI_Send(&data1[index],chunksize,MPI_INT,cldno,0,MPI_COMM_WORLD); index = index + chunksize; } // collect sum of children Rsum = 0; for (cldno = 0; cldno < proc; ++cldno) { source = 1; xMPI_Recv(&sum,1,MPI_INT,source,0,MPI_COMM_WORLD,&status); Rsum += sum; printf("- - - - - - - - - - - - - -\n"); printf("Received from process %d, Sum: %d \n",cldno,sum); } printf("Total Sum received: %d -- %s\n", Rsum,(Rsum == Tsum) ? "PASS" : "FAIL"); } else { xMPI_Recv(&index,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); xMPI_Recv(&data2[index],chunksize,MPI_INT,0,0,MPI_COMM_WORLD,&status); sum = 0; for (i = index; i < index + chunksize; ++i) sum += data2[i]; xMPI_Send(&sum,1,MPI_INT,0,0,MPI_COMM_WORLD); } } // run_edit2 -- fixed child count void run_edit2(void) { int i; int cldno; int Tsum; int Rsum; int sum; int index; int source; // BUGFIX #1 -- child count must be one less than size proc = size - 1; chunksize = SIZE / proc; if (rank == 0) { Tsum = init(); // send split of array to children index = 0; for (cldno = 1; cldno <= proc; ++cldno) { xMPI_Send(&index,1,MPI_INT,cldno,0,MPI_COMM_WORLD); xMPI_Send(&data1[index],chunksize,MPI_INT,cldno,0,MPI_COMM_WORLD); index = index + chunksize; } // collect sum of children Rsum = 0; for (cldno = 0; cldno < proc; ++cldno) { source = 1; xMPI_Recv(&sum,1,MPI_INT,source,0,MPI_COMM_WORLD,&status); Rsum += sum; printf("- - - - - - - - - - - - - -\n"); printf("Received from process %d, Sum: %d \n",cldno,sum); } printf("Total Sum received: %d -- %s\n", Rsum,(Rsum == Tsum) ? "PASS" : "FAIL"); } else { xMPI_Recv(&index,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); xMPI_Recv(&data2[index],chunksize,MPI_INT,0,0,MPI_COMM_WORLD,&status); sum = 0; for (i = index; i < index + chunksize; ++i) sum += data2[i]; xMPI_Send(&sum,1,MPI_INT,0,0,MPI_COMM_WORLD); } } // run_edit3 -- fixed second root loop and MPI_Recv void run_edit3(void) { int i; int cldno; int Tsum; int Rsum; int sum; int index; // BUGFIX #1 -- child count must be one less than size proc = size - 1; chunksize = SIZE / proc; if (rank == 0) { Tsum = init(); // send split of array to children index = 0; for (cldno = 1; cldno <= proc; ++cldno) { xMPI_Send(&index,1,MPI_INT,cldno,0,MPI_COMM_WORLD); xMPI_Send(&data1[index],chunksize,MPI_INT,cldno,0,MPI_COMM_WORLD); index = index + chunksize; } // collect sum of children // BUGFIX #2 -- loop was wrong and the source arg must be the child rank Rsum = 0; for (cldno = 1; cldno <= proc; ++cldno) { xMPI_Recv(&sum,1,MPI_INT,cldno,0,MPI_COMM_WORLD,&status); Rsum += sum; printf("- - - - - - - - - - - - - -\n"); printf("Received from process %d, Sum: %d \n",cldno,sum); } printf("Total Sum received: %d -- %s\n", Rsum,(Rsum == Tsum) ? "PASS" : "FAIL"); } else { xMPI_Recv(&index,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); xMPI_Recv(&data2[index],chunksize,MPI_INT,0,0,MPI_COMM_WORLD,&status); sum = 0; for (i = index; i < index + chunksize; ++i) sum += data2[i]; xMPI_Send(&sum,1,MPI_INT,0,0,MPI_COMM_WORLD); } } // run_edit4 -- fixed chunk size allocation void run_edit4(void) { int i; int cldno; int Tsum; int Rsum; int sum; int sendsize; int totsize; int index; // BUGFIX #1 -- child count must be one less than size proc = size - 1; totsize = SIZE; chunksize = totsize / proc; if (rank == 0) { Tsum = init(); // send split of array to children index = 0; for (cldno = 1; cldno <= proc; ++cldno, totsize -= sendsize) { // BUGFIX #3a -- not every child node gets the same amount if (cldno < proc) sendsize = chunksize; else sendsize = totsize; xMPI_Send(&index,1,MPI_INT,cldno,0,MPI_COMM_WORLD); xMPI_Send(&sendsize,1,MPI_INT,cldno,0,MPI_COMM_WORLD); xMPI_Send(&data1[index],sendsize,MPI_INT,cldno,0,MPI_COMM_WORLD); index = index + sendsize; } // collect sum of children // BUGFIX #2 -- loop was wrong and the source arg must be the child rank Rsum = 0; for (cldno = 1; cldno <= proc; ++cldno) { xMPI_Recv(&sum,1,MPI_INT,cldno,0,MPI_COMM_WORLD,&status); Rsum += sum; printf("- - - - - - - - - - - - - -\n"); printf("Received from process %d, Sum: %d \n",cldno,sum); } printf("Total Sum received: %d -- %s\n", Rsum,(Rsum == Tsum) ? "PASS" : "FAIL"); } else { // BUGFIX #3b -- not every child node gets the same amount xMPI_Recv(&index,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); xMPI_Recv(&chunksize,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); xMPI_Recv(&data2[index],chunksize,MPI_INT,0,0,MPI_COMM_WORLD,&status); sum = 0; for (i = index; i < index + chunksize; ++i) sum += data2[i]; xMPI_Send(&sum,1,MPI_INT,0,0,MPI_COMM_WORLD); } } int main(int argc,char **argv) { char *cp; // NOTE: this will vary a bit with rank // to do the job properly we'd need the root to bcast this -- see below tvzero = tvgetf(); MPI_Init(&argc,&argv); MPI_Comm_rank(MPI_COMM_WORLD,&rank); MPI_Comm_size(MPI_COMM_WORLD,&size); --argc; ++argv; for (; argc > 0; --argc, ++argv) { cp = *argv; if (*cp != '-') break; switch (cp[1]) { case 'R': cp += 2; opt_run = (*cp != 0) ? atoi(cp) : 1; break; case 'T': cp += 2; opt_debug = (*cp != 0) ? atoi(cp) : 1; break; } } // root send to all children if (opt_debug) MPI_Bcast(&tvzero,1,MPI_DOUBLE,0,MPI_COMM_WORLD); // show our pid so we can map it to rank [which is more meaningful] dbgprt(1,"PID pid=%d\n",getpid()); switch (opt_run) { case 1: run_edit1(); break; case 2: run_edit2(); break; case 3: run_edit3(); break; case 4: run_edit4(); break; default: break; } xMPI_Finalize(); return 0; } ``` --- Here are the logs [combined into one to save space]: ``` # test #1 edit #1 with -np=2 -T9 [manderly:6620] *** An error occurred in MPI_Send [manderly:6620] *** reported by process [3255828481,0] [manderly:6620] *** on communicator MPI_COMM_WORLD [manderly:6620] *** MPI_ERR_RANK: invalid rank [manderly:6620] *** MPI_ERRORS_ARE_FATAL (processes in this communicator will now abort, [manderly:6620] *** and potentially your MPI job) [0.014549255/R:0/L:480] PID pid=6620 [0.014554262/R:1/L:480] PID pid=6621 [0.014572620/R:1/L:259] MPI_Recv ptr=0x7ffc98d18a6c cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD Total Sum: 1250025000 [0.014715672/R:0/L:239] MPI_Send ptr=[&index=0] cnt=1 typ=MPI_INT torank=1 tag=0 comm=MPI_COMM_WORLD [0.014730692/R:0/L:240] MPI_Send ptr=[&data1[index]=1] cnt=25000 typ=MPI_INT torank=1 tag=0 comm=MPI_COMM_WORLD [0.014730930/R:1/L:260] MPI_Recv ptr=0x603960 cnt=25000 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.014817476/R:0/L:239] MPI_Send ptr=[&index=25000] cnt=1 typ=MPI_INT torank=2 tag=0 comm=MPI_COMM_WORLD [0.014842749/R:1/L:266] MPI_Send ptr=[&sum=312512500] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD [0.014861822/R:1/L:499] MPI_Finalize # test #2 edit #2 with -np=2 -T0 Total Sum: 1250025000 - - - - - - - - - - - - - - Received from process 0, Sum: 1250025000 Total Sum received: 1250025000 -- PASS # test #3 edit #2 with -np=5 -T9 [0.028285980/R:0/L:480] PID pid=6632 [0.028294086/R:1/L:480] PID pid=6633 [0.028315544/R:1/L:313] MPI_Recv ptr=0x7ffe22a554ec cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.028294325/R:4/L:480] PID pid=6637 [0.028332472/R:4/L:313] MPI_Recv ptr=0x7ffd5ed6a77c cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.028387308/R:2/L:480] PID pid=6634 [0.028410435/R:2/L:313] MPI_Recv ptr=0x7fff6f23896c cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.028449297/R:3/L:480] PID pid=6635 [0.028471947/R:3/L:313] MPI_Recv ptr=0x7ffd23af2ecc cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD Total Sum: 1250025000 [0.028527975/R:0/L:293] MPI_Send ptr=[&index=0] cnt=1 typ=MPI_INT torank=1 tag=0 comm=MPI_COMM_WORLD [0.028543711/R:0/L:294] MPI_Send ptr=[&data1[index]=1] cnt=12500 typ=MPI_INT torank=1 tag=0 comm=MPI_COMM_WORLD [0.028544903/R:1/L:314] MPI_Recv ptr=0x603960 cnt=12500 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.028627157/R:0/L:293] MPI_Send ptr=[&index=12500] cnt=1 typ=MPI_INT torank=2 tag=0 comm=MPI_COMM_WORLD [0.028636694/R:0/L:294] MPI_Send ptr=[&data1[index]=12501] cnt=12500 typ=MPI_INT torank=2 tag=0 comm=MPI_COMM_WORLD [0.028637648/R:2/L:314] MPI_Recv ptr=0x60fcb0 cnt=12500 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.028641224/R:1/L:320] MPI_Send ptr=[&sum=78131250] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD [0.028657198/R:1/L:499] MPI_Finalize [0.028701305/R:0/L:293] MPI_Send ptr=[&index=25000] cnt=1 typ=MPI_INT torank=3 tag=0 comm=MPI_COMM_WORLD [0.028716326/R:0/L:294] MPI_Send ptr=[&data1[index]=25001] cnt=12500 typ=MPI_INT torank=3 tag=0 comm=MPI_COMM_WORLD [0.028719425/R:2/L:320] MPI_Send ptr=[&sum=234381250] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD [0.028721094/R:3/L:314] MPI_Recv ptr=0x61c000 cnt=12500 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.028738737/R:2/L:499] MPI_Finalize [0.028776169/R:0/L:293] MPI_Send ptr=[&index=37500] cnt=1 typ=MPI_INT torank=4 tag=0 comm=MPI_COMM_WORLD [0.028784752/R:0/L:294] MPI_Send ptr=[&data1[index]=37501] cnt=12500 typ=MPI_INT torank=4 tag=0 comm=MPI_COMM_WORLD [0.028797865/R:3/L:320] MPI_Send ptr=[&sum=390631250] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD [0.028819084/R:3/L:499] MPI_Finalize [0.028877974/R:4/L:314] MPI_Recv ptr=0x628350 cnt=12500 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.028944492/R:0/L:302] MPI_Recv ptr=0x7ffe7db6e4b8 cnt=1 typ=MPI_INT fmrank=1 tag=0 comm=MPI_COMM_WORLD - - - - - - - - - - - - - - Received from process 0, Sum: 78131250 [0.028969765/R:0/L:302] MPI_Recv ptr=0x7ffe7db6e4b8 cnt=1 typ=MPI_INT fmrank=1 tag=0 comm=MPI_COMM_WORLD [0.028957367/R:4/L:320] MPI_Send ptr=[&sum=546881250] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD [0.028982162/R:4/L:499] MPI_Finalize TIMEOUT!!! # test #4 edit #3 with -np=5 -T0 Total Sum: 1250025000 - - - - - - - - - - - - - - Received from process 1, Sum: 78131250 - - - - - - - - - - - - - - Received from process 2, Sum: 234381250 - - - - - - - - - - - - - - Received from process 3, Sum: 390631250 - - - - - - - - - - - - - - Received from process 4, Sum: 546881250 Total Sum received: 1250025000 -- PASS # test #5 edit #3 with -np=7 -T9 [0.043676138/R:0/L:480] PID pid=6662 [0.043689251/R:1/L:480] PID pid=6663 [0.043709040/R:1/L:366] MPI_Recv ptr=0x7ffc571a085c cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.043683767/R:4/L:480] PID pid=6666 [0.043709040/R:4/L:366] MPI_Recv ptr=0x7ffd9e8ea57c cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.043860435/R:3/L:480] PID pid=6665 [0.043884993/R:3/L:366] MPI_Recv ptr=0x7ffd1f26c0fc cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.043950558/R:5/L:480] PID pid=6669 [0.043974400/R:5/L:366] MPI_Recv ptr=0x7ffc171ddf2c cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.043961048/R:2/L:480] PID pid=6664 [0.043980122/R:2/L:366] MPI_Recv ptr=0x7ffde0a06dec cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.043968439/R:6/L:480] PID pid=6670 [0.043987513/R:6/L:366] MPI_Recv ptr=0x7ffe4afba88c cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD Total Sum: 1250025000 [0.044004679/R:0/L:346] MPI_Send ptr=[&index=0] cnt=1 typ=MPI_INT torank=1 tag=0 comm=MPI_COMM_WORLD [0.044021130/R:0/L:347] MPI_Send ptr=[&data1[index]=1] cnt=8333 typ=MPI_INT torank=1 tag=0 comm=MPI_COMM_WORLD [0.044066429/R:1/L:367] MPI_Recv ptr=0x603960 cnt=8333 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.044160843/R:0/L:346] MPI_Send ptr=[&index=8333] cnt=1 typ=MPI_INT torank=2 tag=0 comm=MPI_COMM_WORLD [0.044172764/R:0/L:347] MPI_Send ptr=[&data1[index]=8334] cnt=8333 typ=MPI_INT torank=2 tag=0 comm=MPI_COMM_WORLD [0.044173002/R:2/L:367] MPI_Recv ptr=0x60bb94 cnt=8333 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.044213533/R:1/L:373] MPI_Send ptr=[&sum=34723611] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD [0.044217110/R:0/L:346] MPI_Send ptr=[&index=16666] cnt=1 typ=MPI_INT torank=3 tag=0 comm=MPI_COMM_WORLD [0.044228792/R:0/L:347] MPI_Send ptr=[&data1[index]=16667] cnt=8333 typ=MPI_INT torank=3 tag=0 comm=MPI_COMM_WORLD [0.044233561/R:2/L:373] MPI_Send ptr=[&sum=104162500] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD [0.044246435/R:2/L:499] MPI_Finalize [0.044233799/R:3/L:367] MPI_Recv ptr=0x613dc8 cnt=8333 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.044275522/R:0/L:346] MPI_Send ptr=[&index=24999] cnt=1 typ=MPI_INT torank=4 tag=0 comm=MPI_COMM_WORLD [0.044286489/R:4/L:367] MPI_Recv ptr=0x61bffc cnt=8333 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.044291496/R:3/L:373] MPI_Send ptr=[&sum=173601389] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD [0.044314146/R:3/L:499] MPI_Finalize [0.044286251/R:0/L:347] MPI_Send ptr=[&data1[index]=25000] cnt=8333 typ=MPI_INT torank=4 tag=0 comm=MPI_COMM_WORLD [0.044338703/R:0/L:346] MPI_Send ptr=[&index=33332] cnt=1 typ=MPI_INT torank=5 tag=0 comm=MPI_COMM_WORLD [0.044353485/R:0/L:347] MPI_Send ptr=[&data1[index]=33333] cnt=8333 typ=MPI_INT torank=5 tag=0 comm=MPI_COMM_WORLD [0.044402599/R:0/L:346] MPI_Send ptr=[&index=41665] cnt=1 typ=MPI_INT torank=6 tag=0 comm=MPI_COMM_WORLD [0.044354916/R:4/L:373] MPI_Send ptr=[&sum=243040278] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD [0.044372797/R:4/L:499] MPI_Finalize [0.044359684/R:5/L:367] MPI_Recv ptr=0x624230 cnt=8333 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.044411659/R:5/L:373] MPI_Send ptr=[&sum=312479167] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD [0.044427156/R:5/L:499] MPI_Finalize [0.044423819/R:6/L:367] MPI_Recv ptr=0x62c464 cnt=8333 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD [0.044469357/R:6/L:373] MPI_Send ptr=[&sum=381918056] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD [0.044484377/R:6/L:499] MPI_Finalize [0.044419050/R:0/L:347] MPI_Send ptr=[&data1[index]=41666] cnt=8333 typ=MPI_INT torank=6 tag=0 comm=MPI_COMM_WORLD [0.044459820/R:0/L:355] MPI_Recv ptr=0x7fffd9e14708 cnt=1 typ=MPI_INT fmrank=1 tag=0 comm=MPI_COMM_WORLD - - - - - - - - - - - - - - Received from process 1, Sum: 34723611 [0.044672012/R:0/L:355] MPI_Recv ptr=0x7fffd9e14708 cnt=1 typ=MPI_INT fmrank=2 tag=0 comm=MPI_COMM_WORLD - - - - - - - - - - - - - - Received from process 2, Sum: 104162500 [0.044713497/R:0/L:355] MPI_Recv ptr=0x7fffd9e14708 cnt=1 typ=MPI_INT fmrank=3 tag=0 comm=MPI_COMM_WORLD - - - - - - - - - - - - - - Received from process 3, Sum: 173601389 [0.044723034/R:0/L:355] MPI_Recv ptr=0x7fffd9e14708 cnt=1 typ=MPI_INT fmrank=4 tag=0 comm=MPI_COMM_WORLD - - - - - - - - - - - - - - Received from process 4, Sum: 243040278 [0.044659376/R:1/L:499] MPI_Finalize [0.044735193/R:0/L:355] MPI_Recv ptr=0x7fffd9e14708 cnt=1 typ=MPI_INT fmrank=5 tag=0 comm=MPI_COMM_WORLD - - - - - - - - - - - - - - Received from process 5, Sum: 312479167 [0.044743538/R:0/L:355] MPI_Recv ptr=0x7fffd9e14708 cnt=1 typ=MPI_INT fmrank=6 tag=0 comm=MPI_COMM_WORLD - - - - - - - - - - - - - - Received from process 6, Sum: 381918056 Total Sum received: 1249925001 -- FAIL [0.044760466/R:0/L:499] MPI_Finalize # test #6 edit #4 with -np=7 -T0 Total Sum: 1250025000 - - - - - - - - - - - - - - Received from process 1, Sum: 34723611 - - - - - - - - - - - - - - Received from process 2, Sum: 104162500 - - - - - - - - - - - - - - Received from process 3, Sum: 173601389 - - - - - - - - - - - - - - Received from process 4, Sum: 243040278 - - - - - - - - - - - - - - Received from process 5, Sum: 312479167 - - - - - - - - - - - - - - Received from process 6, Sum: 382018055 Total Sum received: 1250025000 -- PASS ```
The line ``` for (dest = 1; dest <= proc; ++dest) ``` should be ``` for (dest = 1; dest < proc; ++dest) ``` You are trying to send to a rank with a label of 2, but with only 2 ranks, you only have ranks 0 and 1 Also, when you are receiving on rank 0, you have: ``` for (int i = 0; i < proc; ++i) ``` Which implies you plan to receive from yourself, but you do not have a corresponding send.
7,718,418
Let's have simplified class: ``` class A { bool val_; public: A() : val_(true) {} bool isNew() const { return val_; } void setDirty() { val_ = false; } }; ``` and the vector of objects of such class: ``` vector<A> coll; coll.push_back(A()); coll.push_back(A()); coll.push_back(A()); coll.push_back(A()); coll[1].setDirty(); coll[3].setDirty(); ``` I need some elegant solution to rearrange(sort) elements in the vector, so that not modified objects will be grouped at the beginning of the sequence.
2011/10/10
['https://Stackoverflow.com/questions/7718418', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/801620/']
You can use [Partition](http://www.cplusplus.com/reference/algorithm/partition/) algorithm from standard library for that: ``` bool MyPredicate(A& a) { return a.isNew();} ... // bound is iterator pointing to the first element for which predicate returns false vector<A>::iterator bound = partition(coll.begin(), coll.end(), MyPredicate); ``` Or, as Christian Rau suggested solution without separate function: ``` std::partition(coll.begin(), coll.end(), std::mem_fun_ref(&A::isNew)) ```
How about `sort`: ``` #include <algorithm> std::sort(coll.begin(), coll.end(), [](const A & a, const A & b) -> bool { return a.isNew() < b.isNew(); } ); ``` You'll have to rewrite the class to declare `isNew()` as `const`. For older compilers, use a function instead of the lambda: ``` bool isNewCompare(const A & a, const A & b) { return a.isNew() < b.isNew(); } std::sort(coll.begin(), coll.end(), isNewCompare); ``` *Edit:* @Vladimir has the better answer, `std::partition()` is the more appropriate algorithm for this problem.
7,718,418
Let's have simplified class: ``` class A { bool val_; public: A() : val_(true) {} bool isNew() const { return val_; } void setDirty() { val_ = false; } }; ``` and the vector of objects of such class: ``` vector<A> coll; coll.push_back(A()); coll.push_back(A()); coll.push_back(A()); coll.push_back(A()); coll[1].setDirty(); coll[3].setDirty(); ``` I need some elegant solution to rearrange(sort) elements in the vector, so that not modified objects will be grouped at the beginning of the sequence.
2011/10/10
['https://Stackoverflow.com/questions/7718418', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/801620/']
You can use [Partition](http://www.cplusplus.com/reference/algorithm/partition/) algorithm from standard library for that: ``` bool MyPredicate(A& a) { return a.isNew();} ... // bound is iterator pointing to the first element for which predicate returns false vector<A>::iterator bound = partition(coll.begin(), coll.end(), MyPredicate); ``` Or, as Christian Rau suggested solution without separate function: ``` std::partition(coll.begin(), coll.end(), std::mem_fun_ref(&A::isNew)) ```
`std::sort` lets you provide a custom comparison function object. You define a class that overrides the paranthesis operator, and returns true if the first argument should come before the right argument: ``` class COrderByDirty { bool operator(const A& lhs, const A& rhs) const { // Says lhs should come before rhs only if // lhs is marked as dirty, and rhs is not if (lhs.GetDirty() < rhs.Dirty()) { return true; } } } ``` Then simply instantiate it use it to sort: ``` std::sort(coll.begin(), coll.end(), COrderByDirty()); ``` If you can use C++11, you can avoid the lengthy class creation and use a lambda, as Kernek does in his answer.
7,718,418
Let's have simplified class: ``` class A { bool val_; public: A() : val_(true) {} bool isNew() const { return val_; } void setDirty() { val_ = false; } }; ``` and the vector of objects of such class: ``` vector<A> coll; coll.push_back(A()); coll.push_back(A()); coll.push_back(A()); coll.push_back(A()); coll[1].setDirty(); coll[3].setDirty(); ``` I need some elegant solution to rearrange(sort) elements in the vector, so that not modified objects will be grouped at the beginning of the sequence.
2011/10/10
['https://Stackoverflow.com/questions/7718418', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/801620/']
You can use [Partition](http://www.cplusplus.com/reference/algorithm/partition/) algorithm from standard library for that: ``` bool MyPredicate(A& a) { return a.isNew();} ... // bound is iterator pointing to the first element for which predicate returns false vector<A>::iterator bound = partition(coll.begin(), coll.end(), MyPredicate); ``` Or, as Christian Rau suggested solution without separate function: ``` std::partition(coll.begin(), coll.end(), std::mem_fun_ref(&A::isNew)) ```
You could use `std::sort` from `<algorithm>` together with `boost::bind`. It could look something like this: ``` std::sort(coll.begin(), coll.end(), boost::bind(&A::isDirty, _1)); ``` Assuming `A` has a function `bool A::isDirty() const`. This works because you use the following ordering predicate implicitly: ``` bool cmp(const A &a, const A &b) { return a.isDirty(); } ``` We just don't care what happens when both are dirty or both are not dirty.
7,718,418
Let's have simplified class: ``` class A { bool val_; public: A() : val_(true) {} bool isNew() const { return val_; } void setDirty() { val_ = false; } }; ``` and the vector of objects of such class: ``` vector<A> coll; coll.push_back(A()); coll.push_back(A()); coll.push_back(A()); coll.push_back(A()); coll[1].setDirty(); coll[3].setDirty(); ``` I need some elegant solution to rearrange(sort) elements in the vector, so that not modified objects will be grouped at the beginning of the sequence.
2011/10/10
['https://Stackoverflow.com/questions/7718418', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/801620/']
How about `sort`: ``` #include <algorithm> std::sort(coll.begin(), coll.end(), [](const A & a, const A & b) -> bool { return a.isNew() < b.isNew(); } ); ``` You'll have to rewrite the class to declare `isNew()` as `const`. For older compilers, use a function instead of the lambda: ``` bool isNewCompare(const A & a, const A & b) { return a.isNew() < b.isNew(); } std::sort(coll.begin(), coll.end(), isNewCompare); ``` *Edit:* @Vladimir has the better answer, `std::partition()` is the more appropriate algorithm for this problem.
`std::sort` lets you provide a custom comparison function object. You define a class that overrides the paranthesis operator, and returns true if the first argument should come before the right argument: ``` class COrderByDirty { bool operator(const A& lhs, const A& rhs) const { // Says lhs should come before rhs only if // lhs is marked as dirty, and rhs is not if (lhs.GetDirty() < rhs.Dirty()) { return true; } } } ``` Then simply instantiate it use it to sort: ``` std::sort(coll.begin(), coll.end(), COrderByDirty()); ``` If you can use C++11, you can avoid the lengthy class creation and use a lambda, as Kernek does in his answer.
7,718,418
Let's have simplified class: ``` class A { bool val_; public: A() : val_(true) {} bool isNew() const { return val_; } void setDirty() { val_ = false; } }; ``` and the vector of objects of such class: ``` vector<A> coll; coll.push_back(A()); coll.push_back(A()); coll.push_back(A()); coll.push_back(A()); coll[1].setDirty(); coll[3].setDirty(); ``` I need some elegant solution to rearrange(sort) elements in the vector, so that not modified objects will be grouped at the beginning of the sequence.
2011/10/10
['https://Stackoverflow.com/questions/7718418', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/801620/']
How about `sort`: ``` #include <algorithm> std::sort(coll.begin(), coll.end(), [](const A & a, const A & b) -> bool { return a.isNew() < b.isNew(); } ); ``` You'll have to rewrite the class to declare `isNew()` as `const`. For older compilers, use a function instead of the lambda: ``` bool isNewCompare(const A & a, const A & b) { return a.isNew() < b.isNew(); } std::sort(coll.begin(), coll.end(), isNewCompare); ``` *Edit:* @Vladimir has the better answer, `std::partition()` is the more appropriate algorithm for this problem.
You could use `std::sort` from `<algorithm>` together with `boost::bind`. It could look something like this: ``` std::sort(coll.begin(), coll.end(), boost::bind(&A::isDirty, _1)); ``` Assuming `A` has a function `bool A::isDirty() const`. This works because you use the following ordering predicate implicitly: ``` bool cmp(const A &a, const A &b) { return a.isDirty(); } ``` We just don't care what happens when both are dirty or both are not dirty.
11,277,841
If I try to build my .sln file in visual studio (using release configuration, but actually none of my configurations build), the build fails with zero errors in the output window and none the error list. In fact, in the build output window, I have 7 projects listed. And under normal verbosity, I have 7 "Build succeeded." lines after each project. Yet at the bottom: ``` ========== Build: 6 succeeded or up-to-date, 1 failed, 0 skipped ========== ``` By building the projects one by one, I have found the 'failing' project and I tried to build it all by itself. It depends on one other project and that builds just fine all by itself. I try building the 'failing' project by itself and I get zero errors and no warnings and a build failed. However in the 'bin' folder for that project, (if I delete the old bin file) I am getting a built dll. Doesn't do me much good though, since the build is 'failing', visual studio makes no effort to launch my project in debug mode. Here's something puzzling: In the command line, I have navigated to the directory with my .sln file in it, and I then run this command: ``` C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe /ToolsVersion:4.0 /p:Configuration=Release ``` Then, in bin/Release, voila, I have my built project. The build passes in the command line but not the IDE. Does anyone have any suggestions? This problem has happened to me twice: Once on windows server 2008 and once on windows xp sp3.
2012/06/30
['https://Stackoverflow.com/questions/11277841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300385/']
[Visual Studio 2010 says Build failed with no errors after I change a source file](https://stackoverflow.com/questions/5068011/visual-studio-2010-says-build-failed-with-no-errors-after-i-change-a-source-file) One answer there suggested that I change the place from where I'm building. Here's the path of the debug directory: C:\Users\Isaac\Documents\Visual Studio 2010\Projects\checkout\Library Projects\BaseSystemCore\BaseSystemCore\bin\Debug Just moving the checkout directory to c:\ did the trick. Something to do with the build path being too long.
I had the same error, it would not build but no errors. Restarting visual studio worked for me, this was in visual studio 2012.
11,277,841
If I try to build my .sln file in visual studio (using release configuration, but actually none of my configurations build), the build fails with zero errors in the output window and none the error list. In fact, in the build output window, I have 7 projects listed. And under normal verbosity, I have 7 "Build succeeded." lines after each project. Yet at the bottom: ``` ========== Build: 6 succeeded or up-to-date, 1 failed, 0 skipped ========== ``` By building the projects one by one, I have found the 'failing' project and I tried to build it all by itself. It depends on one other project and that builds just fine all by itself. I try building the 'failing' project by itself and I get zero errors and no warnings and a build failed. However in the 'bin' folder for that project, (if I delete the old bin file) I am getting a built dll. Doesn't do me much good though, since the build is 'failing', visual studio makes no effort to launch my project in debug mode. Here's something puzzling: In the command line, I have navigated to the directory with my .sln file in it, and I then run this command: ``` C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe /ToolsVersion:4.0 /p:Configuration=Release ``` Then, in bin/Release, voila, I have my built project. The build passes in the command line but not the IDE. Does anyone have any suggestions? This problem has happened to me twice: Once on windows server 2008 and once on windows xp sp3.
2012/06/30
['https://Stackoverflow.com/questions/11277841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300385/']
[Visual Studio 2010 says Build failed with no errors after I change a source file](https://stackoverflow.com/questions/5068011/visual-studio-2010-says-build-failed-with-no-errors-after-i-change-a-source-file) One answer there suggested that I change the place from where I'm building. Here's the path of the debug directory: C:\Users\Isaac\Documents\Visual Studio 2010\Projects\checkout\Library Projects\BaseSystemCore\BaseSystemCore\bin\Debug Just moving the checkout directory to c:\ did the trick. Something to do with the build path being too long.
Close Visual Studio. Run cmd, and type: **C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe /ToolsVersion:4.0 /p:Configuration=Release *yoursolution.sln*** Then, enter again on VS and run your project. Worked for me!
11,277,841
If I try to build my .sln file in visual studio (using release configuration, but actually none of my configurations build), the build fails with zero errors in the output window and none the error list. In fact, in the build output window, I have 7 projects listed. And under normal verbosity, I have 7 "Build succeeded." lines after each project. Yet at the bottom: ``` ========== Build: 6 succeeded or up-to-date, 1 failed, 0 skipped ========== ``` By building the projects one by one, I have found the 'failing' project and I tried to build it all by itself. It depends on one other project and that builds just fine all by itself. I try building the 'failing' project by itself and I get zero errors and no warnings and a build failed. However in the 'bin' folder for that project, (if I delete the old bin file) I am getting a built dll. Doesn't do me much good though, since the build is 'failing', visual studio makes no effort to launch my project in debug mode. Here's something puzzling: In the command line, I have navigated to the directory with my .sln file in it, and I then run this command: ``` C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe /ToolsVersion:4.0 /p:Configuration=Release ``` Then, in bin/Release, voila, I have my built project. The build passes in the command line but not the IDE. Does anyone have any suggestions? This problem has happened to me twice: Once on windows server 2008 and once on windows xp sp3.
2012/06/30
['https://Stackoverflow.com/questions/11277841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300385/']
[Visual Studio 2010 says Build failed with no errors after I change a source file](https://stackoverflow.com/questions/5068011/visual-studio-2010-says-build-failed-with-no-errors-after-i-change-a-source-file) One answer there suggested that I change the place from where I'm building. Here's the path of the debug directory: C:\Users\Isaac\Documents\Visual Studio 2010\Projects\checkout\Library Projects\BaseSystemCore\BaseSystemCore\bin\Debug Just moving the checkout directory to c:\ did the trick. Something to do with the build path being too long.
if your solution contains too many projects , build projects individually, Check which project is failing for that project check the references of that project , if on any reference if their is yellow color mark, then delete that reference , and add that again , then build and check, this will work or check in output window , each line , in some line it may be showing , dependency is their, but file didnt exist that is the problem causing this may be due to file corruption
11,277,841
If I try to build my .sln file in visual studio (using release configuration, but actually none of my configurations build), the build fails with zero errors in the output window and none the error list. In fact, in the build output window, I have 7 projects listed. And under normal verbosity, I have 7 "Build succeeded." lines after each project. Yet at the bottom: ``` ========== Build: 6 succeeded or up-to-date, 1 failed, 0 skipped ========== ``` By building the projects one by one, I have found the 'failing' project and I tried to build it all by itself. It depends on one other project and that builds just fine all by itself. I try building the 'failing' project by itself and I get zero errors and no warnings and a build failed. However in the 'bin' folder for that project, (if I delete the old bin file) I am getting a built dll. Doesn't do me much good though, since the build is 'failing', visual studio makes no effort to launch my project in debug mode. Here's something puzzling: In the command line, I have navigated to the directory with my .sln file in it, and I then run this command: ``` C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe /ToolsVersion:4.0 /p:Configuration=Release ``` Then, in bin/Release, voila, I have my built project. The build passes in the command line but not the IDE. Does anyone have any suggestions? This problem has happened to me twice: Once on windows server 2008 and once on windows xp sp3.
2012/06/30
['https://Stackoverflow.com/questions/11277841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300385/']
I had the same error, it would not build but no errors. Restarting visual studio worked for me, this was in visual studio 2012.
Close Visual Studio. Run cmd, and type: **C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe /ToolsVersion:4.0 /p:Configuration=Release *yoursolution.sln*** Then, enter again on VS and run your project. Worked for me!
11,277,841
If I try to build my .sln file in visual studio (using release configuration, but actually none of my configurations build), the build fails with zero errors in the output window and none the error list. In fact, in the build output window, I have 7 projects listed. And under normal verbosity, I have 7 "Build succeeded." lines after each project. Yet at the bottom: ``` ========== Build: 6 succeeded or up-to-date, 1 failed, 0 skipped ========== ``` By building the projects one by one, I have found the 'failing' project and I tried to build it all by itself. It depends on one other project and that builds just fine all by itself. I try building the 'failing' project by itself and I get zero errors and no warnings and a build failed. However in the 'bin' folder for that project, (if I delete the old bin file) I am getting a built dll. Doesn't do me much good though, since the build is 'failing', visual studio makes no effort to launch my project in debug mode. Here's something puzzling: In the command line, I have navigated to the directory with my .sln file in it, and I then run this command: ``` C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe /ToolsVersion:4.0 /p:Configuration=Release ``` Then, in bin/Release, voila, I have my built project. The build passes in the command line but not the IDE. Does anyone have any suggestions? This problem has happened to me twice: Once on windows server 2008 and once on windows xp sp3.
2012/06/30
['https://Stackoverflow.com/questions/11277841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300385/']
I had the same error, it would not build but no errors. Restarting visual studio worked for me, this was in visual studio 2012.
if your solution contains too many projects , build projects individually, Check which project is failing for that project check the references of that project , if on any reference if their is yellow color mark, then delete that reference , and add that again , then build and check, this will work or check in output window , each line , in some line it may be showing , dependency is their, but file didnt exist that is the problem causing this may be due to file corruption
12,964,364
I am working on a physics engine related project. In the C++ code below: ``` #include <iostream> #include <vector> struct Vector3 { float x; float y; float z; }; struct object { std::vector < std::vector < Vector3 > > set_vertices; int ID; int Type; }; class World { public: std::vector< object > objects; private: // other members }; int main (void) { World world; // How to fill in "objects" of "world"? // Is this safe to do? world.objects.resize(5); // What about the way of allocating "set_vertices" below? for(size_t i=0; i<world.objects.size(); i++) { world.objects[i].set_vertices.resize(12, std::vector < Vector3 >(3)); for(size_t j=0; j<world.objects[i].set_vertices.size(); j++) { for(size_t k=0; k<world.objects[i].set_vertices[j].size(); k++) { world.objects[i].set_vertices[j][k].x = 0.0f; world.objects[i].set_vertices[j][k].y = 0.0f; world.objects[i].set_vertices[j][k].z = 0.0f; world.objects[i].ID = i; world.objects[i].Type = 0; } } } return 0; } ``` is the way I have allocated memory for `objects` of `world` safe? There would be any memory related issue? Is there any better way of initializing `objects` dynamically (i.e. not in constructor)? If so, how? thanks.
2012/10/18
['https://Stackoverflow.com/questions/12964364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1023798/']
I'd imagine that using RAII and having the constructor and destructor of `object` to take care of the memory would be a better way of doing this. Adding in a new `object` into world you can make use of `std::vector` ability to resize dynamically by just calling `push_back()` instead of needing to create the loop that has `i` as the index. To avoid unnecessary resizes if you know how many elements you are adding in advance you can call `.reserve(n)` where `n` is the number of elements you are adding.
It's safe. You could save boilerplate by moving all that filling into a constructor, if appropriate. You might also be able to find a more efficient approach than levels of nested vectors. So, it's safe but could still be improved.
42,006,760
I have a table: ``` <div> <div className="shadow-z-1"> <table className="table table-bordered table-hover"> <thead> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>John</td> <td>Doe</td> </tr> <tr> <td>2</td> <td>Jane</td> <td>Doe</td> </tr> </tbody> </table> </div> ... </div> ``` And I am currently styling it using the following stylesheet: ``` .shadow-z-1 { -webkit-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 1px 2px 0 rgba(0, 0, 0, 0.24); -moz-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 1px 2px 0 rgba(0, 0, 0, 0.24); box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 1px 2px 0 rgba(0, 0, 0, 0.24); } .table { width: 100%; max-width: 100%; margin-top: 1rem; margin-bottom: 2rem; background-color: #fff; > { thead > tr, tbody > tr, tfoot > tr { -webkit-transition: all 0.3s ease; -o-transition: all 0.3s ease; transition: all 0.3s ease; } thead > tr > th, tbody > tr > th, tfoot > tr > th, thead > tr > td, tbody > tr > td, tfoot > tr > td { text-align: left; padding: 1.6rem; vertical-align: top; border-top: 0; -webkit-transition: all 0.3s ease; -o-transition: all 0.3s ease; transition: all 0.3s ease; } thead > tr > th { font-weight: 400; color: #757575; vertical-align: bottom; border-bottom: 1px solid rgba(0, 0, 0, 0.12); } caption + thead > tr:first-child > th, colgroup + thead > tr:first-child > th, thead:first-child > tr:first-child > th, caption + thead > tr:first-child > td, colgroup + thead > tr:first-child > td, thead:first-child > tr:first-child > td { border-top: 0; } tbody + tbody { border-top: 1px solid rgba(0, 0, 0, 0.12); } } .table { background-color: #fff; } .no-border { border: 0; } } .table-condensed > { thead > tr > th, tbody > tr > th, tfoot > tr > th, thead > tr > td, tbody > tr > td, tfoot > tr > td { padding: 0.8rem; } } .table-bordered { border: 0; > { thead > tr > th, tbody > tr > th, tfoot > tr > th, thead > tr > td, tbody > tr > td, tfoot > tr > td { border: 0; border-bottom: 1px solid #e0e0e0; } thead > tr > { th, td { border-bottom-width: 2px; } } } } .table-striped > tbody > tr:nth-child(odd) > { td, th { background-color: #f5f5f5; } } .table-hover > tbody > tr:hover > { td, th { background-color: rgba(0, 0, 0, 0.12); } } ``` This is working fine but what I am trying to do now is add in vertical and horizontal scrolling to the table. For the vertical scrolling, I would like to keep the header fixed so I know I need to give the table body a definitive height but I can't figure out where I should be doing it in my stylesheet. For the horizontal scrolling, I don't really know where to begin. I would like to be able to keep the width of all the columns the same so that if another one is added, rather than being squeezed into a defined area the horizontal scrollbar will show up. Ideally I am looking to achieve this using only css (or SaSS in my case). Any help with this would be much appreciated! Thanks for your time.
2017/02/02
['https://Stackoverflow.com/questions/42006760', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5993072/']
Here is a css code: ```css .scroll-table-container { border:2px solid green; height: 300px; overflow: scroll; } .scroll-table, td, th { border-collapse:collapse; border:1px solid #777; min-width: 300px;} ```
Check this example: ``` <html> <head> <style> div{display:inline-block;height:46px;overflow:scroll} table{background:gray} td{background:green} td,th{width:100px} th{background:orange} </style> </head> <body> <table> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> </tr> </table> <div> <table> <tr> <td>1</td> <td>John</td> <td>Doe</td> </tr> <tr> <td>2</td> <td>Jane</td> <td>Doe</td> </tr> <tr> <td>3</td> <td>Josh</td> <td>Doe</td> </tr> <tr> <td>4</td> <td>Joana</td> <td>Doe</td> </tr> </table> </div> </body> </html> ```
47,488,903
I downloaded PayuMoney payment extension for Magento 1.9 from their website and copied the respective directories/code in the app folder. In the Admin, it is showing the configuration settings for this extension where I entered following details as instructed in the integration guide document: ``` Enabled: ​ ‘Yes’ Environment: sandbox PayUmoney Key: Test key as provided in the guide (for testing purpose) PayUmoney Salt:​ Test salt as provided in the guide (for testing purpose) Citrus Payment/Vanity Url: Blank Citrus Access Key:​ Blank Citrus Secret Key: Blank Route (%): Blank ``` [Refer the screenshot: PayuMoney extension setting in Magento Admin](https://i.stack.imgur.com/cHsFi.png) I want to test the functionality hence want to use sandbox environment with test credentials provided in the guide. But with above configuration setting, PayuMoney is not coming up for the customer in the checkout page as a payment option. I checked related threads but it has not helped much. Appreciate if anyone has any idea to solve this problem.
2017/11/25
['https://Stackoverflow.com/questions/47488903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4873820/']
First of all, it's important to realize that though "model the animal kingdom in a class hierarchy" is a common beginner exercise, and often used in examples -- I use Animal, Mammal, Giraffe, Tiger, and so on all the time in examples -- **it is not a realistic problem to solve using OO techniques**. It's simply intended to get you thinking about the concepts in OO programming by thinking about a domain that you already understand well. Real zoos which have software to manage their animal inventory do not build class hierarchies like this because their concerns do not actually include what mammals have in common over what birds have in common. Though animal kingdom analogies are useful to get going with OO, it's important to not come away with the belief that every feature that exists in a real-world hierarchy has to be modeled in the class hierarchy. So, that said, the rest of my critique will be assuming that you really do want to model the animal kingdom as an exercise. Second, the fundamental problem with your implementation is that the hierarchy is either not deep enough or too deep. The problem is that *mammal and bird should be abstract* because there is no thing in the world that is *just a mammal* or *just a bird*. What you want is an abstract class bird that extends animal, and then a concrete (and probably sealed!) class Crow that extends Bird. Then the question to ask is: do I really need the mammal and bird levels at all? Are they *useful* to my program? Am I ever going to have a method that can take any mammal but no lizard? If its not useful then eliminate it, and go straight from animal to crow. Third, the sound a crow makes is "caw caw", not "crow sound". :-) Fourth, to answer your best question: you typically use an interface when you have *several unrelated things that "can do" the same thing but with different implementations* and you use an abstract class *to share implementation details amongst classes that have an "is a kind of" relationship.* Making a sound is a something that a lot of things can do that are unrelated to each other. A bird and a piano are not the same kind of thing and they have different mechanisms, but they both make sounds. So making sound should be represented by an interface. A bird is a kind of animal, and there might be functions common to all animals that are specialized by birds. In short: a bird is a kind of animal, so it should be a subclass. A bird can make a sound, and lots of other things can also, so making a sound should be an interface.
one of the reasons you want to use Interface is that C# does not support multiple inheritance. In general, I would like to think of interface as ability or feature instead of being a model. Something like: ``` public interface ISwimable { int SwimmingSpeed { get; set; } } public interface IWalkable { int RunningSpeed { get; set; } } ``` Now if I have an animal that lives in water I would like it to implement ISwimable, and if I have an animal that can walk, its class should implement IWalkable, and if it can do both, it will implement both.
59,174,310
I am working on a C++ project using CodeBlocks on Windows but then decided to switch to NetBeans IDE 8.2. Within my project, I am calling another executable file with some passed parameters (I run the other .exe with suitable parameters then I take the output of it to use in my main project), and it used to work on CodeBlocks but not on NetBeans. The code is the following: ``` #include <iostream> #include <fstream> #include <stdlib.h> #include <cstdlib> #include <string.h> #include <sstream> #include <vector> #include <stdio.h> #include <stdlib.h> #include <windows.h> #include "My_Constants.h" #include "Data.h" #include "Parameters.h" #include "Pattern.h" #include "Squish.h" #include "Deserializer.h" #include "Automatic_Run.h" using namespace std; int main() { Parameters parameters; parameters.mode = SQUISH; Automatic_Run runner; string inputname; //--------------------------------User Input------------------------------------- cout << "enter input file name \n"; getline(cin, inputname); parameters.inputFileName.assign(inputname); cout<<"=============================================================================\n"; //--------------------------------Running SQUISH/first call-------------------------- cout<<"Running SQUISH - first call\n"; char command[1000]=""; string passedParameters = " -i "+parameters.inputFileName +" -f "+ "t"; strcat(command,"C:\\Users\\Administrator\\Documents\\CodeBlocksProjects\\TestSQUISH\\bin\\Debug\\TestSQUISH.exe "); strcat(command,passedParameters.c_str()); int result = system(command); // the rest of the code(not relevant to the problem) return 0; } ``` On CodeBlocks, it used to work perfectly and give me the output as a file in the path of my main project (the one I am calling TestSQUISH from). However, now on NetBeans, I am getting the following error: > > sh: C:UsersAdministratorDocumentsCodeBlocksProjectsTestSQUISHbinDebugTestSQUISH.exe: command not found > > > I checked the terminal of NetBeans to get an idea of what is happening (assuming it might be related) and I noticed that I have to change the path first, then run the executable using: > > ./ TestSQUISH.exe (+parameters) > > > However, that also didn't work for my project. Can anyone please suggest a solution or tell me how I can make NetBeans run the command on a Windows terminal as CodeBlocks used to do?
2019/12/04
['https://Stackoverflow.com/questions/59174310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1383685/']
Your current remote will be using https protocol. That is why it is still asking for password. use `git remote show origin | grep URL` to see the current remote URL for origin if it starts with `https://` it will ask for username and password. Then remove it by `git remote rm origin` Then add ssh url by `git remote add origin <url>` Make sure that you provide ssh url here, it should be something like `[email protected]..` Go to your github repo and click on green clone button and if it is in https format change it to ssh [![enter image description here](https://i.stack.imgur.com/AAX5b.png)](https://i.stack.imgur.com/AAX5b.png) Use the `Use SSH` link to change it to SSH Then you should see the ssh url [![enter image description here](https://i.stack.imgur.com/GNuIo.png)](https://i.stack.imgur.com/GNuIo.png)
Github does not provide SSH access. Your command is trying to connecto to github by ssh as connection to a remote computer. This is not what you are allowed to do. What you can do with the SSH keys in github now, is clone repositories, commit, etc. ``` git clone [email protected]:<project> ``` And with SSH you are allowed to do actions on a project with the registered user. Now you can commit, perform pull requests, ...
59,174,310
I am working on a C++ project using CodeBlocks on Windows but then decided to switch to NetBeans IDE 8.2. Within my project, I am calling another executable file with some passed parameters (I run the other .exe with suitable parameters then I take the output of it to use in my main project), and it used to work on CodeBlocks but not on NetBeans. The code is the following: ``` #include <iostream> #include <fstream> #include <stdlib.h> #include <cstdlib> #include <string.h> #include <sstream> #include <vector> #include <stdio.h> #include <stdlib.h> #include <windows.h> #include "My_Constants.h" #include "Data.h" #include "Parameters.h" #include "Pattern.h" #include "Squish.h" #include "Deserializer.h" #include "Automatic_Run.h" using namespace std; int main() { Parameters parameters; parameters.mode = SQUISH; Automatic_Run runner; string inputname; //--------------------------------User Input------------------------------------- cout << "enter input file name \n"; getline(cin, inputname); parameters.inputFileName.assign(inputname); cout<<"=============================================================================\n"; //--------------------------------Running SQUISH/first call-------------------------- cout<<"Running SQUISH - first call\n"; char command[1000]=""; string passedParameters = " -i "+parameters.inputFileName +" -f "+ "t"; strcat(command,"C:\\Users\\Administrator\\Documents\\CodeBlocksProjects\\TestSQUISH\\bin\\Debug\\TestSQUISH.exe "); strcat(command,passedParameters.c_str()); int result = system(command); // the rest of the code(not relevant to the problem) return 0; } ``` On CodeBlocks, it used to work perfectly and give me the output as a file in the path of my main project (the one I am calling TestSQUISH from). However, now on NetBeans, I am getting the following error: > > sh: C:UsersAdministratorDocumentsCodeBlocksProjectsTestSQUISHbinDebugTestSQUISH.exe: command not found > > > I checked the terminal of NetBeans to get an idea of what is happening (assuming it might be related) and I noticed that I have to change the path first, then run the executable using: > > ./ TestSQUISH.exe (+parameters) > > > However, that also didn't work for my project. Can anyone please suggest a solution or tell me how I can make NetBeans run the command on a Windows terminal as CodeBlocks used to do?
2019/12/04
['https://Stackoverflow.com/questions/59174310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1383685/']
Your current remote will be using https protocol. That is why it is still asking for password. use `git remote show origin | grep URL` to see the current remote URL for origin if it starts with `https://` it will ask for username and password. Then remove it by `git remote rm origin` Then add ssh url by `git remote add origin <url>` Make sure that you provide ssh url here, it should be something like `[email protected]..` Go to your github repo and click on green clone button and if it is in https format change it to ssh [![enter image description here](https://i.stack.imgur.com/AAX5b.png)](https://i.stack.imgur.com/AAX5b.png) Use the `Use SSH` link to change it to SSH Then you should see the ssh url [![enter image description here](https://i.stack.imgur.com/GNuIo.png)](https://i.stack.imgur.com/GNuIo.png)
All I want at this point is to no enter my username and password whenever I want to push my stuff on github. I made it work. But a day I had to create an other ssh key and id for my VPS but I overwrited it, I didn't know that I have to create one id/key per file. So I delete known\_host and erase the content of rsa.pub and rsa, and create a brand new one but it don't work..
56,323,181
How to delete duplicate from this result ``` select *, row_number() over (order by (select null)) as seqnum from [elo].[dbo].[objkeys] where parentid in (select parentid from [elo].[dbo].[objekte] inner join [elo].[dbo].[objkeys] on objid = parentid where objmask like 26 and okeydata like 'yes' ) ``` output is ``` parentid okeyname okeydata 1 name a 1 number 1 1 yes_no yes 2 name a 2 number 1 2 yes_no yes 3 name a 3 number 1 3 yes_no no 4 name a 4 number 2 4 yes_no no 5 name b 5 number 3 5 yes_no yes 6 name b 6 number 3 6 yes_no yes 7 name b 7 number 3 7 yes_no no 8 name b 8 number 3 8 yes_no no ``` need to be like this ``` parentid okeyname okeydata 1 name a 1 number 1 1 yes_no yes 3 name a 3 number 1 3 yes_no no 5 name b 5 number 3 5 yes_no yes 7 name b 7 number 3 7 yes_no no ```
2019/05/27
['https://Stackoverflow.com/questions/56323181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10306114/']
Can you please try **ml-auto** instead of **mr-auto**? So the ul tag will be like this ``` <ul class="navbar-nav ml-auto"> ```
Please check the following Stack Overflow post [What happened to the .pull-left and .pull-right classes in Bootstrap 4?](https://stackoverflow.com/questions/39655110/what-happened-to-the-pull-left-and-pull-right-classes-in-bootstrap-4/42887127) Hope this helps you out.
45,614,363
I am having trouble getting my Alamofire call to execute my json Closure in Swift. Below is my NetworkingService file: ``` import Foundation import Alamofire import SwiftyJSON class NetworkingService { static let shared = NetworkingService() private init() {} func getSong(completionHandler: @escaping (JSON) -> Void) { Alamofire.request("http://10.0.1.7/myiosapp/v1/songs.php", method: .get, parameters: nil, encoding: URLEncoding(), headers: nil).responseJSON { (response) in print(response) } } } ``` Below is my Model class, Song: ``` import Foundation import SwiftyJSON struct Song { let trackName: String let trackArtist: String let trackFile: String // failable intializer init?(json: JSON) { guard let trackName = json["track"].string, let trackArtist = json["artist"].string, let trackFile = json["file"].string else { return nil } self.trackName = trackName self.trackArtist = trackArtist self.trackFile = trackFile } } ``` Below is the relevant code in my HomeController file: ``` import UIKit import SwiftyJSON class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout { override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) showJSON() } var songs = [SongTest]() func showJSON() { print("This print outs") NetworkingService.shared.getSong { (json) in print("This does not print out") self.songs = [] if let listOfSongs = json["songs"].array { for item in listOfSongs { let song = SongTest(json: item) self.songs.append(song!) } for r in self.songs { print(r.trackName) print(r.trackArtist) print(r.trackFile) } } } } } ``` In my HomeController, I am able to see ("this prints out") in my console along with the JSON data from the url, which is managed in my NetworkService file. I have set a breakpoint at `NetworkingService.shared.getSong { (json) in`. If the JSON data is printing out, it makes me believe the error is occurring with this closure: `(json)`. Any ideas on why this is happening and how to fix-it?
2017/08/10
['https://Stackoverflow.com/questions/45614363', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5412136/']
In your first method you define a `completionHandler` that you never call : This should works: ``` func getSong(completionHandler: @escaping (JSON) -> Void) { Alamofire.request("http://10.0.1.7/myiosapp/v1/songs.php", method: .get, parameters: nil, encoding: URLEncoding(), headers: nil).responseJSON { (response) in print(response) completionHandler(response.result.value) } } ```
As per this code i think you missed to call the `completionHandler(response)`
45,614,363
I am having trouble getting my Alamofire call to execute my json Closure in Swift. Below is my NetworkingService file: ``` import Foundation import Alamofire import SwiftyJSON class NetworkingService { static let shared = NetworkingService() private init() {} func getSong(completionHandler: @escaping (JSON) -> Void) { Alamofire.request("http://10.0.1.7/myiosapp/v1/songs.php", method: .get, parameters: nil, encoding: URLEncoding(), headers: nil).responseJSON { (response) in print(response) } } } ``` Below is my Model class, Song: ``` import Foundation import SwiftyJSON struct Song { let trackName: String let trackArtist: String let trackFile: String // failable intializer init?(json: JSON) { guard let trackName = json["track"].string, let trackArtist = json["artist"].string, let trackFile = json["file"].string else { return nil } self.trackName = trackName self.trackArtist = trackArtist self.trackFile = trackFile } } ``` Below is the relevant code in my HomeController file: ``` import UIKit import SwiftyJSON class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout { override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) showJSON() } var songs = [SongTest]() func showJSON() { print("This print outs") NetworkingService.shared.getSong { (json) in print("This does not print out") self.songs = [] if let listOfSongs = json["songs"].array { for item in listOfSongs { let song = SongTest(json: item) self.songs.append(song!) } for r in self.songs { print(r.trackName) print(r.trackArtist) print(r.trackFile) } } } } } ``` In my HomeController, I am able to see ("this prints out") in my console along with the JSON data from the url, which is managed in my NetworkService file. I have set a breakpoint at `NetworkingService.shared.getSong { (json) in`. If the JSON data is printing out, it makes me believe the error is occurring with this closure: `(json)`. Any ideas on why this is happening and how to fix-it?
2017/08/10
['https://Stackoverflow.com/questions/45614363', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5412136/']
I was able to solve my problem: ``` class NetworkingService { static let shared = NetworkingService() private init() {} func getSong(completionHandler: @escaping (JSON) -> Void) { Alamofire.request("http://10.0.1.7/myiosapp/v1/songs.php", method: .get, parameters: nil, encoding: URLEncoding(), headers: nil).responseJSON { (response) in guard let value = response.result.value else { completionHandler(response.result.error as! JSON) return } let swiftyJsonVar = JSON(value) completionHandler(swiftyJsonVar) } } } ```
As per this code i think you missed to call the `completionHandler(response)`
64,618,846
I'm new in wordpress and woocommerce development part. I'm trying to integrate woocommerce for my products, everything was fine. But when i click on product permalink for product details or product single page it's redirect to the same page. Interesting thing is when i click on product, the url changed but not go through to the details page. Here is the page link- <https://dev.shopvitalsleep.com/collections/all/> I'm using loop inside woocommerce.php with my custom designed page. Here is the code sample- ```php <div class="row justify-content-center equal-box"> <?php $args = array( 'post_type' => 'product', 'posts_per_page' => 12 ); $loop = new WP_Query( $args ); if ( $loop->have_posts() ) { while ( $loop->have_posts() ) : $loop->the_post(); $product = wc_get_product($loop->post->ID); ?> <div class="col-lg-6 mb-4"> <div class="product-content text-center"> <div class="product-images"> <a href="<?php the_permalink(); ?>" class="product-details-link"> <?php the_post_thumbnail('full'); ?> </a> </div> <div class="product-info"> <h4 class="product-title"><?php echo get_the_title(); ?></h4> <div class="price"> <p> <span class="reg-price"> <del>$<?php echo get_post_meta( get_the_ID(), '_regular_price', true ); ?></del> </span> <span class="sell-price">now $<?php echo get_post_meta( get_the_ID(), '_sale_price', true ); ?> USD</span> </p> </div> </div> </div> <div class="row mt-auto product-content text-center mb-2"> <div class="col-6"> <a class="button style-blue view-detail-button" href="<?php the_permalink(); ?>">View Details</a> </div> <div class="col-6"> <div class="add-to-cart "><?php echo sprintf( '<a href="%s" data-quantity="1" class="%s" %s>%s</a>', esc_url( $product->add_to_cart_url() ), esc_attr( implode( ' ', array_filter( array( 'button', 'product_type_' . $product->get_type(), $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '', $product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '', ) ) ) ), wc_implode_html_attributes( array( 'data-product_id' => $product->get_id(), 'data-product_sku' => $product->get_sku(), 'aria-label' => $product->add_to_cart_description(), 'rel' => 'nofollow', ) ), esc_html( $product->add_to_cart_text() ) ); ?> </div> </div> </div> </div> <?php endwhile; } else { echo __( 'No products found' ); } wp_reset_postdata(); ?> </div> ``` Folder structure: `../themes/theme-name/woocommerce.php` Please help me to findout where i make mistakes.
2020/10/31
['https://Stackoverflow.com/questions/64618846', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7088878/']
Looks like your WooCommerce single page is not working. Take a look at their official docs for the correct file structure. I think you have a problem here referencing incorrect file or you have overwritten core file, like woocommerce.php. You should use a child theme and then do your edits there. [WooCommerce Docs Template Structure](https://docs.woocommerce.com/document/template-structure/)
I figured it out! The problem is `woocommerce.php` file. This file overwrite the other directory. In my case, I'm developing a custom theme that's why I need to create a directory inside my `../themes/my-theme` nameed- `/woocommerce/archive-product.php` and delete `woocommerce.php` form `../themes/my-theme` So, moral of the topic is- If your theme has a `woocommerce.php` file, you will be unable to override the `woocommerce/archive-product.php` custom template in your theme, as `woocommerce.php` has priority over other template files. This is intended to prevent display issues.
1,618,038
Is there an [XSLT](http://www.w3.org/TR/xslt) equivalent for JSON? Something to allow me to do transformations on JSON like XSLT does to XML.
2009/10/24
['https://Stackoverflow.com/questions/1618038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147141/']
[JSONiq](http://www.jsoniq.org/) is such a standard and [Zorba](http://www.zorba.io/) an open-source C++ implementation. JSONiq can also be seen as XQuery with adding JSON as a native data type.
Yate (<https://github.com/pasaran/yate>) is specifically designed after XSLT, features JPath (a natural XPath equivalent for JS), compiles to JavaScript and has quite a history of production use. It’s practically undocumented, but reading through samples and tests should be enough.
1,618,038
Is there an [XSLT](http://www.w3.org/TR/xslt) equivalent for JSON? Something to allow me to do transformations on JSON like XSLT does to XML.
2009/10/24
['https://Stackoverflow.com/questions/1618038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147141/']
Have a look at [jsonpath-object-transform](https://www.npmjs.com/package/jsonpath-object-transform)
Yate (<https://github.com/pasaran/yate>) is specifically designed after XSLT, features JPath (a natural XPath equivalent for JS), compiles to JavaScript and has quite a history of production use. It’s practically undocumented, but reading through samples and tests should be enough.
1,618,038
Is there an [XSLT](http://www.w3.org/TR/xslt) equivalent for JSON? Something to allow me to do transformations on JSON like XSLT does to XML.
2009/10/24
['https://Stackoverflow.com/questions/1618038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147141/']
XSLT supports JSON as seen at <http://www.w3.org/TR/xslt-30/#json> XML uses angular brackets for delimiter tokens, JSON uses braces, square brackets, ... I. e. XML's fewer token recognition comparisons means it's optimized for declarative transformation, whereas more comparisons, being like switch statement, for speed reasons assume speculative branch prediction that imperative code in scripting languages is useful for. As direct consequence, for different mixes of semi-structured data, you may want to benchmark XSLT and javascript engines' performance as part of responsive pages. For negligible data payload, transformations might work just as well with JSON without XML serialization. W3's decision ought to be based on better analysis.
One approach not yet given is to use a parser generator to create a parser in XSLT which parses JSON and produces an XML output. One option that gets mentioned a lot at the XML conferences is the ReX parser generator (<http://www.bottlecaps.de/rex/>) - although totally undocumented on the site, recipes are available on searching.
1,618,038
Is there an [XSLT](http://www.w3.org/TR/xslt) equivalent for JSON? Something to allow me to do transformations on JSON like XSLT does to XML.
2009/10/24
['https://Stackoverflow.com/questions/1618038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147141/']
[jq - lightweight and flexible command-line JSON processor](http://stedolan.github.io/jq/) It's not template-based like XSLT, but more concise. e.g. to extract `name` and `address` fields into an array: `[.name, .address]` The [tutorial](http://stedolan.github.io/jq/tutorial/) walks through an example of transforming Twitter's JSON API (and the [manual](http://stedolan.github.io/jq/manual/) has many examples).
it is very possible to convert JSON using XSLT: you need JSON2SAX deserializer and SAX2JSON serializer. Sample code in Java: <http://www.gerixsoft.com/blog/json/xslt4json>
1,618,038
Is there an [XSLT](http://www.w3.org/TR/xslt) equivalent for JSON? Something to allow me to do transformations on JSON like XSLT does to XML.
2009/10/24
['https://Stackoverflow.com/questions/1618038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147141/']
XSLT equivalents for JSON - a list of candidates (tools and specs) Tools ===== **1. [XSLT](http://www.w3.org/TR/xslt-30/#json)** You can use [XSLT for JSON](http://www.w3.org/TR/xslt-30/#json) with the aim of [fn:json-to-xml](https://www.w3.org/TR/xslt-30/#func-json-to-xml). > > This section describes facilities allowing JSON data to be processed using XSLT. > > > **2. [jq](https://stedolan.github.io/jq/)** > > jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text. > There are install packages for different OS. > > > **3. [jj](https://github.com/tidwall/jj)** > > JJ is a command line utility that provides a fast and simple way to retrieve or update values from JSON documents. It's powered by GJSON and SJSON under the hood. > > > **4. [fx](https://github.com/antonmedv/fx)** > > Command-line JSON processing tool > > > * Don't need to learn new syntax > * Plain JavaScript > * Formatting and highlighting > * Standalone binary > > > **5. [CsvCruncher](https://github.com/OndraZizka/csv-cruncher/)** > > Command-line tabular data SQL-based processing tool > > > * Don't need to learn new syntax > * Suitable when JSON contains a large array with similar items > * Supports multiple documents to be processed as multiple SQL tables > * Written in Kotlin, runs on Java > * Also available as a Java library in Maven Central repository > > > **6. [jl](https://github.com/chrisdone/jl)** > > jl ("JSON lambda") is a tiny functional language for querying and manipulating JSON. > > > **7. [JOLT](https://github.com/bazaarvoice/jolt)** > > JSON to JSON transformation library written in Java where the "specification" for the transform is itself a JSON document. > > > **8. [gron](https://github.com/tomnomnom/gron)** > > Make JSON greppable! > gron transforms JSON into discrete assignments to make it easier to grep for what you want and see the absolute 'path' to it. It eases the exploration of APIs that return large blobs of JSON but have terrible documentation. > > > **9. [json-e](https://github.com/taskcluster/json-e)** > > JSON-e is a data-structure parameterization system for embedding context in JSON objects. > The central idea is to treat a data structure as a "template" and transform it, using another data structure as context, to produce an output data structure. > > > **10. [JSLT](https://github.com/schibsted/jslt)** > > JSLT is a complete query and transformation language for JSON. The language design is inspired by jq, XPath, and XQuery. > > > **11. [JSONata](https://docs.jsonata.org/overview.html)** > > JSONata is a lightweight query and transformation language for JSON data. Inspired by the 'location path' semantics of XPath 3.1, it allows sophisticated queries to be expressed in a compact and intuitive notation. > > > **12. [JSONPath Plus](https://github.com/JSONPath-Plus/JSONPath)** > > Analyse, transform, and selectively extract data from JSON documents (and JavaScript objects). > jsonpath-plus expands on the original specification to add some additional operators and makes explicit some behaviors the original did not spell out. > > > **13. [json-transforms](https://github.com/ColinEberhardt/json-transforms)** Last Commit Dec 1, 2017 > > Provides a recursive, pattern-matching approach to transforming JSON data. Transformations are defined as a set of rules which match the structure of a JSON object. When a match occurs, the rule emits the transformed data, optionally recursing to transform child objects. > > > **14. [json](https://github.com/trentm/json)** Last commit Jun 23, 2018 > > json is a fast CLI tool for working with JSON. It is a single-file node.js script with no external deps (other than node.js itself). > > > **15. [jsawk](https://github.com/micha/jsawk)** Last commit Mar 4, 2015 > > Jsawk is like awk, but for JSON. You work with an array of JSON objects read from stdin, filter them using JavaScript to produce a results array that is printed to stdout. > > > **16. [yate](https://github.com/pasaran/yate)** Last Commit Mar 13, 2017 > > Tests can be used as docu <https://github.com/pasaran/yate/tree/master/tests> > > > **17. [jsonpath-object-transform](https://github.com/dvdln/jsonpath-object-transform)** Last Commit Jan 18, 2017 > > Pulls data from an object literal using JSONPath and generate a new objects based on a template. > > > **18. [Stapling](https://github.com/WelcomWeb/Stapling)** Last Commit Sep 16, 2013 > > Stapling is a JavaScript library that enables XSLT formatting for JSON objects. > Instead of using a JavaScript templating engine and text/html templates, Stapling gives you the opportunity to use XSLT templates - loaded asynchronously with Ajax and then cached client side - to parse your JSON datasources. > > > Specs: ====== * [JsonPointer](https://www.rfc-editor.org/rfc/rfc6901) > > JSON Pointer defines a string syntax for identifying a specific value > within a JavaScript Object Notation (JSON) document. > > > * [JsonPath](http://goessner.net/articles/JsonPath/) > > JSONPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination with an XML document > > > * [JSPath](https://github.com/dfilatov/jspath) > > JSPath for JSON is like XPath for XML." > > > * [JSONiq](http://www.jsoniq.org/) > > The main source of inspiration behind JSONiq is XQuery, which has been proven so far a successful and productive query language for semi-structured data > > >
Interesting idea. Some searching on Google produced a few pages of interest, including: * an [outline](http://goessner.net/articles/jsont/) of how such a "jsonT" tool might be implemented, and [some downloads](http://goessner.net/download/prj/jsont/) * some [discussion of that implementation](http://ajaxian.com/archives/transforming-json) * a company which [may have implemented something suitable](https://www.p6r.com/articles/2008/05/06/xslt-and-xpath-for-json/) Hope this helps.
1,618,038
Is there an [XSLT](http://www.w3.org/TR/xslt) equivalent for JSON? Something to allow me to do transformations on JSON like XSLT does to XML.
2009/10/24
['https://Stackoverflow.com/questions/1618038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147141/']
To say lack of tools suggest lack of need is just begging the question. The same could be applied to support for X or Y in Linux (Why bother developing quality drivers and/or games for such a minority OS? And why pay attention to an OS that big game and hardware companies don't develop for?). Probably the people who would need to use XSLT and JSON end up using a somewhat trivial workaround: Transforming JSON into XML. But that's not the optimal solution, is it? When you have a native JSON format and you want to edit it "wysywyg" in the browser, XSLT would be a more than adequate solution for the problem. Doing that with traditional javascript programming can become a pain in the arse. In fact, I have implemented a "stone-age" approach to XSLT, using substring parsing to interpret some basic commands for javascript, like calling a template, process children, etc. Certainly implementing a transformation engine with a JSON object is much easier than implementing a full-fledged XML parser to parse the XSLT. Problem is, that to use XML templates to transform a JSON object you need to parse the XML of the templates. To tranform a JSON object with XML (or HTML, or text or whatever) you need to think carefully about the syntax and what special characters you need to use to identify the transformation commands. Otherwise you'll end up having to design a parser for your own custom templating language. Having walked through that path, I can tell you that it's not pretty. Update (Nov 12, 2010): After a couple of weeks working on my parser, I've been able to optimize it. Templates are parsed beforehand and commands are stored as JSON objects. Transformation rules are also JSON objects, while the template code is a mix of HTML and a homebrew syntax similar to shell code. I've been able to transform a complex JSON document into HTML to make a document editor. The code is around 1K lines for the editor (it's for a private project so I can't share it) and around 990 lines for the JSON transformation code (includes iteration commands, simple comparisons, template calling, variable saving and evaluation). I plan to release it under a MIT license. Drop me a mail if you want to get involved.
For a working doodle/proof of concept of an approach to utilize pure JavaScript along with the familiar and declarative pattern behind XSLT's matching expressions and recursive templates, see <https://gist.github.com/brettz9/0e661b3093764f496e36> (A similar approach might be taken for JSON.) Note that the demo also relies on JavaScript 1.8 expression closures for convenience in expressing templates in Firefox (at least until the ES6 short form for methods may be implemented). Disclaimer: This is my own code.
1,618,038
Is there an [XSLT](http://www.w3.org/TR/xslt) equivalent for JSON? Something to allow me to do transformations on JSON like XSLT does to XML.
2009/10/24
['https://Stackoverflow.com/questions/1618038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147141/']
I've been really tired of the enormous amount of JavaScript templating engines out there, and all their inline HTML-templates, different markup styles, etc., and decided to [build a small library](https://github.com/WelcomWeb/Stapling) that enables XSLT formatting for JSON data structures. Not rocket science in any way -- it's just JSON parsed to XML and then formatted with a XSLT document. It's fast too, not as fast as JavaScript template engines in Chrome, but in most other browsers it's at least as fast as the JS engine alternative for larger data structures.
[CsvCruncher](https://github.com/OndraZizka/csv-cruncher/) ========================================================== Despite it's name does not suggest it, CsvCruncher can be efficiently used to read *tabular*\* JSON data and process them using SQL. `*` Tabular means that some part of the JSON tree is regular, i.e. one to many entries of same or similar structure. CsvCruncher turns this part of the tree into a SQL table, and then you have a full SQL syntax to query it. You may also load multiple JSON trees, and then have multiple tables to play with. You may also store the SQL result as a JSON (or CSV) and then process it again. This has served me way better than really complicated XSLT approach (despite it's a lot of fun when you really know it deeply). *Disclaimer: I am the developer of CsvCruncher.*
1,618,038
Is there an [XSLT](http://www.w3.org/TR/xslt) equivalent for JSON? Something to allow me to do transformations on JSON like XSLT does to XML.
2009/10/24
['https://Stackoverflow.com/questions/1618038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147141/']
As yet another new answer to an old question, I'd suggest a look at [DefiantJS](http://defiantjs.com/). It's not an XSLT *equivalent* for JSON, it ***is*** XSLT for JSON. The "Templating" section of the documentation includes this example: ``` <!-- Defiant template --> <script type="defiant/xsl-template"> <xsl:template name="books_template"> <xsl:for-each select="//movie"> <xsl:value-of select="title"/><br/> </xsl:for-each> </xsl:template> </script> <script type="text/javascript"> var data = { "movie": [ {"title": "The Usual Suspects"}, {"title": "Pulp Fiction"}, {"title": "Independence Day"} ] }, htm = Defiant.render('books_template', data); console.log(htm); // The Usual Suspects<br> // Pulp Fiction<br> // Independence Day<br> ```
[CsvCruncher](https://github.com/OndraZizka/csv-cruncher/) ========================================================== Despite it's name does not suggest it, CsvCruncher can be efficiently used to read *tabular*\* JSON data and process them using SQL. `*` Tabular means that some part of the JSON tree is regular, i.e. one to many entries of same or similar structure. CsvCruncher turns this part of the tree into a SQL table, and then you have a full SQL syntax to query it. You may also load multiple JSON trees, and then have multiple tables to play with. You may also store the SQL result as a JSON (or CSV) and then process it again. This has served me way better than really complicated XSLT approach (despite it's a lot of fun when you really know it deeply). *Disclaimer: I am the developer of CsvCruncher.*
1,618,038
Is there an [XSLT](http://www.w3.org/TR/xslt) equivalent for JSON? Something to allow me to do transformations on JSON like XSLT does to XML.
2009/10/24
['https://Stackoverflow.com/questions/1618038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147141/']
Try [JOLT](https://github.com/bazaarvoice/jolt). It is a JSON to JSON transformation library written in Java. It was created specifically because we did not want to play the "JSON -> XML -> XSLT -> XML -> JSON" game, and using a template for any sufficiently complex transform is unmaintainable.
it is very possible to convert JSON using XSLT: you need JSON2SAX deserializer and SAX2JSON serializer. Sample code in Java: <http://www.gerixsoft.com/blog/json/xslt4json>
1,618,038
Is there an [XSLT](http://www.w3.org/TR/xslt) equivalent for JSON? Something to allow me to do transformations on JSON like XSLT does to XML.
2009/10/24
['https://Stackoverflow.com/questions/1618038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147141/']
Interesting idea. Some searching on Google produced a few pages of interest, including: * an [outline](http://goessner.net/articles/jsont/) of how such a "jsonT" tool might be implemented, and [some downloads](http://goessner.net/download/prj/jsont/) * some [discussion of that implementation](http://ajaxian.com/archives/transforming-json) * a company which [may have implemented something suitable](https://www.p6r.com/articles/2008/05/06/xslt-and-xpath-for-json/) Hope this helps.
I am using Camel route umarshal(xmljson) -> to(xlst) -> marshal(xmljson). Efficient enough (though not 100% perfect), but simple, if you are already using Camel.
73,693,252
So I have a file from which I import another file, in the main file I need to use a variable that is in another file and is under DEF function and IF condition. But every time I get that there is no such variable. Code: First file: ``` from modules.proxy import * set_proxy() browser.get("website.com") ``` Second file: ``` def set_proxy(): if proxy_type == "type1": global browser browser = webdriver.Chrome(CHROME_DIR) ``` Result: " **name 'browser' is not defined** "
2022/09/12
['https://Stackoverflow.com/questions/73693252', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17238800/']
you should return the browser variable value in the end of the function like this: ``` return browser ``` now get it main file like this: ``` browser = set_proxy() browser.get("website.com") ```
You need to give a default value for `browser`. File 1: ```py browser: str = "" def test(): proxy: bool = True if proxy: global browser browser = "TEST" ``` File 2: ```py import file1 file1.test() print(file1.browser) file1.browser = "TEST2" print(file1.browser) ``` As expected the output are: ``` TEST TEST2 ```
42,826
I am integrating with a set of REST services exposed by our partner. The unit of integration is at the project level meaning that for each project created on our partners side of the fence they will expose a unique set of REST services. To be more clear, assume there are two projects - project1 and project2. The REST services available to access the project data would then be: /project1/search/getstuff?etc... /project1/analysis/getstuff?etc... /project1/cluster/getstuff?etc... /project2/search/getstuff?etc... /project2/analysis/getstuff?etc... /project2/cluster/getstuff?etc... My task is to wrap these services in a C# class to be used by our app developer. I want to make it simple for the app developer and am thinking of providing something like the following class. ``` class ProjectClient { SearchClient _searchclient; AnalysisClient _analysisclient; ClusterClient _clusterclient; string Project {get; set;} ProjectClient(string _project) { Project = _project; } } ``` SearchClient, AnalysisClient and ClusterClient are my classes to support the respective services shown above. The problem with this approach is that ProjectClient will need to provide public methods for each of the API's exposed by SearchClient, etc... ``` public void SearchGetStuff() { _searchclient.getStuff(); } ``` Any suggestions how I can architect this better?
2011/02/02
['https://softwareengineering.stackexchange.com/questions/42826', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/15370/']
Why not make it easy on your self - both decision-wise and implementation-wise - and just use one of the many frameworks that already exist to consume Web API's, like [RestSharp](http://restsharp.org/) or [Hammock](http://hammock.codeplex.com/).
an interface for each REST project, one class per interface, with a static factory in other words, the ProjectClient class as presented violates the single-responsibility principle (and verges on being a 'god' class). I suggest: ``` public static class ProjectClientFactory { public static ISearchClient MakeSearchClient(string projectUrl) { ... } public static IAnalysisClient MakeAnalysisClient(string projectUrl) { ... } public static IClusterClient MakeClusterClient(string projectUrl) { ... } } ```
35,089,135
I'm having a really bad issue here and I can't find anything about it online... this is my website: <http://top6.com> when you try to go to a page from FireFox, it shows you the page then redirects you back to the previous one... this only happens with FireFox and only happens if I'm not in a Private window. I tried to disable all plugins I have installed, didn't work. Checked htaccess, seems fine... Checkev for malware - none. Don't know what else to do... any help is highly appreciated...
2016/01/29
['https://Stackoverflow.com/questions/35089135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5261700/']
Use `array_chunk()` to split your array into arrays of size 4, then iterate row wise over data using `foreach`. ``` $links = array( array("Link 1", "link_href1"), array("Link 2", "link_href2"), array("Link 3", "link_href3"), array("Link 4", "link_href4"), array("Link 5", "link_href5"), array("Link 6", "link_href6"), array("Link 7", "link_href7"), array("Link 8", "link_href8"), array("Link 9", "link_href9"), ); $divsPerRow = 4; foreach(array_chunk($links,$divsPerRow) as $row) { echo "<div class=\"row\">\n"; foreach($row as $col) { list($label,$link) = $col; echo "\t<div class=\"col-xs-3 col-sm-6\">\n\t\t<a href=\"$link\">$label</a>\n\t</div>\n"; } echo "</div>\n"; } ``` Can even handle scenarios where `count($links)` is not a multipe of 4. Just set `$divsPerRow` to the desired value. Output: ``` <div class="row"> <div class="col-xs-3 col-sm-6"> <a href="link_href1">Link 1</a> </div> <div class="col-xs-3 col-sm-6"> <a href="link_href2">Link 2</a> </div> <div class="col-xs-3 col-sm-6"> <a href="link_href3">Link 3</a> </div> <div class="col-xs-3 col-sm-6"> <a href="link_href4">Link 4</a> </div> </div> <div class="row"> <div class="col-xs-3 col-sm-6"> <a href="link_href5">Link 5</a> </div> <div class="col-xs-3 col-sm-6"> <a href="link_href6">Link 6</a> </div> <div class="col-xs-3 col-sm-6"> <a href="link_href7">Link 7</a> </div> <div class="col-xs-3 col-sm-6"> <a href="link_href8">Link 8</a> </div> </div> <div class="row"> <div class="col-xs-3 col-sm-6"> <a href="link_href9">Link 9</a> </div> </div> ``` Live example can be found at: <http://sandbox.onlinephpfunctions.com/code/0075882e8abeda68ed1807b6d738714145b302e8>
It appears you are using a 12 column grid (probably bootstrap). If might be helpful to not only put things in the proper divs, but also have the ability to change the style using php variables. Here is a little code snip that might help you: ``` $colSize = 3; $colPrefix = "col-xs"; $numPerRow = 12/$colSize; for($ii = 0; $ii<count($links); $ii++) { if ($ii % $numPerRow == 0) { echo "<div class='row'>\n"; } echo "\t<div class='$colPrefix-$colSize'>\n"; echo "\t\t<a href='{$links[$ii][1]}'>{$links[$ii][0]}</a>\n"; echo "\t</div>\n"; if ($ii % $numPerRow == $numPerRow-1 || $ii == count($links)-1) { echo "</div>\n"; } } ``` Naturally, this would just be a starting point. If you wanted to hard-code some of the html classes instead of using PHP variables, it should be easy enough to change. The important part is that you can set `$numPerRow` to whatever you need and the code will work from there.
35,089,135
I'm having a really bad issue here and I can't find anything about it online... this is my website: <http://top6.com> when you try to go to a page from FireFox, it shows you the page then redirects you back to the previous one... this only happens with FireFox and only happens if I'm not in a Private window. I tried to disable all plugins I have installed, didn't work. Checked htaccess, seems fine... Checkev for malware - none. Don't know what else to do... any help is highly appreciated...
2016/01/29
['https://Stackoverflow.com/questions/35089135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5261700/']
Use `array_chunk()` to split your array into arrays of size 4, then iterate row wise over data using `foreach`. ``` $links = array( array("Link 1", "link_href1"), array("Link 2", "link_href2"), array("Link 3", "link_href3"), array("Link 4", "link_href4"), array("Link 5", "link_href5"), array("Link 6", "link_href6"), array("Link 7", "link_href7"), array("Link 8", "link_href8"), array("Link 9", "link_href9"), ); $divsPerRow = 4; foreach(array_chunk($links,$divsPerRow) as $row) { echo "<div class=\"row\">\n"; foreach($row as $col) { list($label,$link) = $col; echo "\t<div class=\"col-xs-3 col-sm-6\">\n\t\t<a href=\"$link\">$label</a>\n\t</div>\n"; } echo "</div>\n"; } ``` Can even handle scenarios where `count($links)` is not a multipe of 4. Just set `$divsPerRow` to the desired value. Output: ``` <div class="row"> <div class="col-xs-3 col-sm-6"> <a href="link_href1">Link 1</a> </div> <div class="col-xs-3 col-sm-6"> <a href="link_href2">Link 2</a> </div> <div class="col-xs-3 col-sm-6"> <a href="link_href3">Link 3</a> </div> <div class="col-xs-3 col-sm-6"> <a href="link_href4">Link 4</a> </div> </div> <div class="row"> <div class="col-xs-3 col-sm-6"> <a href="link_href5">Link 5</a> </div> <div class="col-xs-3 col-sm-6"> <a href="link_href6">Link 6</a> </div> <div class="col-xs-3 col-sm-6"> <a href="link_href7">Link 7</a> </div> <div class="col-xs-3 col-sm-6"> <a href="link_href8">Link 8</a> </div> </div> <div class="row"> <div class="col-xs-3 col-sm-6"> <a href="link_href9">Link 9</a> </div> </div> ``` Live example can be found at: <http://sandbox.onlinephpfunctions.com/code/0075882e8abeda68ed1807b6d738714145b302e8>
you can also try a foreach loop: ``` $i = 0; foreach ($links as $link) { if ($i == 0) { echo '<div class="row">'; } #... echo '<a href="' . $link[1] . '">' . $link[0] . '</a>'; #... ++$i; if ($i == 4) { echo '</div>'; $i = 0; } } if ($i != 0) { echo '</div>'; } ```
17,800,748
I am developing a chrome extension for company internal use, what i want to do is open folder in explorer (design folder at internal server) when someone add the project id in a textbox and click the button, ex: 'Y:\design\' + siteNumber Can i do it using javascript? Thanks! Nalinda
2013/07/23
['https://Stackoverflow.com/questions/17800748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1896674/']
No, javascript doesn't have access to the local machine's files/folders.
Sort of. You would need to write a stand-alone application in a native language (like C++ or Java) that could execute the opening of the folder, then have the Chrome extension communicate with it through the [NPAPI Plugin](http://developer.chrome.com/extensions/npapi.html). You *could* keep it all in Javascript by creating a Node.js program that executes the `open /path/to/folder` command (or your OS's equivalent). Either way, that native program would have to be pre-installed on the user's machine. But this doesn't seem like it should be a problem if it is an internal project.
25,150,148
can't find an answer to this anywhere. haven't used c++ for long. in this file, 512, 256, 4736, and 448 all red-underlined as error 'expecting type specifier' ``` // AttackSqrs.h #include <valarray> #include <vector> #include <unordered_map> #include <string> #include <iostream> class AttackSqrs { public: AttackSqrs(); ~AttackSqrs(); private: void init(); std::valarray<int> board(512); std::valarray<int> vrChessPieces(256); std::valarray<int> vrAttackSqrs(4736); std::valarray<int> vrNumAttackSqrsEachSqr(448); }; ``` but when i create this header file: ``` // diag.h #include <valarray> #include <vector> #include <unordered_map> #include <string> #include <iostream> void init(); std::valarray<int> board(512); std::valarray<int> vrChessPieces(256); std::valarray<int> vrAttackSqrs(4736); std::valarray<int> vrNumAttackSqrsEachSqr(448); ``` the errors go away. thanks in advance for any help.
2014/08/05
['https://Stackoverflow.com/questions/25150148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2808996/']
You don't initialize members that way. Use the initialization list of the `AttackSqrs` constructor: ``` class AttackSqrs { public: AttackSqrs(); ~AttackSqrs(); private: void init(); std::valarray<int> board; std::valarray<int> vrChessPieces; std::valarray<int> vrAttackSqrs; std::valarray<int> vrNumAttackSqrsEachSqr; }; // Then in a CPP file AttackSqrs::AttackSqrs() : board(512), vrChessPieces(256), vrAttackSqrs(4736), vrNumAttackSqrsEachSqr(448) {} ```
Your question is about vectors but you use valarray, which I haven't used before. I will answer for vectors. You need to set the size of the vectors in the constructor. header file ``` class AttackSqrs { public: AttackSqrs(); ~AttackSqrs(); private: std::vector<int> board(512); }; ``` cpp file ``` AttackSqrs::AttackSqrs() : board(512) { } ``` Alternatively, as the sizes are constant, you can use arrays. ``` class AttackSqrs { public: AttackSqrs(); ~AttackSqrs(); private: std::array<int, 512> board; // c++11 int board[512]; // pre-c++11 }; ```
25,150,148
can't find an answer to this anywhere. haven't used c++ for long. in this file, 512, 256, 4736, and 448 all red-underlined as error 'expecting type specifier' ``` // AttackSqrs.h #include <valarray> #include <vector> #include <unordered_map> #include <string> #include <iostream> class AttackSqrs { public: AttackSqrs(); ~AttackSqrs(); private: void init(); std::valarray<int> board(512); std::valarray<int> vrChessPieces(256); std::valarray<int> vrAttackSqrs(4736); std::valarray<int> vrNumAttackSqrsEachSqr(448); }; ``` but when i create this header file: ``` // diag.h #include <valarray> #include <vector> #include <unordered_map> #include <string> #include <iostream> void init(); std::valarray<int> board(512); std::valarray<int> vrChessPieces(256); std::valarray<int> vrAttackSqrs(4736); std::valarray<int> vrNumAttackSqrsEachSqr(448); ``` the errors go away. thanks in advance for any help.
2014/08/05
['https://Stackoverflow.com/questions/25150148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2808996/']
On the header file, you only declare the variable and their types. Any kind of object construction is implemented in the cpp file. **AttackSqrs.h** ``` class AttackSqrs { public: AttackSqrs(); ~AttackSqrs(); private: void init(); std::valarray<int> board; std::valarray<int> vrChessPieces; std::valarray<int> vrAttackSqrs; std::valarray<int> vrNumAttackSqrsEachSqr; }; ``` **AttackSqrs.cpp** ``` AttackSqrs::AttackSqrs() : board(512), vrChessPieces(256), vrAttackSqrs(4736), vrNumAttackSqrsEachSqr(448){ } ```
Your question is about vectors but you use valarray, which I haven't used before. I will answer for vectors. You need to set the size of the vectors in the constructor. header file ``` class AttackSqrs { public: AttackSqrs(); ~AttackSqrs(); private: std::vector<int> board(512); }; ``` cpp file ``` AttackSqrs::AttackSqrs() : board(512) { } ``` Alternatively, as the sizes are constant, you can use arrays. ``` class AttackSqrs { public: AttackSqrs(); ~AttackSqrs(); private: std::array<int, 512> board; // c++11 int board[512]; // pre-c++11 }; ```
8,671,537
This is a weired problem, I have implemented simple quick sort as follows.. ``` static void Main(string[] args) { List<int> unsorted = new List<int> { 1, 3, 5, 7, 9, 8, 6, 4, 2 }; List<int> sorted = quicksort(unsorted); Console.WriteLine(string.Join(",", sorted)); Console.ReadKey(); } private static List<T> quicksort<T>(List<T> arr) where T : IComparable<T> { List<T> loe = new List<T>(), gt = new List<T>(); if (arr.Count < 2) return arr; int pivot = arr.Count / 2; T pivot_val = arr[pivot]; arr.RemoveAt(pivot); foreach (T i in arr) { if (i.CompareTo(pivot_val) <= 0) loe.Add(i); else gt.Add(i); } List<T> resultSet = new List<T>(); resultSet.AddRange(quicksort(loe)); gt.Add(pivot_val); resultSet.AddRange(quicksort(gt)); return resultSet; } ``` Output is : 1,2,3,4,5,6,7,8,9 But When I use any negative number in the unsorted list there is a stackoverflow error, for example if List unsorted = new List { 1, 3, 5, 7, 9, 8, 6, 4, 2, **-1** }; Now there is a stackoverflow.. What's going on? Why this is not working ?
2011/12/29
['https://Stackoverflow.com/questions/8671537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/612936/']
Your algorithm has a bug. Consider the simplest input list { 1, -1 }. Let's step through your logic. 1. You first choose a pivot index, Count / 2, which is 1. 2. You then remove the pivot element at index 1 (-1) from the `arr` list. 3. Next you compare each remaining element in the `arr` list (there's just the 1 at index 0) with the pivot. 4. The 1 is greater than the pivot (-1) so you add it to the `gt` list. 5. Next you quicksort the `loe` list, which is empty. That sort returns an empty list, which you add to the result set. 6. You then add the pivot value to the end of the `gt` list, so the `gt` list now looks like this: { 1, -1 }. **Notice that this is the exact same list as you started with.** 7. You then attempt to quicksort the `gt` list. Since you are calling the quicksort routine with the same input, the same sequence of steps happens again, until the stack overflows. It seems the error in your logic is that you blindly add the pivot to the gt list without comparing it to anything. I'll leave it to you to figure out how to make it work. Edited to add: I'm assuming this is a homework assignment, but if it's not, I would highly recommend using .NET's built in `Sort()` method on `List<T>`. It has been highly optimized and heavily tested, and will most likely perform better than anything home-brewed. Why reinvent the wheel?
if you don't have a debugger try this... ``` foreach (T i in arr) { if (i.CompareTo(pivot_val) <= 0) { loe.Add(i); Console.WriteLine("loe.add " + i.ToString()); } else { gt.Add(i); Console.WriteLine("gt.add " + i.ToString()); } } ```
29,123,885
I am using WebApi in a ASP.Net web application. I have a method in the controller called `Delete` and I want to access to this method by using jQuery's AJAX method. Below is my code: ``` [Authorize] public int Delete(int proposalId) { // logic here... } ``` ```js $.ajax({ url: "/Controller/Proposal/" + proposalId, type: "Post", contentType: "application/json", success: function() { bootbox.alert("Proposal deleted successfully."); ReloadGrid(); }, error: function() { } }); ``` ```csharp RouteTable.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "controller/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); ``` ```xml <system.webServer> <modules runAllManagedModulesForAllRequests="true"></modules> </system.webServer> ``` The problem is that when I am using `POST` it is executing another method which starts as Post. Can anyone please help me with this?
2015/03/18
['https://Stackoverflow.com/questions/29123885', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1145184/']
Assuming this is accessing a REST API, you need to send a `DELETE` request by setting the appropriate `type` in your `$.ajax` call: ``` $.ajax({ url: "/Controller/Proposal/" + proposalId, type: "DELETE", // <- Change here contentType: "application/json", success: function() { bootbox.alert("Proposal deleted successfully."); ReloadGrid(); }, error: function() { } }); ```
If you must use a custom method for deletion for example, you can always rely on setting HTTP attributes -- like so: ``` [HttpDelete] [Route("api/Proposal")] public IHttpActionResult Proposal(long id){ ... } ```