prompt
stringlengths
48
2.37k
chosen
stringlengths
7
4.28k
rejected
stringlengths
11
4.44k
Question: I was once asked the following question by a student I was tutoring; and I was stumped by it: When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground? * One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case. * One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere. * It's because of the nature of the force. It's independent of the motion of the stone. I prefer the last explanation - but is it true? And is this the best explanation? Answer:
I think its because both halves of a projectile's trajectory are symmetric in every aspect. The projectile going from its apex position to the ground is just the time reversed version of the projectile going from its initial position to the apex position.
**Assuming that the only forces acting on the stone are the initial force exerted by the hand on the stone AND the force of gravity**, we have the following situation: Immediately after throwing, the stone has a kinetic energy in the x-direction that never changes (**conservation of energy**) and the stone has a kinetic energy in the y-direction that is constantly being depleted by gravity as it rises to its apex. Once the stone is at its apex (vertical kinetic energy = 0), gravity **works** to restore all of the stone's original vertical kinetic energy as it falls back to its original height. So, the x-direction **kinetic energy** remained constant throughout the flight and the y-direction **total energy (kinetic + potential)** remained constant throughout the flight, independent of each other. This combination causes the symmetry of the situation. If air resistance and terminal velocity are introduced into the problem, the character of the problem is completely changed. Even a very simple situation as the one you described can become very complex and confusing to most people. Most people would be stymied by the complexity of the math involved even in this simple situation, let alone the complexity of putting a probe into orbit about Earth.
Question: How do I apply css styles to HTML tags within a class at once instead of repeating the class name each time. ``` .container h1,.container p,.container a,.container ol,.container ul,.container li, .container fieldset,.container form,.container label,.container legend, .container table { some css rules here } ``` how do I reduce repetition of the class name? Answer:
Use [LESS](http://lesscss.org/). It would come out looking like this. ``` .container { h1, p, a, ol, ul, li, fieldset, form, label, legend, table { your styles here } } ``` Otherwise, you're SOL. Sorry.
You cannot reduce the current selector of yours as far as pure CSS goes. You might want to take a look at [LESS](http://lesscss.org/) or [SASS](http://sass-lang.com/) for doing that. Also, I just read your selector, seems like *you are covering almost every tag*, so if you are looking to target few properties to each tag, the best you can do with CSS is to use a `*` selector *(Universal selector)* which will match any type of element nested under an element having a `class` of `.container` ``` .container * { /* Styles goes here */ } ``` Apart from the above, some properties are inherited by few child elements from their parent such as `font-size`, `color`, `font-family` etc. So you don't need to write those for each, because I saw you using `.container ul, .container li` which didn't make much sense to me.
Question: How can I implement a hook in my template file that will change the label of a field for the "group" content type from "author" to "created by"? ![screenshot of author field](https://i.stack.imgur.com/jDhMv.png) Answer:
To rename the label of a field add the preprocess function [template\_preprocess\_node](http://api.drupal.org/api/drupal/modules--node--node.module/function/template_preprocess_node/7) to your *template.php* file: ``` function *YOUR THEME*_preprocess_node(&$vars){ //Supposing that your content type name is "group" if($vars['type'] == 'group'){ //Supposing that your field name is "field_txt_group" $vars['content']['field_txt_author']['#title'] = 'created by'; } } ```
I'll take a guess that there are a few different ways you can do this. 1. Use jQuery to target the element and use text replacement. You could so something like: ``` $("#my-element").each(function () { var s=$(this).text(); //get text $(this).text(s.replace('Author', 'created by')); //set the text to the replaced version }); ``` Of course you will need to add on Drupal specific jQuery code depending on what version of Drupal you are using (6 or 7). See: [JavaScript in Drupal 5 and Drupal 6](http://drupal.org/node/121997) and [Managing JavaScript in Drupal 7](http://drupal.org/node/756722). 1. Try the [String Overrides](http://drupal.org/project/stringoverrides) module 2. Write a template pre-process function (template.php in your theme folder) to replace that text.
Question: How can I implement a hook in my template file that will change the label of a field for the "group" content type from "author" to "created by"? ![screenshot of author field](https://i.stack.imgur.com/jDhMv.png) Answer:
To rename the label of a field add the preprocess function [template\_preprocess\_node](http://api.drupal.org/api/drupal/modules--node--node.module/function/template_preprocess_node/7) to your *template.php* file: ``` function *YOUR THEME*_preprocess_node(&$vars){ //Supposing that your content type name is "group" if($vars['type'] == 'group'){ //Supposing that your field name is "field_txt_group" $vars['content']['field_txt_author']['#title'] = 'created by'; } } ```
You can also change the label from a field preprocess ``` function THEMENAME_preprocess_field(&$variables, $hook) { $field_name = $variables['element']['#field_name']; $view_mode = $variables['element']['#view_mode']; switch ($field_name) { case 'YOUR_FIELD_NAME': $variables['label'] = t('FIELD LABEL EVERYWHERE'); // Possible to restrict by view mode if ($view_mode == 'teaser') { $variables['label'] = t('TEASER LABEL HERE'); } break; // Duplicate for other fields case 'OTHER_FIELD_MACHINE_NAMES': // ...code break; } } ```
Question: I have a class Application with EmbeddedId and second column in embbbedID is forgein key and having many to one relationship with offer. ``` @Entity public class Application implements Serializable{ private Integer id; @EmbeddedId private MyKey mykey; private String resume; @Enumerated(EnumType.STRING) @NotNull private ApplicationStatus applicationStatus; @Embeddable public class MyKey implements Serializable{ private static final long serialVersionUID = 1L; @NotNull private String emailId; @ManyToOne(fetch = FetchType.LAZY) @NotNull private Offer offer; ``` in Offer class mapping is done on jobTitle. ``` @Repository interface ApplicationRepository extends JpaRepository <Application,MyKey> ``` { ``` List<Application> findAllByMyKey_Offer(String jobTitle); } ``` Trying this but getting no success... I want to fetch All application regarding a specific jobTitle. What shud be my method name in ApplicationRepository class. Answer:
Your methode name is wrong, the right one is `findAllByMykey_Offer` or `findAllByMykeyOffer`, as your field is named mykey. As mentionned in the documentation <https://docs.spring.io/spring-data/jpa/docs/2.1.0.RELEASE/reference/html/> using `List<Application> findAllByMykey_Offer(String jobTitle);` is better than `List<Application> findAllByMykeyOffer(String jobTitle);`
With composite key, your field name should include name of the field of embedded id. In you case it would be like this (I haven't tested it) ``` List<Application> findAllByMykeyOffer(String jobTitle); ``` Notice that `k` is lower-case here, because your field in class `Application` is named `mykey`, not `myKey`
Question: I want to create a list with my database field values. There are 2 columns, name and surname. I want to create a list that stores all names in name column in a field and then add to my DTO. Is this possible? Answer:
**Steps you can follow**: - * First you need to have a `List<String>` that will store all your names. Declare it like this: - ``` List<String> nameList = new ArrayList<String>(); ``` * Now, you have all the records fetched and stored in `ResultSet`. So I assume that you can iterate over `ResultSet` and get each `values` from it. You need to use `ResultSet#getString` to fetch the `name`. * Now, each time you fetch one record, get the `name` field and add it to your list. ``` while(resultSet.next()) { nameList.add(resultSet.getString("name")); } ``` * Now, since you haven't given enough information about your `DTO`, so that part you need to find out, how to add this `ArrayList` to your `DTO`. * The above `list` only contains `name` and not `surname` as you wanted only `name`. But if you want both, you need to create a custom DTO `(FullName)`, that contains `name` and `surname` as fields. And instantiate it from every `ResultSet` and add it to the `List<FullName>`
It is. What have you tried ? To access the database, you need to [use JDBC](http://docs.oracle.com/javase/tutorial/jdbc/basics/index.html) and execute a query, giving you a `ResultSet`. I would create an class called `FullName` with 2 String fields `name` and `surname`. Just populate these in a loop using ``` rs.getString("NAME"); // column name rs.getString("SURNAME"); ``` e.g. ``` List<FullName> fullnames = new ArrayList<FullName>(); while (rs.next()) { fullnames.add(new FullName(rs)); } ``` Note that I'm populating the object via the `ResultSet` object directly. You may choose instead to implement a constructor taking the 2 name fields. Note also that I'm creating a `Fullname` object. So the firstname/surname are kept separate and you have the freedom to add initials etc. later. You may prefer to rename this `Person` and that will give you the freedom to add additional attributes going forwards.
Question: I want to create a list with my database field values. There are 2 columns, name and surname. I want to create a list that stores all names in name column in a field and then add to my DTO. Is this possible? Answer:
It is. What have you tried ? To access the database, you need to [use JDBC](http://docs.oracle.com/javase/tutorial/jdbc/basics/index.html) and execute a query, giving you a `ResultSet`. I would create an class called `FullName` with 2 String fields `name` and `surname`. Just populate these in a loop using ``` rs.getString("NAME"); // column name rs.getString("SURNAME"); ``` e.g. ``` List<FullName> fullnames = new ArrayList<FullName>(); while (rs.next()) { fullnames.add(new FullName(rs)); } ``` Note that I'm populating the object via the `ResultSet` object directly. You may choose instead to implement a constructor taking the 2 name fields. Note also that I'm creating a `Fullname` object. So the firstname/surname are kept separate and you have the freedom to add initials etc. later. You may prefer to rename this `Person` and that will give you the freedom to add additional attributes going forwards.
What worked for me is: ``` ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); ArrayList<String> resultList= new ArrayList<>(columnCount); while (rs.next()) { int i = 1; while(i <= columnCount) { resultList.add(rs.getString(i++)); } } return resultList; ```
Question: I want to create a list with my database field values. There are 2 columns, name and surname. I want to create a list that stores all names in name column in a field and then add to my DTO. Is this possible? Answer:
**Steps you can follow**: - * First you need to have a `List<String>` that will store all your names. Declare it like this: - ``` List<String> nameList = new ArrayList<String>(); ``` * Now, you have all the records fetched and stored in `ResultSet`. So I assume that you can iterate over `ResultSet` and get each `values` from it. You need to use `ResultSet#getString` to fetch the `name`. * Now, each time you fetch one record, get the `name` field and add it to your list. ``` while(resultSet.next()) { nameList.add(resultSet.getString("name")); } ``` * Now, since you haven't given enough information about your `DTO`, so that part you need to find out, how to add this `ArrayList` to your `DTO`. * The above `list` only contains `name` and not `surname` as you wanted only `name`. But if you want both, you need to create a custom DTO `(FullName)`, that contains `name` and `surname` as fields. And instantiate it from every `ResultSet` and add it to the `List<FullName>`
JDBC unfortunately doesn't offer any ways to conveniently do this in a one-liner. But there are other APIs, such as [jOOQ](http://www.jooq.org) (disclaimer: I work for the company behind jOOQ): ``` List<DTO> list = DSL.using(connection) .fetch("SELECT first_name, last_name FROM table") .into(DTO.class); ``` Or [Spring JDBC](http://projects.spring.io/spring-data/) ``` List<DTO> list = new JdbcTemplate(new SingleConnectionDataSource(connection, true)) .query("SELECT first_name, last_name FROM table", (rs, rowNum) -> new DTO(rs.getString(1), rs.getString(2)); ``` Or [Apache DbUtils](http://commons.apache.org/proper/commons-dbutils/): ``` List<DTO> list = new QueryRunner() .query(connection, "SELECT first_name, last_name FROM table", new ArrayListHandler()) .stream() .map(array -> new DTO((String) array[0], (String) array[1])) .collect(Collectors.toList()); ``` I've used Java 8 for the Spring JDBC / Apache DbUtils examples, but it can be done with older versions of Java as well.
Question: I want to create a list with my database field values. There are 2 columns, name and surname. I want to create a list that stores all names in name column in a field and then add to my DTO. Is this possible? Answer:
**Steps you can follow**: - * First you need to have a `List<String>` that will store all your names. Declare it like this: - ``` List<String> nameList = new ArrayList<String>(); ``` * Now, you have all the records fetched and stored in `ResultSet`. So I assume that you can iterate over `ResultSet` and get each `values` from it. You need to use `ResultSet#getString` to fetch the `name`. * Now, each time you fetch one record, get the `name` field and add it to your list. ``` while(resultSet.next()) { nameList.add(resultSet.getString("name")); } ``` * Now, since you haven't given enough information about your `DTO`, so that part you need to find out, how to add this `ArrayList` to your `DTO`. * The above `list` only contains `name` and not `surname` as you wanted only `name`. But if you want both, you need to create a custom DTO `(FullName)`, that contains `name` and `surname` as fields. And instantiate it from every `ResultSet` and add it to the `List<FullName>`
What worked for me is: ``` ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); ArrayList<String> resultList= new ArrayList<>(columnCount); while (rs.next()) { int i = 1; while(i <= columnCount) { resultList.add(rs.getString(i++)); } } return resultList; ```
Question: I want to create a list with my database field values. There are 2 columns, name and surname. I want to create a list that stores all names in name column in a field and then add to my DTO. Is this possible? Answer:
JDBC unfortunately doesn't offer any ways to conveniently do this in a one-liner. But there are other APIs, such as [jOOQ](http://www.jooq.org) (disclaimer: I work for the company behind jOOQ): ``` List<DTO> list = DSL.using(connection) .fetch("SELECT first_name, last_name FROM table") .into(DTO.class); ``` Or [Spring JDBC](http://projects.spring.io/spring-data/) ``` List<DTO> list = new JdbcTemplate(new SingleConnectionDataSource(connection, true)) .query("SELECT first_name, last_name FROM table", (rs, rowNum) -> new DTO(rs.getString(1), rs.getString(2)); ``` Or [Apache DbUtils](http://commons.apache.org/proper/commons-dbutils/): ``` List<DTO> list = new QueryRunner() .query(connection, "SELECT first_name, last_name FROM table", new ArrayListHandler()) .stream() .map(array -> new DTO((String) array[0], (String) array[1])) .collect(Collectors.toList()); ``` I've used Java 8 for the Spring JDBC / Apache DbUtils examples, but it can be done with older versions of Java as well.
What worked for me is: ``` ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); ArrayList<String> resultList= new ArrayList<>(columnCount); while (rs.next()) { int i = 1; while(i <= columnCount) { resultList.add(rs.getString(i++)); } } return resultList; ```
Question: I want for the click on the item menu, this item will change the icon. Selector for the item: button\_add\_to\_wishlist.xml ``` <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="false" android:drawable="@drawable/ic_add_fav" /> <item android:state_checked="true" android:drawable="@drawable/ic_add_fav_fill" /> ``` Menu ``` <item android:id="@+id/add_to_wishlist" android:title="@string/book_btn_text_add_to_wishlist" android:icon="@drawable/button_add_to_wishlist" android:checkable="true" app:showAsAction="always"/> ``` Answer:
There is no command to tell Amazon S3 to archive a specific object to Amazon Glacier. Instead, [Lifecycle Rules](https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lifecycle-mgmt.html) are used to identify objects. The [Lifecycle Configuration Elements](https://docs.aws.amazon.com/AmazonS3/latest/dev/intro-lifecycle-rules.html) documentation shows each rule consisting of: * **Rule metadata** that include a rule ID, and status indicating whether the rule is enabled or disabled. If a rule is disabled, Amazon S3 will not perform any actions specified in the rule. * **Prefix** identifying objects by the key prefix to which the rule applies. * One or more **transition/expiration actions with a date or a time period** in the object's lifetime when you want Amazon S3 to perform the specified action. The only way to identify *which* objects are transitioned is via the **prefix** parameter. Therefore, you would need to specify a separate rule for each object. (The prefix can include the full object name.) However, there is a **limit of 1000 rules** per lifecycle configuration. Yes, you could move objects one-at-a-time to Amazon Glacier, but this would actually involve uploading archives to Glacier rather than 'moving' them from S3. Also, be careful -- there are **higher 'per request' charges for Glacier than S3** that might actually cost you more than the savings you'll gain in storage costs. In the meantime, consider using [Amazon S3 Standard - Infrequent Access storage class](https://aws.amazon.com/s3/storage-classes/), which can **save around 50% of S3 storage costs** for infrequently-accessed data.
You can programmatically archive a specific object on S3 to Glacier using [Lifecycle Rules](https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lifecycle-mgmt.html) (with a prefix of the exact object you wish to archive). There is a [PUT lifecycle](http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlifecycle.html) API. This API replaces the *entire* lifecycle configuration, so if you have rules outside of this process you will need to add them to each lifecycle you upload. If you want to archive specific files, you can either: * For each file, create a lifecycle with one rule, wait until the file has transferred, then do the same for the next file * Create a lifecycle configuration with one rule per file The second will finish faster (as you do not need to wait between files), but requires that you know all the files you want to archive in advance. There is a limit of 1,000 rules per lifecycle configuration, so if you have an awful lot of files that you want to archive, you will need to split them into separate lifecycle configurations.
Question: In java exceptions have at least these four constructors: ``` Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) ``` If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor How can you achieve the same thing in scala? so far now I saw [this article](https://lizdouglass.wordpress.com/2010/12/15/scala-multiple-constructors/) and this [SO answer](https://stackoverflow.com/a/3300046/47633), but I suspect there must be an easier way to achieve such a common thing Answer:
well, this is the best I've found so far ``` class MissingConfigurationException private(ex: RuntimeException) extends RuntimeException(ex) { def this(message:String) = this(new RuntimeException(message)) def this(message:String, throwable: Throwable) = this(new RuntimeException(message, throwable)) } object MissingConfigurationException { def apply(message:String) = new MissingConfigurationException(message) def apply(message:String, throwable: Throwable) = new MissingConfigurationException(message, throwable) } ``` this way you may use the "new MissingConfigurationException" or the apply method from the companion object Anyway, I'm still surprised that there isn't a simpler way to achieve it
Here is a similar approach to the one of @roman-borisov but more typesafe. ``` case class ShortException(message: String = "", cause: Option[Throwable] = None) extends Exception(message) { cause.foreach(initCause) } ``` Then, you can create Exceptions in the Java manner: ``` throw ShortException() throw ShortException(message) throw ShortException(message, Some(cause)) throw ShortException(cause = Some(cause)) ```
Question: In java exceptions have at least these four constructors: ``` Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) ``` If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor How can you achieve the same thing in scala? so far now I saw [this article](https://lizdouglass.wordpress.com/2010/12/15/scala-multiple-constructors/) and this [SO answer](https://stackoverflow.com/a/3300046/47633), but I suspect there must be an easier way to achieve such a common thing Answer:
You can use `Throwable.initCause`. ``` class MyException (message: String, cause: Throwable) extends RuntimeException(message) { if (cause != null) initCause(cause) def this(message: String) = this(message, null) } ```
Scala pattern matching in try/catch blocks works on interfaces. My solution is to use an interface for the exception name then use separate class instances. ``` trait MyException extends RuntimeException class MyExceptionEmpty() extends RuntimeException with MyException class MyExceptionStr(msg: String) extends RuntimeException(msg) with MyException class MyExceptionEx(t: Throwable) extends RuntimeException(t) with MyException object MyException { def apply(): MyException = new MyExceptionEmpty() def apply(msg: String): MyException = new MyExceptionStr(msg) def apply(t: Throwable): MyException = new MyExceptionEx(t) } class MyClass { try { throw MyException("oops") } catch { case e: MyException => println(e.getMessage) case _: Throwable => println("nope") } } ``` Instantiating MyClass will output "oops".
Question: In java exceptions have at least these four constructors: ``` Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) ``` If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor How can you achieve the same thing in scala? so far now I saw [this article](https://lizdouglass.wordpress.com/2010/12/15/scala-multiple-constructors/) and this [SO answer](https://stackoverflow.com/a/3300046/47633), but I suspect there must be an easier way to achieve such a common thing Answer:
well, this is the best I've found so far ``` class MissingConfigurationException private(ex: RuntimeException) extends RuntimeException(ex) { def this(message:String) = this(new RuntimeException(message)) def this(message:String, throwable: Throwable) = this(new RuntimeException(message, throwable)) } object MissingConfigurationException { def apply(message:String) = new MissingConfigurationException(message) def apply(message:String, throwable: Throwable) = new MissingConfigurationException(message, throwable) } ``` this way you may use the "new MissingConfigurationException" or the apply method from the companion object Anyway, I'm still surprised that there isn't a simpler way to achieve it
You can use `Throwable.initCause`. ``` class MyException (message: String, cause: Throwable) extends RuntimeException(message) { if (cause != null) initCause(cause) def this(message: String) = this(message, null) } ```
Question: In java exceptions have at least these four constructors: ``` Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) ``` If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor How can you achieve the same thing in scala? so far now I saw [this article](https://lizdouglass.wordpress.com/2010/12/15/scala-multiple-constructors/) and this [SO answer](https://stackoverflow.com/a/3300046/47633), but I suspect there must be an easier way to achieve such a common thing Answer:
You can use `Throwable.initCause`. ``` class MyException (message: String, cause: Throwable) extends RuntimeException(message) { if (cause != null) initCause(cause) def this(message: String) = this(message, null) } ```
Here is a similar approach to the one of @roman-borisov but more typesafe. ``` case class ShortException(message: String = "", cause: Option[Throwable] = None) extends Exception(message) { cause.foreach(initCause) } ``` Then, you can create Exceptions in the Java manner: ``` throw ShortException() throw ShortException(message) throw ShortException(message, Some(cause)) throw ShortException(cause = Some(cause)) ```
Question: In java exceptions have at least these four constructors: ``` Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) ``` If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor How can you achieve the same thing in scala? so far now I saw [this article](https://lizdouglass.wordpress.com/2010/12/15/scala-multiple-constructors/) and this [SO answer](https://stackoverflow.com/a/3300046/47633), but I suspect there must be an easier way to achieve such a common thing Answer:
well, this is the best I've found so far ``` class MissingConfigurationException private(ex: RuntimeException) extends RuntimeException(ex) { def this(message:String) = this(new RuntimeException(message)) def this(message:String, throwable: Throwable) = this(new RuntimeException(message, throwable)) } object MissingConfigurationException { def apply(message:String) = new MissingConfigurationException(message) def apply(message:String, throwable: Throwable) = new MissingConfigurationException(message, throwable) } ``` this way you may use the "new MissingConfigurationException" or the apply method from the companion object Anyway, I'm still surprised that there isn't a simpler way to achieve it
Scala pattern matching in try/catch blocks works on interfaces. My solution is to use an interface for the exception name then use separate class instances. ``` trait MyException extends RuntimeException class MyExceptionEmpty() extends RuntimeException with MyException class MyExceptionStr(msg: String) extends RuntimeException(msg) with MyException class MyExceptionEx(t: Throwable) extends RuntimeException(t) with MyException object MyException { def apply(): MyException = new MyExceptionEmpty() def apply(msg: String): MyException = new MyExceptionStr(msg) def apply(t: Throwable): MyException = new MyExceptionEx(t) } class MyClass { try { throw MyException("oops") } catch { case e: MyException => println(e.getMessage) case _: Throwable => println("nope") } } ``` Instantiating MyClass will output "oops".
Question: In java exceptions have at least these four constructors: ``` Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) ``` If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor How can you achieve the same thing in scala? so far now I saw [this article](https://lizdouglass.wordpress.com/2010/12/15/scala-multiple-constructors/) and this [SO answer](https://stackoverflow.com/a/3300046/47633), but I suspect there must be an easier way to achieve such a common thing Answer:
Default value for `cause` is null. And for `message` it is either `cause.toString()` or null: ``` val e1 = new RuntimeException() e.getCause // res1: java.lang.Throwable = null e.getMessage //res2: java.lang.String = null val cause = new RuntimeException("cause msg") val e2 = new RuntimeException(cause) e.getMessage() //res3: String = java.lang.RuntimeException: cause msg ``` So you can just use default values: ``` class MyException(message: String = null, cause: Throwable = null) extends RuntimeException(MyException.defaultMessage(message, cause), cause) object MyException { def defaultMessage(message: String, cause: Throwable) = if (message != null) message else if (cause != null) cause.toString() else null } // usage: new MyException(cause = myCause) // res0: MyException = MyException: java.lang.RuntimeException: myCause msg ```
Scala pattern matching in try/catch blocks works on interfaces. My solution is to use an interface for the exception name then use separate class instances. ``` trait MyException extends RuntimeException class MyExceptionEmpty() extends RuntimeException with MyException class MyExceptionStr(msg: String) extends RuntimeException(msg) with MyException class MyExceptionEx(t: Throwable) extends RuntimeException(t) with MyException object MyException { def apply(): MyException = new MyExceptionEmpty() def apply(msg: String): MyException = new MyExceptionStr(msg) def apply(t: Throwable): MyException = new MyExceptionEx(t) } class MyClass { try { throw MyException("oops") } catch { case e: MyException => println(e.getMessage) case _: Throwable => println("nope") } } ``` Instantiating MyClass will output "oops".
Question: In java exceptions have at least these four constructors: ``` Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) ``` If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor How can you achieve the same thing in scala? so far now I saw [this article](https://lizdouglass.wordpress.com/2010/12/15/scala-multiple-constructors/) and this [SO answer](https://stackoverflow.com/a/3300046/47633), but I suspect there must be an easier way to achieve such a common thing Answer:
Default value for `cause` is null. And for `message` it is either `cause.toString()` or null: ``` val e1 = new RuntimeException() e.getCause // res1: java.lang.Throwable = null e.getMessage //res2: java.lang.String = null val cause = new RuntimeException("cause msg") val e2 = new RuntimeException(cause) e.getMessage() //res3: String = java.lang.RuntimeException: cause msg ``` So you can just use default values: ``` class MyException(message: String = null, cause: Throwable = null) extends RuntimeException(MyException.defaultMessage(message, cause), cause) object MyException { def defaultMessage(message: String, cause: Throwable) = if (message != null) message else if (cause != null) cause.toString() else null } // usage: new MyException(cause = myCause) // res0: MyException = MyException: java.lang.RuntimeException: myCause msg ```
You can use `Throwable.initCause`. ``` class MyException (message: String, cause: Throwable) extends RuntimeException(message) { if (cause != null) initCause(cause) def this(message: String) = this(message, null) } ```
Question: Attempting to do something very simple - compile basic win 32 c programs through windows cmd. This is something I should be able to do myself, but I am just so stuck here.. I keep stumbling into weird problems, vague errors. I dunno whether I should go into details. Using tcc ( tiny c compiler) 1. One simple hellowin.c example from a book required winmm.lib. How do I import it ? can someone give me the exact command for gcc/tcc /any command line compiler for windows(except cygwin) ? I did try various options after reading help , but it kept giving me a can't find stupid error. 2. a sample from platform sdk that I tried to compile gave a - winnt.h "( expected" error. this after a #define \_M\_IX86 . what it means ? 3. any general guide for compiling c programs for windows(win32 api) through command line ? . explaining what all should be #defined ..etc.. I have googled a lot but most of the c compiling guidelines for win32 programs focus on vb .I wanna do it manually , on the command line. Thanks Answer:
If I create a new project using Visual Studio it #defines the following preprocessor symbols using compiler command-line options: * `WIN32` * `_WINDOWS` * one of either `_DEBUG` or `NDEBUG` * `UNICODE` and `_UNICODE` (although the Windows headers and libraries also support non-Unicode-enabled applications, if your compiler doesn't support Unicode). <http://bellard.org/tcc/tcc-doc.html> says "For usage on Windows, see also tcc-win32.txt".
Sounds like the kind of compiler that might be looking for INCLUDE and LIB paths in the environment. If you do "set" on the command line and don't see those vars listed, you could try setting them to the paths your compiler is using. Not sure where you would have installed this tcc tool, but look for directories named 'include' and 'lib' and try assigning those to the aforementioned environment variables.
Question: Attempting to do something very simple - compile basic win 32 c programs through windows cmd. This is something I should be able to do myself, but I am just so stuck here.. I keep stumbling into weird problems, vague errors. I dunno whether I should go into details. Using tcc ( tiny c compiler) 1. One simple hellowin.c example from a book required winmm.lib. How do I import it ? can someone give me the exact command for gcc/tcc /any command line compiler for windows(except cygwin) ? I did try various options after reading help , but it kept giving me a can't find stupid error. 2. a sample from platform sdk that I tried to compile gave a - winnt.h "( expected" error. this after a #define \_M\_IX86 . what it means ? 3. any general guide for compiling c programs for windows(win32 api) through command line ? . explaining what all should be #defined ..etc.. I have googled a lot but most of the c compiling guidelines for win32 programs focus on vb .I wanna do it manually , on the command line. Thanks Answer:
Download the Windows PlatformSDK and it comes with its own command line compiler. It creates a shortcut Start->Programs->... to open a command prompt for either 32bit or 64bit. Select the 32bit variant and you get a fully initialized command prompt with compiler in your PATH and all INCLUDE, LIB and LIBPATH set. cmd> cl hello.c This should give you hello.exe. For more help on compiler "cl /?", for linker "link /?"
Sounds like the kind of compiler that might be looking for INCLUDE and LIB paths in the environment. If you do "set" on the command line and don't see those vars listed, you could try setting them to the paths your compiler is using. Not sure where you would have installed this tcc tool, but look for directories named 'include' and 'lib' and try assigning those to the aforementioned environment variables.
Question: Attempting to do something very simple - compile basic win 32 c programs through windows cmd. This is something I should be able to do myself, but I am just so stuck here.. I keep stumbling into weird problems, vague errors. I dunno whether I should go into details. Using tcc ( tiny c compiler) 1. One simple hellowin.c example from a book required winmm.lib. How do I import it ? can someone give me the exact command for gcc/tcc /any command line compiler for windows(except cygwin) ? I did try various options after reading help , but it kept giving me a can't find stupid error. 2. a sample from platform sdk that I tried to compile gave a - winnt.h "( expected" error. this after a #define \_M\_IX86 . what it means ? 3. any general guide for compiling c programs for windows(win32 api) through command line ? . explaining what all should be #defined ..etc.. I have googled a lot but most of the c compiling guidelines for win32 programs focus on vb .I wanna do it manually , on the command line. Thanks Answer:
If I create a new project using Visual Studio it #defines the following preprocessor symbols using compiler command-line options: * `WIN32` * `_WINDOWS` * one of either `_DEBUG` or `NDEBUG` * `UNICODE` and `_UNICODE` (although the Windows headers and libraries also support non-Unicode-enabled applications, if your compiler doesn't support Unicode). <http://bellard.org/tcc/tcc-doc.html> says "For usage on Windows, see also tcc-win32.txt".
You can try gcc from [equation.com](http://www.equation.com/). It's a mingw wrapped compiler, but you don't have to worry about mingw: just download, install and use. There's no IDE either. The download page is at [<http://www.equation.com/servlet/equation.cmd?fa=fortran>](http://www.equation.com/servlet/equation.cmd?fa=fortran).
Question: Attempting to do something very simple - compile basic win 32 c programs through windows cmd. This is something I should be able to do myself, but I am just so stuck here.. I keep stumbling into weird problems, vague errors. I dunno whether I should go into details. Using tcc ( tiny c compiler) 1. One simple hellowin.c example from a book required winmm.lib. How do I import it ? can someone give me the exact command for gcc/tcc /any command line compiler for windows(except cygwin) ? I did try various options after reading help , but it kept giving me a can't find stupid error. 2. a sample from platform sdk that I tried to compile gave a - winnt.h "( expected" error. this after a #define \_M\_IX86 . what it means ? 3. any general guide for compiling c programs for windows(win32 api) through command line ? . explaining what all should be #defined ..etc.. I have googled a lot but most of the c compiling guidelines for win32 programs focus on vb .I wanna do it manually , on the command line. Thanks Answer:
Download the Windows PlatformSDK and it comes with its own command line compiler. It creates a shortcut Start->Programs->... to open a command prompt for either 32bit or 64bit. Select the 32bit variant and you get a fully initialized command prompt with compiler in your PATH and all INCLUDE, LIB and LIBPATH set. cmd> cl hello.c This should give you hello.exe. For more help on compiler "cl /?", for linker "link /?"
You can try gcc from [equation.com](http://www.equation.com/). It's a mingw wrapped compiler, but you don't have to worry about mingw: just download, install and use. There's no IDE either. The download page is at [<http://www.equation.com/servlet/equation.cmd?fa=fortran>](http://www.equation.com/servlet/equation.cmd?fa=fortran).
Question: First of all: I want to use Java EE not Spring! I have some self defined annotations which are acting as interceptor bindings. I use the annotations on my methods like this: ```java @Logged @Secured @RequestParsed @ResultHandled public void doSomething() { // ... } ``` For some methods I want to use a single of these annotations but most methods I want to use like this: ```java @FunctionMethod public void doSomething() { // ... } ``` Can I bundle these set of annotations to a single one? I cannot write the code in a single interceptor because for some methods I want to use them seperately too. I know that there is a @Stereotype definition possible, but as far as I know, this is used to define a whole class not a single method. Answer:
The `position: absolute;` and the `right:-100px;` is pushing your element past the right edge of the viewport. Floating does not affect absolutely positioned elements. If you want the element to be `100px` away from the edge, make that a positive `100px`. Or, if you want it right up against the edge, make it `0`. If you truly want to float it, remove the absolute positioning. Hopefully I understood the question, and I hope this helps! Edit: I re-read the question and think an even better solution would be to add `position: relative;` to the wrapper. Right now, your absolutely position element is positioned relative to the viewport. If you give `wrapper` relative positioning, it will cause `imageright` to be positioned relative to `wrapper`.
you *can* apply `overflow:hidden;` to the body, which is how you get what you're after, but it's highly inadvisable. Another way to take the div "out of flow" is to make it `position: fixed;` but that will mean it will be visible as you scroll down.
Question: I'm using Sitecore Webforms For Marketers in a multi-language environment (e.g. .com, .be, .nl en .de). There are 3 servers: 2 Content Delivery Servers (CDS) en 1 Content Management Server (CMS). On the CDS servers is no possibility to write data, so i have configured a webservice to forward the form data from the CDS to the CMS server. My problem is that the Web service communicates with the .com domain. By using the .com domein for webservice communication, the CMS doesn't have any know how what the site context is from the submitting domain. For example, a user submits a form on the .nl domain, the CMS server thinks it's coming form the .com domain. Does anyone know how i can get the site context (e.g. NL-nl) from the submit? Thanks a lot! Jordy Answer:
Similar question was asked [here](https://stackoverflow.com/questions/20800966/how-to-get-the-sitecore-current-site-object-inside-custom-save-action-wffm) and answered by [@TwentyGotoTen](https://stackoverflow.com/users/2124993/twentygototen). The place where you need to get the current site is different than in linked question, but the answer is the same. Use the code which is used by Sitecore to resolve site: ``` var url = System.Web.HttpContext.Current.Request.Url; var siteContext = Sitecore.Sites.SiteContextFactory.GetSiteContext(url.Host, url.PathAndQuery); ``` The extended version of the code for resolving sites (linked in the same question by [@MarkUrsino](https://stackoverflow.com/users/134360/mark-ursino)) can be found in article [Sitecore Context Site Resolution](http://firebreaksice.com/sitecore-context-site-resolution/). Can you use the proper domain for each web service call? If you have to call web service using `.com` domain only, maybe you can try to check `UrlReferrer` instead of current request `Url` host?
Update your web service to pass an extra parameter for the host name (via the CD clients) and then on the service (on your CM) get the context site from that.
Question: I'm using Sitecore Webforms For Marketers in a multi-language environment (e.g. .com, .be, .nl en .de). There are 3 servers: 2 Content Delivery Servers (CDS) en 1 Content Management Server (CMS). On the CDS servers is no possibility to write data, so i have configured a webservice to forward the form data from the CDS to the CMS server. My problem is that the Web service communicates with the .com domain. By using the .com domein for webservice communication, the CMS doesn't have any know how what the site context is from the submitting domain. For example, a user submits a form on the .nl domain, the CMS server thinks it's coming form the .com domain. Does anyone know how i can get the site context (e.g. NL-nl) from the submit? Thanks a lot! Jordy Answer:
Similar question was asked [here](https://stackoverflow.com/questions/20800966/how-to-get-the-sitecore-current-site-object-inside-custom-save-action-wffm) and answered by [@TwentyGotoTen](https://stackoverflow.com/users/2124993/twentygototen). The place where you need to get the current site is different than in linked question, but the answer is the same. Use the code which is used by Sitecore to resolve site: ``` var url = System.Web.HttpContext.Current.Request.Url; var siteContext = Sitecore.Sites.SiteContextFactory.GetSiteContext(url.Host, url.PathAndQuery); ``` The extended version of the code for resolving sites (linked in the same question by [@MarkUrsino](https://stackoverflow.com/users/134360/mark-ursino)) can be found in article [Sitecore Context Site Resolution](http://firebreaksice.com/sitecore-context-site-resolution/). Can you use the proper domain for each web service call? If you have to call web service using `.com` domain only, maybe you can try to check `UrlReferrer` instead of current request `Url` host?
I created for each domain a custom save action. This solves the problem.
Question: I'm using Sitecore Webforms For Marketers in a multi-language environment (e.g. .com, .be, .nl en .de). There are 3 servers: 2 Content Delivery Servers (CDS) en 1 Content Management Server (CMS). On the CDS servers is no possibility to write data, so i have configured a webservice to forward the form data from the CDS to the CMS server. My problem is that the Web service communicates with the .com domain. By using the .com domein for webservice communication, the CMS doesn't have any know how what the site context is from the submitting domain. For example, a user submits a form on the .nl domain, the CMS server thinks it's coming form the .com domain. Does anyone know how i can get the site context (e.g. NL-nl) from the submit? Thanks a lot! Jordy Answer:
I created for each domain a custom save action. This solves the problem.
Update your web service to pass an extra parameter for the host name (via the CD clients) and then on the service (on your CM) get the context site from that.
Question: My Flash plugin just won't work for Firefox on Linux Mint. I am running Linux Mint 14 Nadia 64bit. * Downloaded firefox-27.0.1.tar.bz2 * Extracted it * Ran ./firefox it works fine * Downloaded install\_flash\_player\_11\_linux.x86\_64.tar.gz * Extracted it * Copied the plugin: **cp libflashplayer.so /home/gary/.mozilla/plugins/** * Copied the Flash Player Local Settings configurations: **sudo cp -r usr/\* /usr** * Generated dependency lists for Flash Player: **ldd /home/gary/.mozilla/plugins/libflashplayer.so** Plugin still doesn't work. Any help would be appreciated. Answer:
Rather than delay initialising the whole page it would be better to allow it all to be initialised, then initialise just the new code. In jQm v1.3.2 and earlier you could do this by adding the following code to your success callback. ``` $('#newsDescription table').trigger('create'); ``` This will allow the whole page to initialise and prevent a flash of an unstyled page to the user if they have a slow network connection which could cause your ajax request to take a while.
I have put `$.mobile.initializePage();` inside success callback every thing works then.
Question: I got excited about Calc's power as an embedded mode. Define some variables in natural inline notation and then do operations on them. But the execution seems a bit messy: you got a separate key bindings when you're in CalcEmbed mode and mistakes are easy to make. Can the mode be tamed so that the following org-mode buffer: ``` * Calc test embed! Let $foo := 342$ and $bar := 2.2$. Now $foo*bar => $! ``` Could be evaluated to ``` * Calc test embed! Let $foo := 342$ and $bar := 2.2$. Now $foo*bar => 752.4$! ``` With a single key stroke, all the while remaining in org-mode? Answer:
Maybe not a single keystroke but you could *activate* embedded mode via `C-x * a` and then (while point is in, say, the first expression) *update* all calc expressions with `C-x * u`. I use embedded mode all the time and it's one of the most understated features of Emacs!
To expand on @éric's answer: you can avoid having to activate the formulas explicitly with `C-x * a` by including these lines: ``` --- Local Variables: --- --- eval:(calc-embedded-activate) --- --- End: --- ``` In an org-mode file, using just `#` instead of `---` is probably better though. Also notice that this and `C-x * a` doesn't actually *activate* embedded mode, but just activates the formulas for embedded mode, so you stay in org-mode. (See [doc for `calc-embedded-activate`](https://www.gnu.org/software/emacs/manual/html_node/calc/Assignments-in-Embedded-Mode.html#index-C_002dx-_002a-a) for reference.) Also, you can call `C-x * u` with a numeric prefix, which will update all activated `=>` formulas, so you don't need to move the point into a formula first (e.g. `C-- C-x * u` but not `C-u C-x * u` which will only update formulas in the current region). In itself, `C-x * u` will only update formulas which are dependent on the current formula (i.e. where the point is pointing at). (See [doc for `calc-embedded-update-formula`](https://www.gnu.org/software/emacs/manual/html_node/calc/Assignments-in-Embedded-Mode.html#index-calc_002dembedded_002dupdate_002dformula) for reference.)
Question: I have table in mysqli database now i want to get 1 result random This is code mysql ``` $cid = $_GET['id']; $ans = $db->query("select * from result where cat_id='$cid' limit 1"); $rowans = $ans->fetch_object(); echo" <h4>".$rowans->title."</h4><br> <img src='".$rowans->img."' style='width:400px;height:300;' /> <p>".$rowans->desc."</p>"; ``` in this code i get 1 result but not random always gives me the same result Answer:
SQL: ``` SELECT * FROM result ORDER BY rand() LIMIT 1 ```
`LIMIT` orders the rows by the primary key of the table, so you always get the same one (the "first" row according to that key). Try: ``` SELECT * FROM result WHERE cat_id='$cid' ORDER BY RAND() LIMIT 0,1; ``` You can think of it this way: it first orders the results by a random order, then picks the first one.
Question: I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks. Answer:
Do it on `IOrganisation`(and have `IPeople` as the return type). Something like this: ``` interface IOrganisation { IList<IPeople> GetPeople(); } ``` This is because the people of an organisation is a property of the organisation, not of the people.
That sounds like it should be on `IOrganization` - that's what you'll call it on, after all. What you *have* is the organization, you *want* the list of people - you can't *start* fromt the list of people, so it *must* be part of the `IOrganization` interface. I find it strange to have *plural* interface names to start with - I'd expect `IOrganization` for a single organization, and `IPerson` for a single person. ``` public interface IOrganization { IList<IPerson> GetPeople(); } ```
Question: I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks. Answer:
Do it on `IOrganisation`(and have `IPeople` as the return type). Something like this: ``` interface IOrganisation { IList<IPeople> GetPeople(); } ``` This is because the people of an organisation is a property of the organisation, not of the people.
Which belongs to which? It seems to me that `iOrganisation.People` would be a list of people ( is your "IPeople" interface representing a list of people or a single person? ) belonging to the organisation. Likewise you might have an `IPeople.Organisations` that lists all organisations that a person belongs to. Both will probably have a different underlying mechanism - maybe calling the same lookup table - it doesn't matter to the person calling the code.
Question: I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks. Answer:
Do it on `IOrganisation`(and have `IPeople` as the return type). Something like this: ``` interface IOrganisation { IList<IPeople> GetPeople(); } ``` This is because the people of an organisation is a property of the organisation, not of the people.
First of all, your should probably not have pluralized interface names. So call them IOrganization and IPerson and then on your `IOrganisation` interface you might have a method called: ``` IEnumerable<IPerson> GetPeople() ```
Question: I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks. Answer:
Do it on `IOrganisation`(and have `IPeople` as the return type). Something like this: ``` interface IOrganisation { IList<IPeople> GetPeople(); } ``` This is because the people of an organisation is a property of the organisation, not of the people.
If you think of an organization as a collection containing people, then it's intuitive to put that in `IOrganization`. It would look like this: ``` interface IOrganization { IList<IPeople> Members { get; } } ```
Question: I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks. Answer:
That sounds like it should be on `IOrganization` - that's what you'll call it on, after all. What you *have* is the organization, you *want* the list of people - you can't *start* fromt the list of people, so it *must* be part of the `IOrganization` interface. I find it strange to have *plural* interface names to start with - I'd expect `IOrganization` for a single organization, and `IPerson` for a single person. ``` public interface IOrganization { IList<IPerson> GetPeople(); } ```
Which belongs to which? It seems to me that `iOrganisation.People` would be a list of people ( is your "IPeople" interface representing a list of people or a single person? ) belonging to the organisation. Likewise you might have an `IPeople.Organisations` that lists all organisations that a person belongs to. Both will probably have a different underlying mechanism - maybe calling the same lookup table - it doesn't matter to the person calling the code.
Question: I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks. Answer:
That sounds like it should be on `IOrganization` - that's what you'll call it on, after all. What you *have* is the organization, you *want* the list of people - you can't *start* fromt the list of people, so it *must* be part of the `IOrganization` interface. I find it strange to have *plural* interface names to start with - I'd expect `IOrganization` for a single organization, and `IPerson` for a single person. ``` public interface IOrganization { IList<IPerson> GetPeople(); } ```
First of all, your should probably not have pluralized interface names. So call them IOrganization and IPerson and then on your `IOrganisation` interface you might have a method called: ``` IEnumerable<IPerson> GetPeople() ```
Question: I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks. Answer:
That sounds like it should be on `IOrganization` - that's what you'll call it on, after all. What you *have* is the organization, you *want* the list of people - you can't *start* fromt the list of people, so it *must* be part of the `IOrganization` interface. I find it strange to have *plural* interface names to start with - I'd expect `IOrganization` for a single organization, and `IPerson` for a single person. ``` public interface IOrganization { IList<IPerson> GetPeople(); } ```
If you think of an organization as a collection containing people, then it's intuitive to put that in `IOrganization`. It would look like this: ``` interface IOrganization { IList<IPeople> Members { get; } } ```
Question: I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks. Answer:
First of all, your should probably not have pluralized interface names. So call them IOrganization and IPerson and then on your `IOrganisation` interface you might have a method called: ``` IEnumerable<IPerson> GetPeople() ```
Which belongs to which? It seems to me that `iOrganisation.People` would be a list of people ( is your "IPeople" interface representing a list of people or a single person? ) belonging to the organisation. Likewise you might have an `IPeople.Organisations` that lists all organisations that a person belongs to. Both will probably have a different underlying mechanism - maybe calling the same lookup table - it doesn't matter to the person calling the code.
Question: I am developing an asp.net application where i have a dataset having 3 tables i.e. `ds.Tables[0], Tables[1] and Tables[2]` I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that? I found similar question in SO [here](https://stackoverflow.com/questions/2442525/how-to-select-min-and-max-values-of-a-column-in-a-datatable) but not sure how that would help me getting my way? **UPDATED:** ``` double minValue = double.MinValue; double maxValue = double.MaxValue; foreach (DataRow dr in dtSMPS.Rows) { double actualValue = dr.Field<double>("TOTAL_SUM"); // This fails specifying type cast error minValue = Math.Min(minValue, actualValue); maxValue = Math.Max(maxValue, actualValue); } ``` Please guide! Thanks. Answer:
First of all, your should probably not have pluralized interface names. So call them IOrganization and IPerson and then on your `IOrganisation` interface you might have a method called: ``` IEnumerable<IPerson> GetPeople() ```
If you think of an organization as a collection containing people, then it's intuitive to put that in `IOrganization`. It would look like this: ``` interface IOrganization { IList<IPeople> Members { get; } } ```
Question: I've got some problems with my Connection string. Seached the web for some mistakes but didn't got any further. Is there something changed between SQL Server versions? ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> </configSections> <connectionStrings> <add name="BeursTD.Properties.Settings.sdtcaptConnectionString" connectionString="Data Source=localhost\SQLEXPRESS,1433;Initial Catalog=sdtcapt;User ID=XXXX;Password=XXXX" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration> ``` Answer:
There are at least two reasons why this issue (`Client Error: Remaining data too small for BSON object`) appears: **1. PHP MongoDB driver is not compatible with MongoDB installed on the machine.** (originally mentioned in the [first answer](https://stackoverflow.com/a/34646148/309031)). Examine PHP driver version set up on your machine on `<?php phpinfo();` page: [![enter image description here](https://i.stack.imgur.com/oaB0u.jpg)](https://i.stack.imgur.com/oaB0u.jpg) Retrieve MongoDB version in use with: ``` mongod --version\ # db version v3.2.0 ``` Use [compatibility table on MongoDB website](https://docs.mongodb.org/ecosystem/drivers/php/#compatibility) to see whether examined PHP MongoDB driver version is compatible with MongoDB version: [![enter image description here](https://i.stack.imgur.com/8uMyC.jpg)](https://i.stack.imgur.com/8uMyC.jpg) If versions are not compatible, it is required to uninstall one of the existing parts and install compatible version. From my own experience, it is much easier to change PHP MongoDB driver, since only different `.so` extension file is required. **2. Two PHP MongoDB drivers are installed on the machine.** Since [`MongoClient`](http://php.net/manual/en/class.mongoclient.php) is deprecated, many tutorials and articles online (including [official mongo-php-driver repository on Github](https://github.com/mongodb/mongo-php-driver#installation)) now guides to install `mongodb`, not `mongo` PHP driver. Year+ before, everyone was pointing at `mongo` extension, however. Because of this change from `mongo` to `mongodb`, we might get both extensions defined in `php.ini` file. *Just make sure, only one extension is defined under "Dynamic Extension" section*: [![enter image description here](https://i.stack.imgur.com/4lPG6.jpg)](https://i.stack.imgur.com/4lPG6.jpg) --- Hope somebody gets this answer useful when looking for a solution to fix "Remaining data too small for BSON object" error working with MongoDB through PHP MongoDB driver.
The issue was that Laravel was unable to communicate with MongoDB because I was using the mongodb-1.1 php driver and MongoDB 3.2 together. According to the table found on this page: <https://docs.mongodb.org/ecosystem/drivers/php/>, these two versions are not compatible. I uninstalled MongoDB 3.2 and installed MongoDB 3.O, and the problem was solved.
Question: These are my haves: ``` vec <- seq(1, 3, by = 1) df <- data.frame(x1 = c("a1", "a2")) ``` and this is my wants: ``` x1 x2 1 a1 1 2 a2 1 3 a1 2 4 a2 2 5 a1 3 6 a2 3 ``` I basically want to replicate the data frame according to the values in the vector vec. This is my working (possibly inefficient approach): ``` vec <- seq(1, 3, by = 1) df <- data.frame(x1 = c("a1", "a2")) results <- NULL for (v in vec) { results <- rbind(results, cbind(df, x2=v)) } results ``` Maybe there is a better way? Sorry this is more like a code review. Thanks! PS: Thanks for all your great answers. Sorry should have thought about some myself but it is early here. I will have to accept one. Sorry no hard feelings! Answer:
You can use `crossing` : ``` tidyr::crossing(df, vec) %>% dplyr::arrange(vec) # x1 vec # <chr> <dbl> #1 a1 1 #2 a2 1 #3 a1 2 #4 a2 2 #5 a1 3 #6 a2 3 ``` Also, ``` tidyr::expand_grid(df, vec) %>% dplyr::arrange(vec) ```
One option could be: ``` data.frame(x1 = df, x2 = rep(vec, each = nrow(df))) x1 x2 1 a1 1 2 a2 1 3 a1 2 4 a2 2 5 a1 3 6 a2 3 ```
Question: These are my haves: ``` vec <- seq(1, 3, by = 1) df <- data.frame(x1 = c("a1", "a2")) ``` and this is my wants: ``` x1 x2 1 a1 1 2 a2 1 3 a1 2 4 a2 2 5 a1 3 6 a2 3 ``` I basically want to replicate the data frame according to the values in the vector vec. This is my working (possibly inefficient approach): ``` vec <- seq(1, 3, by = 1) df <- data.frame(x1 = c("a1", "a2")) results <- NULL for (v in vec) { results <- rbind(results, cbind(df, x2=v)) } results ``` Maybe there is a better way? Sorry this is more like a code review. Thanks! PS: Thanks for all your great answers. Sorry should have thought about some myself but it is early here. I will have to accept one. Sorry no hard feelings! Answer:
You can use `crossing` : ``` tidyr::crossing(df, vec) %>% dplyr::arrange(vec) # x1 vec # <chr> <dbl> #1 a1 1 #2 a2 1 #3 a1 2 #4 a2 2 #5 a1 3 #6 a2 3 ``` Also, ``` tidyr::expand_grid(df, vec) %>% dplyr::arrange(vec) ```
`expand.grid` can give all combinations of two vectors. ``` expand.grid(x1 = df$x1, vec = vec) #> x1 vec #> 1 a1 1 #> 2 a2 1 #> 3 a1 2 #> 4 a2 2 #> 5 a1 3 #> 6 a2 3 ```
Question: I am trying to make my nav bar sit parallel with my logo but I'm having difficulty doing this. First of all, when I enter the code for the image, the image afterwards doesn't display at the top of the page. Instead, it sits about 40px below the page. I have tried using floats, but have had no luck. I have created a negative value of -20px for the logo to sit further at the top of the page but would like to know if that is normal practice in CSS I have tried looking at youtube videos but the code they share doesn't seem to work on my project. I'm just wondering whether the image may be a bit too big for the header ![](https://i.stack.imgur.com/ep89u.png) Answer:
"To maintain the integrity of the data dictionary, tables in the SYS schema are manipulated only by the database. They should never be modified by any user or database administrator. You must not create any tables in the SYS schema." <https://docs.oracle.com/database/121/ADMQS/GUID-CF1CD853-AF15-41EC-BC80-61918C73FDB5.htm#ADMQS12003>
Try to put in this order: ``` ALTER TABLE table_name DROP COLUMN column_name; ``` If the table has data it doesn't work.
Question: I have a table `HRTC` in SQL Server. I want to import data which is in Excel into this table. But my Excel file does not have all the columns which match the `HRTC` table. Is there anyway I can do this? I am thinking something like in the import wizard ``` Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\testing.xls;HDR=YES', 'SELECT * FROM [SheetName$]') select column1, column2 from HRTC ``` Answer:
Try this Create a temp table ``` Select * INTO TmpTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\testing.xls;HDR=YES', 'SELECT * FROM [SheetName$]') ``` Then to insert row into hrtc using temptable, any missing columns will have null ``` INSERT INTO hrtc(column1, column2) select col1, col2 from TmpTable ```
One simple approach is to script your excel file into a collection of insert statement, then run it on SQL Server. Also if you can export your excel file into CSV file, this is often useful. Tool like SQL Server Management Studio should have some kind of import wizard where you can load the CSV, choose column mapping etc.
Question: I have a table `HRTC` in SQL Server. I want to import data which is in Excel into this table. But my Excel file does not have all the columns which match the `HRTC` table. Is there anyway I can do this? I am thinking something like in the import wizard ``` Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\testing.xls;HDR=YES', 'SELECT * FROM [SheetName$]') select column1, column2 from HRTC ``` Answer:
Try this Create a temp table ``` Select * INTO TmpTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\testing.xls;HDR=YES', 'SELECT * FROM [SheetName$]') ``` Then to insert row into hrtc using temptable, any missing columns will have null ``` INSERT INTO hrtc(column1, column2) select col1, col2 from TmpTable ```
What I often end up doing in these situations is to do some code completion using excel's CONCATENATE function. Let's say you have: ``` A B 1 foo bar 2 test2 bar2 3 test3 bar 3 ``` If you needed to insert those into a table. In column C you can write: ``` =CONCATENATE("INSERT INTO HRTC(col, col2) VALUES('", A1, "','", B1, "')") ```
Question: I have a table `HRTC` in SQL Server. I want to import data which is in Excel into this table. But my Excel file does not have all the columns which match the `HRTC` table. Is there anyway I can do this? I am thinking something like in the import wizard ``` Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\testing.xls;HDR=YES', 'SELECT * FROM [SheetName$]') select column1, column2 from HRTC ``` Answer:
One simple approach is to script your excel file into a collection of insert statement, then run it on SQL Server. Also if you can export your excel file into CSV file, this is often useful. Tool like SQL Server Management Studio should have some kind of import wizard where you can load the CSV, choose column mapping etc.
What I often end up doing in these situations is to do some code completion using excel's CONCATENATE function. Let's say you have: ``` A B 1 foo bar 2 test2 bar2 3 test3 bar 3 ``` If you needed to insert those into a table. In column C you can write: ``` =CONCATENATE("INSERT INTO HRTC(col, col2) VALUES('", A1, "','", B1, "')") ```
Question: Hi I was wondering whether someone would be able to help me with a query. I am trying to select from an EAV type table where the value is not multiple values. Using the example below I am trying to retrieve rows where tag\_id != 1 and tag\_id != 2. So based on the data I want to return just the row containing contact\_id 3 ``` Tags Table: contact_id tag_id 1 1 1 2 2 1 2 4 3 4 ``` The desire result is to return a single row: ``` contact_id -> 3 ``` I have tried the following queries which don't return what I am looking for so are obviously are not correct: ``` select `contact_id` from `contact_tags` where tag_id !=1 and tag_id != 2 select `contact_id` from `contact_tags` where tag_id NOT IN(1,2) ``` Any help on this. Or just a pointer in the right direction would be great. Answer:
You can use `NOT EXISTS()` in which the statement inside selects all records where it has tags of `1` or `2`. ``` SELECT contact_id FROM contact_tags a WHERE NOT EXISTS ( SELECT 1 FROM contact_tags b WHERE tag_id IN (1, 2) AND a.contact_id = b.contact_id ) GROUP BY contact_id ``` * [SQLFiddle Demo](http://sqlfiddle.com/#!2/b2b11/5) Another alternative is to use `LEFT JOIN` ``` SELECT a.contact_id FROM contact_tags a LEFT JOIN contact_tags b ON a.contact_id = b.contact_id AND b.tag_id IN (1, 2) WHERE b.contact_id IS NULL ``` * [SQLFiddle Demo](http://sqlfiddle.com/#!2/b2b11/13)
Stealing from @491243 fiddle here is a modification which returns contacts\_id which lack both tags\_id <http://sqlfiddle.com/#!2/b2b11/19>
Question: Hi I was wondering whether someone would be able to help me with a query. I am trying to select from an EAV type table where the value is not multiple values. Using the example below I am trying to retrieve rows where tag\_id != 1 and tag\_id != 2. So based on the data I want to return just the row containing contact\_id 3 ``` Tags Table: contact_id tag_id 1 1 1 2 2 1 2 4 3 4 ``` The desire result is to return a single row: ``` contact_id -> 3 ``` I have tried the following queries which don't return what I am looking for so are obviously are not correct: ``` select `contact_id` from `contact_tags` where tag_id !=1 and tag_id != 2 select `contact_id` from `contact_tags` where tag_id NOT IN(1,2) ``` Any help on this. Or just a pointer in the right direction would be great. Answer:
may be this is what you want ``` select contact_id from contact_tags where contact_id not in ( select contact_id from contact_tags where tag_id in (1,2) ) tmp ```
Stealing from @491243 fiddle here is a modification which returns contacts\_id which lack both tags\_id <http://sqlfiddle.com/#!2/b2b11/19>
Question: I'm new in Ruby/Rails, so, my question: what is the perfect way to upload file and save filename in database with rails? Are there any Gem? Or maybe there are good build-in feature? Answer:
Also try [carrierwave](https://github.com/jnicklas/carrierwave), Ryan has a good screencast about this [gem](http://railscasts.com/episodes/253-carrierwave-file-uploads)
Most people use the [Paperclip Gem](https://github.com/thoughtbot/paperclip).
Question: I'm new in Ruby/Rails, so, my question: what is the perfect way to upload file and save filename in database with rails? Are there any Gem? Or maybe there are good build-in feature? Answer:
You can try Paperclip.It is most popular gem in rails community... ``` https://github.com/thoughtbot/paperclip ``` these lines do the all stuff ``` class User < ActiveRecord::Base has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" } end ``` Try it......
Most people use the [Paperclip Gem](https://github.com/thoughtbot/paperclip).
Question: I'm new in Ruby/Rails, so, my question: what is the perfect way to upload file and save filename in database with rails? Are there any Gem? Or maybe there are good build-in feature? Answer:
Just take a look on the links to choose between paperClip & carrierwave : [Rails 3 paperclip vs carrierwave vs dragonfly vs attachment\_fu](https://stackoverflow.com/questions/7419731/rails-3-paperclip-vs-carrierwave-vs-dragonfly-vs-attachment-fu) And <http://bcjordan.github.com/posts/rails-image-uploading-framework-comparison/>
Most people use the [Paperclip Gem](https://github.com/thoughtbot/paperclip).
Question: I'm new in Ruby/Rails, so, my question: what is the perfect way to upload file and save filename in database with rails? Are there any Gem? Or maybe there are good build-in feature? Answer:
Also try [carrierwave](https://github.com/jnicklas/carrierwave), Ryan has a good screencast about this [gem](http://railscasts.com/episodes/253-carrierwave-file-uploads)
Just take a look on the links to choose between paperClip & carrierwave : [Rails 3 paperclip vs carrierwave vs dragonfly vs attachment\_fu](https://stackoverflow.com/questions/7419731/rails-3-paperclip-vs-carrierwave-vs-dragonfly-vs-attachment-fu) And <http://bcjordan.github.com/posts/rails-image-uploading-framework-comparison/>
Question: I'm new in Ruby/Rails, so, my question: what is the perfect way to upload file and save filename in database with rails? Are there any Gem? Or maybe there are good build-in feature? Answer:
You can try Paperclip.It is most popular gem in rails community... ``` https://github.com/thoughtbot/paperclip ``` these lines do the all stuff ``` class User < ActiveRecord::Base has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" } end ``` Try it......
Just take a look on the links to choose between paperClip & carrierwave : [Rails 3 paperclip vs carrierwave vs dragonfly vs attachment\_fu](https://stackoverflow.com/questions/7419731/rails-3-paperclip-vs-carrierwave-vs-dragonfly-vs-attachment-fu) And <http://bcjordan.github.com/posts/rails-image-uploading-framework-comparison/>
Question: lick() is a private method of Cat. Unfortunately, Cat's this.paw is not accessible in lick(). Is there a simple way to create a private method that has access to the member variables of its containing class? ``` <!doctype html> <html> <head> <meta charset="utf-8"> </head> <body> <p id="catStatus">???</p> <script> function Cat() { this.paw; var lick = function() { alert(this.paw); if(this.paw == "sticky") { alert("meow"); document.getElementById("catStatus").innerHTML = "*Slurp*"; } }; this.beCat = function() { this.paw = "sticky"; lick(); } } var kitty = new Cat(); kitty.beCat(); </script> </body> </html> ``` ![Result](https://i.stack.imgur.com/cIpgr.png) Answer:
The value of `this` depends on how you call the method. Since you're not calling the method on the object instance, `this` becomes the global object. Instead, you need to save `this` in a variable: ``` function Cat() { this.paw = ...; var me = this; var lick = function() { alert(me.paw); if(me.paw == "sticky") { alert("meow"); document.getElementById("catStatus").innerHTML = "*Slurp*"; } }; this.beCat = function() { this.paw = "sticky"; lick(); } } ```
There are a couple ways to solve this. The problem is that the context inside of lick is not the instance of cat. You can either: Use the call method to set the context ``` this.beCat = function() { this.paw = "sticky"; lick.call(this); }; ``` or use closure ``` var instance = this; var lick = function() { alert(instance.paw); if(instance.paw == "sticky") { alert("meow"); document.getElementById("catStatus").innerHTML = "*Slurp*"; } }; ```
Question: lick() is a private method of Cat. Unfortunately, Cat's this.paw is not accessible in lick(). Is there a simple way to create a private method that has access to the member variables of its containing class? ``` <!doctype html> <html> <head> <meta charset="utf-8"> </head> <body> <p id="catStatus">???</p> <script> function Cat() { this.paw; var lick = function() { alert(this.paw); if(this.paw == "sticky") { alert("meow"); document.getElementById("catStatus").innerHTML = "*Slurp*"; } }; this.beCat = function() { this.paw = "sticky"; lick(); } } var kitty = new Cat(); kitty.beCat(); </script> </body> </html> ``` ![Result](https://i.stack.imgur.com/cIpgr.png) Answer:
The value of `this` depends on how you call the method. Since you're not calling the method on the object instance, `this` becomes the global object. Instead, you need to save `this` in a variable: ``` function Cat() { this.paw = ...; var me = this; var lick = function() { alert(me.paw); if(me.paw == "sticky") { alert("meow"); document.getElementById("catStatus").innerHTML = "*Slurp*"; } }; this.beCat = function() { this.paw = "sticky"; lick(); } } ```
The context of this depends upon who called the function. In this case it is beCat. You can however explicitly specify the this scope by using call. In your case: ``` this.beCat = function () { this.paw = "sticky"; lick.call(this); } ``` Or you can store the this in a variable. You can read more about the this scope/how it works [here](http://unschooled.org/2012/03/understanding-javascript-this/).
Question: I'm working with [AI-Thermometer](https://github.com/tomek-l/ai-thermometer) project using Nvidia Jeton Nano. The project is using Pi camera v2 for video capturing. Here's the command of showing video streams using Pi camera v2. ```sh gst-launch-1.0 nvarguscamerasrc sensor_mode=0 ! 'video/x-raw(memory:NVMM),width=3264, height=2464, framerate=21/1, format=NV12' ! nvvidconv flip-method=2 ! 'video/x-raw,width=960, height=720' ! nvvidconv ! nvegltransform ! nveglglessink -e ``` I want to use the normal USB webcam (such as Logitech c930) instead of Pi camera v2. To do so, I need to stream the USB webcam data using GStreamer in the same way as above pipeline commands. I installed `v4l-utils` on Ubuntu of Jetson Nano. And tried like this, ```sh gst-launch-1.0 v4l2src device="/dev/video0" ! 'video/x-raw(memory:NVMM),width= ... ``` , but it gave a warning and didn't work. How can I show video streams from webcam? Answer:
There should not quotes around the device parameter i.e. `device=/dev/video0`. If the error persists, then its probably something else.
```none gst-launch-1.0 v4l2src device="/dev/video0" ! \ "video/x-raw, width=640, height=480, format=(string)YUY2" ! \ xvimagesink -e ```
Question: What naming conventions do you use for everyday code? I'm pondering this because I currently have a project in Python that contains 3 packages, each with a unique purpose. Now, I've been putting general-purpose, 'utility' methods into the first package I created for the project, however I'm contemplating moving these methods to a separate package. The question is what would I call it? Utility, Collection, Assorted? Is there any standard naming conventions you swear by, and if so can you please provide links? I'm aware each language has it's own naming conventions, however is there any particular one that you find the most useful, that you'd recommend I'd start using? Answer:
In general, you should follow the naming convention of the language you're using. It doesn't matter if you like or prefer the standards of another language. Consistency within the context of the language helps make your code more readable, maintainable, and usable by others. In Python, that means you use [PEP 8](http://www.python.org/dev/peps/pep-0008/). Using a personal example: In Python, I'd call the package "utils" -- or if I intended on redistribution, "coryutils" or something similar to avoid namespace collisions. In Java or ActionScript, I'd call the package "net.petosky.utils", regardless of whether I intended on redistribution or not.
Unless you have some good reason not to, you should follow the guidelines presented in [PEP 8](http://www.python.org/dev/peps/pep-0008/). See, in particular, "Prescriptive: Naming Conventions".
Question: I have a table like this: ``` CREATE TABLE mytable ( user_id int, device_id ascii, record_time timestamp, timestamp timeuuid, info_1 text, info_2 int, PRIMARY KEY (user_id, device_id, record_time, timestamp) ); ``` When I ask Cassandra to delete a record (an entry in the columnfamily) like this: ``` DELETE from my_table where user_id = X and device_id = Y and record_time = Z and timestamp = XX; ``` it returns without an error, but when I query again the record is still there. Now if I try to delete a whole row like this: ``` DELETE from my_table where user_id = X ``` It works and removes the whole row, and querying again immediately doesn't return any more data from that row. What I am doing wrong? How you can remove a record in Cassandra? Thanks Answer:
Ok, here is my theory as to what is going on. You have to be careful with timestamps, because they will *store* data down to the millisecond. But, they will only *display* data to the second. Take this sample table for example: ``` aploetz@cqlsh:stackoverflow> SELECT id, datetime FROM data; id | datetime --------+-------------------------- B25881 | 2015-02-16 12:00:03-0600 B26354 | 2015-02-16 12:00:03-0600 (2 rows) ``` The `datetime`s (of type timestamp) are equal, right? Nope: ``` aploetz@cqlsh:stackoverflow> SELECT id, blobAsBigint(timestampAsBlob(datetime)), datetime FROM data; id | blobAsBigint(timestampAsBlob(datetime)) | datetime --------+-----------------------------------------+-------------------------- B25881 | 1424109603000 | 2015-02-16 12:00:03-0600 B26354 | 1424109603234 | 2015-02-16 12:00:03-0600 (2 rows) ``` As you are finding out, this becomes problematic when you use timestamps as part of your PRIMARY KEY. It is possible that your timestamp is storing more precision than it is showing you. And thus, you will need to provide that hidden precision if you will be successful in deleting that single row. Anyway, you have a couple of options here. One, find a way to ensure that you are not entering more precision than necessary into your `record_time`. Or, you could define `record_time` as a timeuuid. Again, it's a theory. I could be totally wrong, but I have seen people do this a few times. Usually it happens when they insert timestamp data using `dateof(now())` like this: ``` INSERT INTO table (key, time, data) VALUES (1,dateof(now()),'blah blah'); ```
``` CREATE TABLE worker_login_table ( worker_id text, logged_in_time timestamp, PRIMARY KEY (worker_id, logged_in_time) ); INSERT INTO worker_login_table (worker_id, logged_in_time) VALUES ("worker_1",toTimestamp(now())); ``` after 1 hour executed the above insert statement once again ``` select * from worker_login_table; worker_id| logged_in_time ----------+-------------------------- worker_1 | 2019-10-23 12:00:03+0000 worker_1 | 2015-10-23 13:00:03+0000 (2 rows) ``` Query the table to get absolute timestamp ``` select worker_id, blobAsBigint(timestampAsBlob(logged_in_time )), logged_in_time from worker_login_table; worker_id | blobAsBigint(timestampAsBlob(logged_in_time)) | logged_in_time --------+-----------------------------------------+-------------------------- worker_1 | 1524109603000 | 2019-10-23 12:00:03+0000 worker_1 | 1524209403234 | 2019-10-23 13:00:03+0000 (2 rows) ``` The below command **will not delete** the entry from Cassandra as the precise value of timestamp is required to delete the entry ``` DELETE from worker_login_table where worker_id='worker_1' and logged_in_time ='2019-10-23 12:00:03+0000'; ``` By using the timestamp from blob **we can delete** the entry from Cassandra ``` DELETE from worker_login_table where worker_id='worker_1' and logged_in_time ='1524209403234'; ```
Question: Got a table with 1200 rows. Added a new column which will contain incremental values - Candidate1 Candidate2 Candidate3 . . . Candidate1200 What is the best way to insert these values , non manual way. I am using SQL Server 2008 Answer:
Simple: ``` $post_title = sanitize_title_with_dashes($post_title); ``` But WordPress does this for you already. I assume you need it for something different?
Some solution might be found at <http://postedpost.com/2008/06/23/ultimate-wordpress-post-name-url-sanitize-solution/> Also, you might want to do it as follows: ``` $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}"); $post_name = str_replace(' ', '-', str_replace($special_chars, '', strtolower($post_name))); ```
Question: Got a table with 1200 rows. Added a new column which will contain incremental values - Candidate1 Candidate2 Candidate3 . . . Candidate1200 What is the best way to insert these values , non manual way. I am using SQL Server 2008 Answer:
I'm guessing you're sanitizing by direct SQL insertion. Instead, consider using wp\_post\_insert() in your insertion script. ``` $new_post_id = wp_insert_post(array( 'post_title' => "This <open_tag insane title thing<b>LOL!;drop table `bobby`;" )); ``` At this point, you just worry about your title - and not the slug, post name, etc. WP will take care of the rest and (at least security) sanitization. The slug, as demonstrated in the screenshot, becomes fairly usable. ![alt text](https://i.stack.imgur.com/PgVau.jpg) This function can be used by simply doing `include( "wp-config.php" );` and going about your business without any other PHP overhead. If you are dealing with some funky titles to begin with, a simple strip\_tags(trim()) might do the trick. Otherwise, you've got other problems to deal with ;-)
Some solution might be found at <http://postedpost.com/2008/06/23/ultimate-wordpress-post-name-url-sanitize-solution/> Also, you might want to do it as follows: ``` $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}"); $post_name = str_replace(' ', '-', str_replace($special_chars, '', strtolower($post_name))); ```
Question: Got a table with 1200 rows. Added a new column which will contain incremental values - Candidate1 Candidate2 Candidate3 . . . Candidate1200 What is the best way to insert these values , non manual way. I am using SQL Server 2008 Answer:
Simple: ``` $post_title = sanitize_title_with_dashes($post_title); ``` But WordPress does this for you already. I assume you need it for something different?
I'm guessing you're sanitizing by direct SQL insertion. Instead, consider using wp\_post\_insert() in your insertion script. ``` $new_post_id = wp_insert_post(array( 'post_title' => "This <open_tag insane title thing<b>LOL!;drop table `bobby`;" )); ``` At this point, you just worry about your title - and not the slug, post name, etc. WP will take care of the rest and (at least security) sanitization. The slug, as demonstrated in the screenshot, becomes fairly usable. ![alt text](https://i.stack.imgur.com/PgVau.jpg) This function can be used by simply doing `include( "wp-config.php" );` and going about your business without any other PHP overhead. If you are dealing with some funky titles to begin with, a simple strip\_tags(trim()) might do the trick. Otherwise, you've got other problems to deal with ;-)
Question: Has anyone seen this site? <http://answermagento.com/> I know this subject has been briefly discussed but this isn't another site using a StackExchange-clone platform. This site consists entirely of scraped content from Magento SE. [Frequently linked-to site ripping off Magento Stack Exchange](https://magento.meta.stackexchange.com/questions/495/frequently-linked-to-site-ripping-off-magento-stack-exchange) Answer:
The content is CC share-alike, but this site isn't properly crediting the origin. Not important though because the domain name infringes our mark. I've sent a note to our legal team to C&D the owner.
Thats a common problem with stackoverflow/stackexchange content. Usually you dont find it on google anymore, as the duplicate content restrictions are good enough to recognize them. If you still see such things, you can report them to the StackExchange Team via one of the communication ways. I for example sent a mail 3 Years ago about one case. It took some days, but they answered and forwarded the case. They have dedicated persons for this kind of Issue. So, just report it directly to StackExchange, they will forward it to the person responsible for this.
Question: Has anyone seen this site? <http://answermagento.com/> I know this subject has been briefly discussed but this isn't another site using a StackExchange-clone platform. This site consists entirely of scraped content from Magento SE. [Frequently linked-to site ripping off Magento Stack Exchange](https://magento.meta.stackexchange.com/questions/495/frequently-linked-to-site-ripping-off-magento-stack-exchange) Answer:
The content is CC share-alike, but this site isn't properly crediting the origin. Not important though because the domain name infringes our mark. I've sent a note to our legal team to C&D the owner.
**Meet "Alan Storm"** ![Alan Storm](https://i.stack.imgur.com/xB5cM.png) This is another website ripping Magento SE, compare this: * Ours: [Inline translate Chrome Bug?](https://magento.stackexchange.com/q/6435/3326) * Theirs: <http://worldofcoder.com/question/12459/how-to-inline-translate-chrome-bug.html> They left out the poster's names and replaced the pics, hence the good looking "Alan Storm"... ;)
Question: Has anyone seen this site? <http://answermagento.com/> I know this subject has been briefly discussed but this isn't another site using a StackExchange-clone platform. This site consists entirely of scraped content from Magento SE. [Frequently linked-to site ripping off Magento Stack Exchange](https://magento.meta.stackexchange.com/questions/495/frequently-linked-to-site-ripping-off-magento-stack-exchange) Answer:
Thats a common problem with stackoverflow/stackexchange content. Usually you dont find it on google anymore, as the duplicate content restrictions are good enough to recognize them. If you still see such things, you can report them to the StackExchange Team via one of the communication ways. I for example sent a mail 3 Years ago about one case. It took some days, but they answered and forwarded the case. They have dedicated persons for this kind of Issue. So, just report it directly to StackExchange, they will forward it to the person responsible for this.
**Meet "Alan Storm"** ![Alan Storm](https://i.stack.imgur.com/xB5cM.png) This is another website ripping Magento SE, compare this: * Ours: [Inline translate Chrome Bug?](https://magento.stackexchange.com/q/6435/3326) * Theirs: <http://worldofcoder.com/question/12459/how-to-inline-translate-chrome-bug.html> They left out the poster's names and replaced the pics, hence the good looking "Alan Storm"... ;)
Question: I need to create perforce clients from my jenkins build scripts, and this needs to be done unattended. This is mainly because jenkins jobs run in unique folders, Perforce insists that each client has a unique root target folder, and we create new jenkins jobs all the time based on need. Right now each time I create a unique jenkins job, I have to manually create a perforce client for that job - I can do this from the command line, but Perforce also insists on pausing the client creation to show me the specification settings file, which I need to manually close before the client is created. To create the client I'm using ``` p4 -u myuser -P mypassword client -S //mydepo/mystream someclientname ``` and I'm using this awful hack to simultaneously kill notepad ``` p4 -u myuser -P mypassword client -S //mydepo/mystream someclientname | taskkill /IM notepad.exe /F ``` This sort of works, but it doesn't feel right. Is there an official/better way I can force p4 to silently force create a client? Answer:
You can position an absolute View over the RNCamera view, and put all of your content into that absolute view. For example: ```js import { RNCamera } from 'react-native-camera'; class TakePicture extends Component { takePicture = async () => { try { const data = await this.camera.takePictureAsync(); console.log('Path to image: ' + data.uri); } catch (err) { // console.log('err: ', err); } }; render() { return ( <View style={styles.container}> <RNCamera ref={cam => { this.camera = cam; }} style={styles.preview} > <View style={styles.captureContainer}> <TouchableOpacity style={styles.captureBtn} onPress={this.takePicture}> <Icon style={styles.iconCamera}>camera</Icon> <Text>Take Photo</Text> </TouchableOpacity> </View> </RNCamera> <View style={styles.space} /> </View> ); } } const styles = StyleSheet.create({ container: { position: 'relative' }, captueContainer: { position: 'absolute' bottom: 0, }, captureBtn: { backgroundColor: 'red' } }); ``` This is just an example. You will have to play with css properties to reach the desired layout.
simply add this to your code, remember it should be placed inside, it will make a stylish button with shadow. `<RNCamera> </RNCamera>` ``` <RNCamera> <View style={{position: 'absolute', bottom: "50%", right: "30%",}}> <TouchableOpacity style={{ borderWidth:1, borderColor:'#4f83cc', alignItems:'center', justifyContent:'center', width:"180%", height:"180%", backgroundColor:'#fff', borderRadius:100, shadowOpacity:1, shadowRadius:1, shadowColor:"#414685", shadowOffset: { width: 1, height: 5.5, }, elevation: 6, }} onPress={()=>{Alert.alert('hellowworld')}} > <Text>hello World</Text> </TouchableOpacity> </View> </RNCamera> ``` here you can see the output, it will be on the top of the camera. [![enter image description here](https://i.stack.imgur.com/FuftO.png)](https://i.stack.imgur.com/FuftO.png)
Question: I have a model called a `Statement` that belongs to a `Member`. Given an array of members, I want to create a query that will return the **most recent** statement for each of those members (preferably in one nice clean query). I thought I might be able to achieve this using `group` and `order` - something like: ``` # @members is already in an array @statements = Statement.all( :conditions => ["member_id IN(?)", @members.collect{|m| m.id}], :group => :member_id, :order => "created_at DESC" ) ``` But unfortunately the above always returns the *oldest* statement for each member. I've tried swapping the order option round, but alas it always returns the oldest statement of the group rather than the most recent. I'm guessing `group_by` isn't the way to achieve this - so how do I achieve it? PS - any non Ruby/Rails people reading this, if you know how to achieve this in raw MySQL, then fire away. Answer:
In MySQL directly, you need a sub-query that returns the maximum `created_at` value for each member, which can then be joined back to the `Statement` table to retrieve the rest of the row. ``` SELECT * FROM Statement s JOIN (SELECT member_id, MAX(created_at) max_created_at FROM Statement GROUP BY member_id ) latest ON s.member_id = latest.member_id AND s.created_at = latest.max_created_at ```
If you are using Rails 3 I would recommend taking a look at the new ActiveRecord query syntax. There is an overview at <http://guides.rubyonrails.org/active_record_querying.html> I am pretty certain you could do what you are trying to do here without writing any SQL. There is an example in the "Grouping" section on that page which looks similar to what you are trying to do.
Question: When an EXE raised an exception message like "access violation at address XXXXXXXX...", the address XXXXXXXX is a hex value, and we can get the source code line number that caused the exception, by looking at the map file. Details below ([by madshi at EE](http://www.experts-exchange.com/Programming/Languages/Pascal/Delphi/Q_21201209.html#a12542996)): > > you need to substract the image base, > which is most probably $400000. > Furthermore you need to substract the > "base of code" address, which is > stored in the image nt headers of each > module (exe/dll). It's usually $1000. > You can check which value it has by > using the freeware tool "PEProwse > Pro". It's the field "Base Of Code" in > the "Details" of the "Optional > Header". You'll also find the image > base address there. > > > **My question is**: How to get the source line number for a **DLL**? Does the same calculation apply? Thanks! Note 1: the map file is generated by Delphi and I'm not sure if this matters. Note 2: I've been using JCL DEBUG but it couldn't catch the exception which seems occurred at the startup of the DLL (an Office add-in, actually). Answer:
Same calculations apply, with the following note: instead of image base address of EXE you'll need to take actual address where DLL had been loaded. Base of code for a DLL should taken in the same manner as for EXE (stored in PE's `IMAGE_OPTIONAL_HEADER`). Btw, EXE and DLL are actually the same thing from the point of view of PE format.
Two binaries can not be loaded at the same address. So the image base address stored in the DLL/EXE is only a suggestion for which the binary is optimized. Where the binary actually gets loaded into memory depends on many factors, like other binaries loaded in the process first, Windows version, injected 3rd party dlls, etc. As suggested you can use a debugger or a tool like Process Explorer to find out at what address the DLL is loaded at that time. Or if you want to know from code you can by getting the HInstance or HModule from the DLL [since both are the same](https://blogs.msdn.com/b/oldnewthing/archive/2004/06/14/155107.aspx) and are the address in memory the DLL is loaded at. Delphi gets you the HModule for other DLL's through the GetModuleHandle method. Newer Delphi versions also have other methods to find HInstance.
Question: I am looking for a textbox control that suggests words as the user types, similar to SuggestAppend for textboxes in winforms, except for WPF. I have looked around on the WPFToolkit and haven't really found anything that fits my needs. Thanks. Answer:
Declare an enum AutoCompleteMode too with value(Append, None,SuggestAppend,Suggest) ``` public enum AutoCompleteMode ``` Create an custom UserControl with TextBox and ItemControls. Handle the **KeyDown** event of TextBox. Popup an custom List to show the suggestion list(ItemControls in here). Then Handle the selection of the ItemControls. Can custom the style of hte ItemControls's ItemTemplate. Apply the AutoCOmpleteMode in this UserControl and handle the Enum changed in the code behind.
WpfToolkit contains [AutoCompleteBox](https://github.com/dotnetprojects/WpfToolkit/blob/master/WpfToolkit/Input/AutoCompleteBox/System/Windows/Controls/AutoCompleteBox.cs) that you can use for auto suggest feature. You will have to define a collection for items to suggest (SuggestionItems) and set it as ItemsSource on AutoCompleteBox control. ``` <someNamespaceAlias:AutoCompleteBox ItemsSource="{Binding SuggestionItems}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" /> ```
Question: Hey I have a .NET .aspx page that I would like to run every hour or so whats the best way to do this ? I assume it will have to open a browser window to do so and if possible that it closes the window after. EDIT : I have access over all features on the server Answer:
**Option 1**: The cleanest solution would be to write a Windows application that does the work (instead of an aspx page) and schedule this application on the server using the Windows Task Scheduler. This has a few advantages over the aspx approach: * You can use the features of the Windows Task Scheduler (event log entries if the task could not be started, see the time of the last run, run the task in the context of a specific user, etc.). * You don't need to "simulate" a web browser call. * Your page cannot be "accidentally" called by a web user or a search engine. * It's conceptually cleaner: The main purpose of a web page is to provide information to the client, not to trigger an action on the server. Of course, there are drawbacks as well: * You have two Visual Studio projects instead of one. * You might need to factor common code into a shared class library. (This can also be seen as an advantage.) * Your system becomes more complex and, thus, potentially harder to maintain. --- **Option 2**: If you need to stick to an aspx page, the easiest solution is probably to call the page via a command-line web client in a scheduled task. Since Windows does not provide any built-in command-line web clients, you'd have to download one such as `wget` or [`curl`](http://curl.haxx.se/). This related SO question contains the necessary command-line syntax: * [Scheduled Tasks for ASP.NET](https://stackoverflow.com/questions/2927330/scheduled-tasks-for-asp-net/2927375#2927375)
use this sample to schedule a task in asp.net : [enter link description here](http://www.codeproject.com/KB/aspnet/ASPNETService.aspx) then you need to create `Hit.aspx` page witch will do what you want. then you should call that page every time (using `WebClient` class) the task execution time elapsed!
Question: Hey I have a .NET .aspx page that I would like to run every hour or so whats the best way to do this ? I assume it will have to open a browser window to do so and if possible that it closes the window after. EDIT : I have access over all features on the server Answer:
**Option 1**: The cleanest solution would be to write a Windows application that does the work (instead of an aspx page) and schedule this application on the server using the Windows Task Scheduler. This has a few advantages over the aspx approach: * You can use the features of the Windows Task Scheduler (event log entries if the task could not be started, see the time of the last run, run the task in the context of a specific user, etc.). * You don't need to "simulate" a web browser call. * Your page cannot be "accidentally" called by a web user or a search engine. * It's conceptually cleaner: The main purpose of a web page is to provide information to the client, not to trigger an action on the server. Of course, there are drawbacks as well: * You have two Visual Studio projects instead of one. * You might need to factor common code into a shared class library. (This can also be seen as an advantage.) * Your system becomes more complex and, thus, potentially harder to maintain. --- **Option 2**: If you need to stick to an aspx page, the easiest solution is probably to call the page via a command-line web client in a scheduled task. Since Windows does not provide any built-in command-line web clients, you'd have to download one such as `wget` or [`curl`](http://curl.haxx.se/). This related SO question contains the necessary command-line syntax: * [Scheduled Tasks for ASP.NET](https://stackoverflow.com/questions/2927330/scheduled-tasks-for-asp-net/2927375#2927375)
You can use <http://quartznet.sourceforge.net/> Quartz Job Scheduler. With Quartz.net you can write a job which will request your web page with interval you choose. or alternatively you can write an windows service which will request that web page.
Question: I can create a [Guava `ImmutableList`](https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/ImmutableList.html) with the `of` method, and will get the correct generic type based on the passed objects: ``` Foo foo = new Foo(); ImmutableList.of(foo); ``` However, [the `of` method with no parameters](https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/ImmutableList.html#of--) cannot infer the generic type and creates an `ImmutableList<Object>`. How can I create an empty `ImmutableList` to satisfy `List<Foo>`? Answer:
If you assign the created list to a variable, you don't have to do anything: ``` ImmutableList<Foo> list = ImmutableList.of(); ``` In other cases where the type can't be inferred, you have to write `ImmutableList.<Foo>of()` as @zigg says.
`ImmutableList.<Foo>of()` will create an empty `ImmutableList` with generic type `Foo`. Though [the compiler can infer the generic type](https://stackoverflow.com/a/29776623/722332) in some circumstances, like assignment to a variable, you'll need to use this format (as I did) when you're providing the value for a function argument.
Question: I can create a [Guava `ImmutableList`](https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/ImmutableList.html) with the `of` method, and will get the correct generic type based on the passed objects: ``` Foo foo = new Foo(); ImmutableList.of(foo); ``` However, [the `of` method with no parameters](https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/ImmutableList.html#of--) cannot infer the generic type and creates an `ImmutableList<Object>`. How can I create an empty `ImmutableList` to satisfy `List<Foo>`? Answer:
`ImmutableList.<Foo>of()` will create an empty `ImmutableList` with generic type `Foo`. Though [the compiler can infer the generic type](https://stackoverflow.com/a/29776623/722332) in some circumstances, like assignment to a variable, you'll need to use this format (as I did) when you're providing the value for a function argument.
Since Java 8 the compiler is much more clever and can figure out the type parameters parameters in more situations. Example: ``` void test(List<String> l) { ... } // Type checks in Java 8 but not in Java 7 test(ImmutableList.of()); ``` ### Explanation The new thing in Java 8 is that the [target type](https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#target_types) of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference. (Most of the time, one exception is assignments.) In this case the parameter type of `test` will be the target type for `of()`, and the return value type of `of` will get chosen to match that argument type.
Question: I can create a [Guava `ImmutableList`](https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/ImmutableList.html) with the `of` method, and will get the correct generic type based on the passed objects: ``` Foo foo = new Foo(); ImmutableList.of(foo); ``` However, [the `of` method with no parameters](https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/ImmutableList.html#of--) cannot infer the generic type and creates an `ImmutableList<Object>`. How can I create an empty `ImmutableList` to satisfy `List<Foo>`? Answer:
If you assign the created list to a variable, you don't have to do anything: ``` ImmutableList<Foo> list = ImmutableList.of(); ``` In other cases where the type can't be inferred, you have to write `ImmutableList.<Foo>of()` as @zigg says.
Since Java 8 the compiler is much more clever and can figure out the type parameters parameters in more situations. Example: ``` void test(List<String> l) { ... } // Type checks in Java 8 but not in Java 7 test(ImmutableList.of()); ``` ### Explanation The new thing in Java 8 is that the [target type](https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#target_types) of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference. (Most of the time, one exception is assignments.) In this case the parameter type of `test` will be the target type for `of()`, and the return value type of `of` will get chosen to match that argument type.
Question: I am using "ExuberantCtags" also known as "ctags -e", also known as just "etags" and I am trying to understand the TAGS file format which is generated by the etags command, in particular I want to understand line #2 of the TAGS file. [Wikipedia says](http://en.wikipedia.org/wiki/Ctags#Etags_2) that line #2 is described like this: ``` {src_file},{size_of_tag_definition_data_in_bytes} ``` In practical terms though TAGS file line:2 for "foo.c" looks like this ``` foo.c,1683 ``` My quandary is how exactly does it find this number: 1683 I know it is the size of the "tag\_definition" so what I want to know is what is the "tag\_definition"? I have tried looking through the [ctags source code](http://ctags.sourceforge.net/), but perhaps someone better at C than me will have more success figuring this out. Thanks! EDIT #2: ``` ^L^J hello.c,79^J float foo (float x) {^?foo^A3,20^J float bar () {^?bar^A7,59^J int main() {^?main^A11,91^J ``` Alright, so if I understand correctly, "79" refers to the number of bytes in the TAGS file from after 79 down to and including "91^J". Makes perfect sense. Now the numbers 20, 59, 91 in this example wikipedia says refer to the {byte\_offset} What is the {byte\_offset} offset from? Thanks for all the help Ken! Answer:
You can probably use [mcrypt](http://de3.php.net/manual/en/ref.mcrypt.php). But may I ask why you're encrypting with ECB mode at all? Remember the [known problems](http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29) with that?
``` mcrypt_decrypt('rijndael-128', $key, $data, 'ecb'); ``` You will have to manually remove [the padding](http://en.wikipedia.org/wiki/Padding_%28cryptography%29#Byte_padding).
Question: ``` firstLetter = word.charAt(0); lastLetter = word.charAt((word.length()) - 1); noFirstLetter = word.substring(1); newWord = noFirstLetter + firstLetter; if(word.equalsIgnoreCase(newWord)) ``` So im trying to take the first letter of the word and if I take the first letter of the word away and move it to the end it should be equal to the same word. My code here isn't working. For example if the user entered "dresser" if you move the "d" to the end of the word you get the word "dresser" again. That is what im trying to check Answer:
I think what you are trying to do is to remove the first character, and then check if rest of the characters are symmetrical around the center of the word.(OK even it is complicated for me) EG: dresser => (drop d) => resser => (add d to the right) => resserd (read from right to left and it is dresser again). after you drop the first letter: resser (there are even number of letters in the word) ``` r e s s e r |_| |_____| |_________| ``` since they are symmetrical, you can say that that word would be Palindromic if you move D from left to right (or vice versa). The whole thing above could be horribly wrong if I misunderstood your question at the first place. But I assumed, your question was NOT a simple substring question. Cheers.
If you move 'd' to the end of the word "dresser" you get "resserd" which is not equal to "dresser". If you move 'd' to the end and then **reverse** the word then they are equal. So, assuming you consider strings equals even if they are reversed, the code you want would be : ``` boolean testPass = false; if ( word.length()==0 ) testPass = true; else { firstLetter = word.charAt(0); noFirstLetter = word.substring(1); newWord = noFirstLetter + firstLetter; reversed = new StringBuilder(newWord).reverse().toString() if (word.equalsIgnoreCase(newWord) || word.equalsIgnoreCase(reversed)) testPass = true; } if ( testPass ) // Do something ``` Take notice of the important check of word having lenght 0. Otherwise word.charAt(0) will throw an exception.
Question: ``` firstLetter = word.charAt(0); lastLetter = word.charAt((word.length()) - 1); noFirstLetter = word.substring(1); newWord = noFirstLetter + firstLetter; if(word.equalsIgnoreCase(newWord)) ``` So im trying to take the first letter of the word and if I take the first letter of the word away and move it to the end it should be equal to the same word. My code here isn't working. For example if the user entered "dresser" if you move the "d" to the end of the word you get the word "dresser" again. That is what im trying to check Answer:
Okay, so I'm presuming that you want to take a `string`, move it's first index to the end and then reverse the `string`. If you do this to a word such as 'dresser' then you end up with the same value. Something like this could work, currently untested: ``` public StringBuilder reverseWord(String word){ firstLetter = word.charAt(0); //find the first letter noFirstLetter = word.substring(1); //removing the first index newWord = noFirstLetter + firstLetter; //move first index to end return new StringBuilder(newWord).reverse().toString(); //reverse } if(reverseWord("dresser").equals("dresser")){ //do something } ``` Edit: As Jose has pointed out, it is important to check the length of the actual parameter by invoking `length()` on `word`.
If you move 'd' to the end of the word "dresser" you get "resserd" which is not equal to "dresser". If you move 'd' to the end and then **reverse** the word then they are equal. So, assuming you consider strings equals even if they are reversed, the code you want would be : ``` boolean testPass = false; if ( word.length()==0 ) testPass = true; else { firstLetter = word.charAt(0); noFirstLetter = word.substring(1); newWord = noFirstLetter + firstLetter; reversed = new StringBuilder(newWord).reverse().toString() if (word.equalsIgnoreCase(newWord) || word.equalsIgnoreCase(reversed)) testPass = true; } if ( testPass ) // Do something ``` Take notice of the important check of word having lenght 0. Otherwise word.charAt(0) will throw an exception.
Question: I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?. Answer:
``` In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict() Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} ``` Speed comparion (using Wouter's method) ``` In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB')) In [7]: %timeit dict(zip(df.A,df.B)) 1000 loops, best of 3: 1.27 ms per loop In [8]: %timeit pd.Series(df.A.values,index=df.B).to_dict() 1000 loops, best of 3: 987 us per loop ```
I like the Wouter method, however the behaviour with duplicate values might not be what is expected and this scenario is not discussed one way or the other by the OP unfortunately. Wouter, will always choose the last value for each key encountered. So in other words, it will keep overwriting the value for each key. The expected behavior in my mind would be more like [Create a dict using two columns from dataframe with duplicates in one column](https://stackoverflow.com/questions/60085490) where a list is kept for each key. So for the case of keeping duplicates, let me submit `df.groupby('Position')['Letter'].apply(list).to_dict()` (Or perhaps even a set instead of a list)
Question: I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?. Answer:
``` dict (zip(data['position'], data['letter'])) ``` this will give you: ``` {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} ```
I like the Wouter method, however the behaviour with duplicate values might not be what is expected and this scenario is not discussed one way or the other by the OP unfortunately. Wouter, will always choose the last value for each key encountered. So in other words, it will keep overwriting the value for each key. The expected behavior in my mind would be more like [Create a dict using two columns from dataframe with duplicates in one column](https://stackoverflow.com/questions/60085490) where a list is kept for each key. So for the case of keeping duplicates, let me submit `df.groupby('Position')['Letter'].apply(list).to_dict()` (Or perhaps even a set instead of a list)
Question: I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?. Answer:
In Python 3.6 the fastest way is still the WouterOvermeire one. Kikohs' proposal is slower than the other two options. ``` import timeit setup = ''' import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB')) df['A'] = df['A'].apply(chr) ''' timeit.Timer('dict(zip(df.A,df.B))', setup=setup).repeat(7,500) timeit.Timer('pd.Series(df.A.values,index=df.B).to_dict()', setup=setup).repeat(7,500) timeit.Timer('df.set_index("A").to_dict()["B"]', setup=setup).repeat(7,500) ``` Results: ``` 1.1214002349999777 s # WouterOvermeire 1.1922008498571748 s # Jeff 1.7034366211428602 s # Kikohs ```
I like the Wouter method, however the behaviour with duplicate values might not be what is expected and this scenario is not discussed one way or the other by the OP unfortunately. Wouter, will always choose the last value for each key encountered. So in other words, it will keep overwriting the value for each key. The expected behavior in my mind would be more like [Create a dict using two columns from dataframe with duplicates in one column](https://stackoverflow.com/questions/60085490) where a list is kept for each key. So for the case of keeping duplicates, let me submit `df.groupby('Position')['Letter'].apply(list).to_dict()` (Or perhaps even a set instead of a list)
Question: I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?. Answer:
``` dict (zip(data['position'], data['letter'])) ``` this will give you: ``` {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} ```
Here are two other ways tested with the following df. ``` df = pd.DataFrame(np.random.randint(0,10,10000).reshape(5000,2),columns=list('AB')) ``` using `to_records()` ``` dict(df.to_records(index=False)) ``` using `MultiIndex.from_frame()` ``` dict(pd.MultiIndex.from_frame(df)) ``` Time of each. ``` 24.6 ms ± 847 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) 1.86 ms ± 11.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ```
Question: I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?. Answer:
``` In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict() Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} ``` Speed comparion (using Wouter's method) ``` In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB')) In [7]: %timeit dict(zip(df.A,df.B)) 1000 loops, best of 3: 1.27 ms per loop In [8]: %timeit pd.Series(df.A.values,index=df.B).to_dict() 1000 loops, best of 3: 987 us per loop ```
In Python 3.6 the fastest way is still the WouterOvermeire one. Kikohs' proposal is slower than the other two options. ``` import timeit setup = ''' import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB')) df['A'] = df['A'].apply(chr) ''' timeit.Timer('dict(zip(df.A,df.B))', setup=setup).repeat(7,500) timeit.Timer('pd.Series(df.A.values,index=df.B).to_dict()', setup=setup).repeat(7,500) timeit.Timer('df.set_index("A").to_dict()["B"]', setup=setup).repeat(7,500) ``` Results: ``` 1.1214002349999777 s # WouterOvermeire 1.1922008498571748 s # Jeff 1.7034366211428602 s # Kikohs ```
Question: I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?. Answer:
I found a faster way to solve the problem, at least on realistically large datasets using: `df.set_index(KEY).to_dict()[VALUE]` Proof on 50,000 rows: ``` df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB')) df['A'] = df['A'].apply(chr) %timeit dict(zip(df.A,df.B)) %timeit pd.Series(df.A.values,index=df.B).to_dict() %timeit df.set_index('A').to_dict()['B'] ``` Output: ``` 100 loops, best of 3: 7.04 ms per loop # WouterOvermeire 100 loops, best of 3: 9.83 ms per loop # Jeff 100 loops, best of 3: 4.28 ms per loop # Kikohs (me) ```
TL;DR ===== ``` >>> import pandas as pd >>> df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']}) >>> dict(sorted(df.values.tolist())) # Sort of sorted... {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} >>> from collections import OrderedDict >>> OrderedDict(df.values.tolist()) OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]) ``` In Long ======= Explaining solution: `dict(sorted(df.values.tolist()))` Given: ``` df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']}) ``` [out]: ``` Letter Position 0 a 1 1 b 2 2 c 3 3 d 4 4 e 5 ``` Try: ``` # Get the values out to a 2-D numpy array, df.values ``` [out]: ``` array([['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]], dtype=object) ``` Then optionally: ``` # Dump it into a list so that you can sort it using `sorted()` sorted(df.values.tolist()) # Sort by key ``` Or: ``` # Sort by value: from operator import itemgetter sorted(df.values.tolist(), key=itemgetter(1)) ``` [out]: ``` [['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]] ``` Lastly, cast the list of list of 2 elements into a dict. ``` dict(sorted(df.values.tolist())) ``` [out]: ``` {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} ``` --- Related ======= Answering @sbradbio comment: If there are multiple values for a specific key and you would like to keep all of them, it's the not the most efficient but the most intuitive way is: ``` from collections import defaultdict import pandas as pd multivalue_dict = defaultdict(list) df = pd.DataFrame({'Position':[1,2,4,4,4], 'Letter':['a', 'b', 'd', 'e', 'f']}) for idx,row in df.iterrows(): multivalue_dict[row['Position']].append(row['Letter']) ``` [out]: ``` >>> print(multivalue_dict) defaultdict(list, {1: ['a'], 2: ['b'], 4: ['d', 'e', 'f']}) ```
Question: I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?. Answer:
I found a faster way to solve the problem, at least on realistically large datasets using: `df.set_index(KEY).to_dict()[VALUE]` Proof on 50,000 rows: ``` df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB')) df['A'] = df['A'].apply(chr) %timeit dict(zip(df.A,df.B)) %timeit pd.Series(df.A.values,index=df.B).to_dict() %timeit df.set_index('A').to_dict()['B'] ``` Output: ``` 100 loops, best of 3: 7.04 ms per loop # WouterOvermeire 100 loops, best of 3: 9.83 ms per loop # Jeff 100 loops, best of 3: 4.28 ms per loop # Kikohs (me) ```
In Python 3.6 the fastest way is still the WouterOvermeire one. Kikohs' proposal is slower than the other two options. ``` import timeit setup = ''' import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB')) df['A'] = df['A'].apply(chr) ''' timeit.Timer('dict(zip(df.A,df.B))', setup=setup).repeat(7,500) timeit.Timer('pd.Series(df.A.values,index=df.B).to_dict()', setup=setup).repeat(7,500) timeit.Timer('df.set_index("A").to_dict()["B"]', setup=setup).repeat(7,500) ``` Results: ``` 1.1214002349999777 s # WouterOvermeire 1.1922008498571748 s # Jeff 1.7034366211428602 s # Kikohs ```
Question: I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?. Answer:
``` In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict() Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} ``` Speed comparion (using Wouter's method) ``` In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB')) In [7]: %timeit dict(zip(df.A,df.B)) 1000 loops, best of 3: 1.27 ms per loop In [8]: %timeit pd.Series(df.A.values,index=df.B).to_dict() 1000 loops, best of 3: 987 us per loop ```
Here are two other ways tested with the following df. ``` df = pd.DataFrame(np.random.randint(0,10,10000).reshape(5000,2),columns=list('AB')) ``` using `to_records()` ``` dict(df.to_records(index=False)) ``` using `MultiIndex.from_frame()` ``` dict(pd.MultiIndex.from_frame(df)) ``` Time of each. ``` 24.6 ms ± 847 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) 1.86 ms ± 11.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ```
Question: I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?. Answer:
TL;DR ===== ``` >>> import pandas as pd >>> df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']}) >>> dict(sorted(df.values.tolist())) # Sort of sorted... {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} >>> from collections import OrderedDict >>> OrderedDict(df.values.tolist()) OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]) ``` In Long ======= Explaining solution: `dict(sorted(df.values.tolist()))` Given: ``` df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']}) ``` [out]: ``` Letter Position 0 a 1 1 b 2 2 c 3 3 d 4 4 e 5 ``` Try: ``` # Get the values out to a 2-D numpy array, df.values ``` [out]: ``` array([['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]], dtype=object) ``` Then optionally: ``` # Dump it into a list so that you can sort it using `sorted()` sorted(df.values.tolist()) # Sort by key ``` Or: ``` # Sort by value: from operator import itemgetter sorted(df.values.tolist(), key=itemgetter(1)) ``` [out]: ``` [['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]] ``` Lastly, cast the list of list of 2 elements into a dict. ``` dict(sorted(df.values.tolist())) ``` [out]: ``` {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} ``` --- Related ======= Answering @sbradbio comment: If there are multiple values for a specific key and you would like to keep all of them, it's the not the most efficient but the most intuitive way is: ``` from collections import defaultdict import pandas as pd multivalue_dict = defaultdict(list) df = pd.DataFrame({'Position':[1,2,4,4,4], 'Letter':['a', 'b', 'd', 'e', 'f']}) for idx,row in df.iterrows(): multivalue_dict[row['Position']].append(row['Letter']) ``` [out]: ``` >>> print(multivalue_dict) defaultdict(list, {1: ['a'], 2: ['b'], 4: ['d', 'e', 'f']}) ```
Here are two other ways tested with the following df. ``` df = pd.DataFrame(np.random.randint(0,10,10000).reshape(5000,2),columns=list('AB')) ``` using `to_records()` ``` dict(df.to_records(index=False)) ``` using `MultiIndex.from_frame()` ``` dict(pd.MultiIndex.from_frame(df)) ``` Time of each. ``` 24.6 ms ± 847 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) 1.86 ms ± 11.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ```
Question: I have list of Active Directory Users's Guid, I need to load a set of properties of those users for a specific reporting. To do this, if we make a bind for each Guid, then it will be a costly one. Whether with DirectorySearcher, can we provide multiple Guid(say 1000) as filter and load the properties?. Answer:
I found a faster way to solve the problem, at least on realistically large datasets using: `df.set_index(KEY).to_dict()[VALUE]` Proof on 50,000 rows: ``` df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB')) df['A'] = df['A'].apply(chr) %timeit dict(zip(df.A,df.B)) %timeit pd.Series(df.A.values,index=df.B).to_dict() %timeit df.set_index('A').to_dict()['B'] ``` Output: ``` 100 loops, best of 3: 7.04 ms per loop # WouterOvermeire 100 loops, best of 3: 9.83 ms per loop # Jeff 100 loops, best of 3: 4.28 ms per loop # Kikohs (me) ```
``` dict (zip(data['position'], data['letter'])) ``` this will give you: ``` {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} ```
Question: I'm trying to select a node's value from XML in a table in MySQL/MariaDB Acoording to the MySQL docs, `following-sibling` is not supported as an XPath axis in MySQL. Is there an alternative? Docs: <http://dev.mysql.com/doc/refman/5.1/en/xml-functions.html#function_extractvalue> My XML structure looks something like: ``` <fields> <record> <id>10</id> <value>Foo</value> </record> <record> <id>20</id> <value>Bar</value> </record> </fields> ``` I need to find the record with ID 10, and get the text in `<value></value>`. Valid XPath would be `/fields/record/id[text()=10]/following-sibling::value/text()` which would return `Foo` What are my options? Thanks! Answer:
In this simple case you do not need the `following-sibling`. Try this instead: ``` /fields/record[id[text()=10]]/value/text() ``` Using the tag `id` inside the brackets leaves your context at `record` so that the following slash descends to the corresponding sibling of `id` (having the same parent as `id`).
I have this XML: ``` <List> <Attribute> <Id>Name</Id> <Value>JOHN</Value> </Attribute> </List> ``` Below is query: > > SELECT EXTRACTVALUE(xml, > "List/Attribute[Id[text()='NAME']]/Value") > FROM xx; > > > But getting error as Unknown column 'List/Attribute[Id[text()='COUNTRY']]/Value' in 'field list'
Question: Actually, I know that $\int\_0^n \lfloor t \rfloor dt$ is $\frac{n(n-1)}{2}$. But I can't solve this simple problem. Can anybody help me? P.S. I'm seventeen, I'm studying in last year of high school, and I'm preparing for the national exams. Answer:
\begin{eqnarray\*} \int\_0^n 2x \lfloor x \rfloor dx = \sum\_{i=0}^{n-1} i \underbrace{\int\_{i}^{i+1} 2x \,dx}\_{x^2 \mid\_i^{i+1}=2i+1} = \underbrace{\sum\_{i=0}^{n-1} i (2i+1)}\_{\text{using} \sum\_{i=0}^{n-1} i^2=\frac{n(n-1)(2n-1)}{6} } = \frac{(n-1)n(n+1)}{3}. \end{eqnarray\*}
**hint:** $\displaystyle \int\_{0}^n = \displaystyle \int\_{0}^1 +\displaystyle \int\_{1}^2 +...+\displaystyle \int\_{n-1}^n$
Question: If $\sum\_{n=1}^{\infty}a\_n$ converge, then $\sum\_{n=1}^{\infty}\sqrt[4]{a\_{n}^{5}}=\underset{n=1}{\overset{\infty}{\sum}}a\_{n}^{\frac{5}{4}}$ converge? Please verify answer below. Answer:
Yes. Because $\sum a\_n$ converges, we know that the limit $\lim a\_n = 0$, by the Divergence Test. This means that $\exists N, \forall n > N, a\_n <1 $. It stands to reason then that $a\_n^{5/4} \le a\_n$ for all such $n>N$. By Direct Comparison, then, $\sum a\_n^{5/4}$ also converges. We cannot say $\sum a\_n^{5/4} < \sum a\_n$. Someone said that but it is untrue. It all depends on the front-end behavior. If for the first $N$ terms $a\_n^{5/4}$ is sufficiently larger than $a\_n$ then the inequality of the actual sum may be reversed. --- It doesnt matter if for any terms $a\_n<0$. If a term is odd then $a\_n^5$ is still odd. And the principle fourth root $a\_n^{5/4}$ is going to be a complex number where $a\_n^{5/4} = |a\_n|^{5/4} \frac{\sqrt{2}+i\sqrt{2}}{2}$ for all negative $a\_n$ The principle fourth root $a\_n^{5/4}$ for positive $a\_n$ is still positive and real. Simply break the series apart into two separate series of positive and negative $a\_n$ terms. We know that $\sum\_{a\_n>0} a\_n^{5/4}$ is going to converge as per the first part of this proof. It has fewer terms and therefore converges to a smaller sum. For the series $\sum\_{a\_n<0} a\_n^{5/4}$ we get the final sum $\frac{\sqrt{2}+i\sqrt{2}}{2} \sum\_{a\_n<0} |a\_n|^{5/4} $. Notice the sum is still going to be convergent as per the first part of this proof, but there is a complex scalar that was factored out. Thus, even for a series containing negative $a\_n$ terms, the sum $\sum a\_n^{5/4}$ is simply going to be the sum $\left(\sum\_{a\_n>0} a\_n^{5/4}\right) + \left(\frac{\sqrt{2}+i\sqrt{2}}{2} \sum\_{a\_n<0} |a\_n|^{5/4}\right) $ Each individual series is now a series of positive terms, each containing fewer terms than the original series and therefore each converges to a smaller sum. --- **Disclaimer** Im no expert in infinite series. They are not exactly intuitive. The problem is infinitely more complicated if you let $a\_n$ take any complex value.
Because $\sum\_{n=1}^{\infty}a\_{n}$ converge, then $a\_n\rightarrow0$, so for big $n$: $a\_{n}<1$, which implies $$\sum\_{n=1}^{\infty}a\_{n}^{\frac{5}{4}}<\sum\_{n=0}^{\infty}a\_{n}$$ so it's also converge
Question: It is my developed project with target API 23. Now I'm using Studio 2.1.3 When I am trying to open this project the error show me like `Error:failed to find Build Tools revision 24.0.0 rc2 Install Build Tools 24.0.0 rc2 and sync project` But when I try to install, then a error message shown. It was a big project, I have to run it. How can I sync it and run it properly? Please help me, Thanks in advance.. Screenshot 1: this is the error message [![enter image description here](https://i.stack.imgur.com/29uSF.png)](https://i.stack.imgur.com/29uSF.png) Screenshot 2: when i click to install and sync then this error message has appeared [![enter image description here](https://i.stack.imgur.com/OFx3n.png)](https://i.stack.imgur.com/OFx3n.png) Answer:
Update the `android-sdk` tools to the newest version: `24.0.2` Change your Android Support libraries version like `appcompat` from `23.x.x` version to `24.2.0` If you would any problem with updating dependencies, check: <https://developer.android.com/studio/intro/update.html#sdk-manager> **Tip:** Try to avoid use in your project `alpha`,`preview` or `beta` versions of project dependencies. Hope it will help
Check your connection to google servers.Some countries like Iran should use VPN to connect. Hop it work
Question: It is my developed project with target API 23. Now I'm using Studio 2.1.3 When I am trying to open this project the error show me like `Error:failed to find Build Tools revision 24.0.0 rc2 Install Build Tools 24.0.0 rc2 and sync project` But when I try to install, then a error message shown. It was a big project, I have to run it. How can I sync it and run it properly? Please help me, Thanks in advance.. Screenshot 1: this is the error message [![enter image description here](https://i.stack.imgur.com/29uSF.png)](https://i.stack.imgur.com/29uSF.png) Screenshot 2: when i click to install and sync then this error message has appeared [![enter image description here](https://i.stack.imgur.com/OFx3n.png)](https://i.stack.imgur.com/OFx3n.png) Answer:
Update the `android-sdk` tools to the newest version: `24.0.2` Change your Android Support libraries version like `appcompat` from `23.x.x` version to `24.2.0` If you would any problem with updating dependencies, check: <https://developer.android.com/studio/intro/update.html#sdk-manager> **Tip:** Try to avoid use in your project `alpha`,`preview` or `beta` versions of project dependencies. Hope it will help
Go to build.gradle(Module:app) and update the `buildToolsVersion '24.0.0 rc2'` to `buildToolsVersion '24.0.0'` or to the latest version
Question: It is my developed project with target API 23. Now I'm using Studio 2.1.3 When I am trying to open this project the error show me like `Error:failed to find Build Tools revision 24.0.0 rc2 Install Build Tools 24.0.0 rc2 and sync project` But when I try to install, then a error message shown. It was a big project, I have to run it. How can I sync it and run it properly? Please help me, Thanks in advance.. Screenshot 1: this is the error message [![enter image description here](https://i.stack.imgur.com/29uSF.png)](https://i.stack.imgur.com/29uSF.png) Screenshot 2: when i click to install and sync then this error message has appeared [![enter image description here](https://i.stack.imgur.com/OFx3n.png)](https://i.stack.imgur.com/OFx3n.png) Answer:
At the top of your *module's* `build.gradle` file there's a specification which build tools the module uses. Fix it to latest. ``` buildToolsVersion "24.0.2" ```
Check your connection to google servers.Some countries like Iran should use VPN to connect. Hop it work
Question: It is my developed project with target API 23. Now I'm using Studio 2.1.3 When I am trying to open this project the error show me like `Error:failed to find Build Tools revision 24.0.0 rc2 Install Build Tools 24.0.0 rc2 and sync project` But when I try to install, then a error message shown. It was a big project, I have to run it. How can I sync it and run it properly? Please help me, Thanks in advance.. Screenshot 1: this is the error message [![enter image description here](https://i.stack.imgur.com/29uSF.png)](https://i.stack.imgur.com/29uSF.png) Screenshot 2: when i click to install and sync then this error message has appeared [![enter image description here](https://i.stack.imgur.com/OFx3n.png)](https://i.stack.imgur.com/OFx3n.png) Answer:
At the top of your *module's* `build.gradle` file there's a specification which build tools the module uses. Fix it to latest. ``` buildToolsVersion "24.0.2" ```
Go to build.gradle(Module:app) and update the `buildToolsVersion '24.0.0 rc2'` to `buildToolsVersion '24.0.0'` or to the latest version
Question: The way I understand the definition of a combination of a set is that, without repetition,for example, the combination of the set $\{1,2\}$ would be $(1,2)$, and not $(1,1)$, $(1,2)$ and $(2,2)$ because I thought I read that each element has to be unique. Is this the case? Also, What is the combination of a set that has only one element? like $\{2\}$ ? the empty set? or is it $(2,2)$ which would to violate the unique property, if uniqueness actually is a constraint. I'm not sure if it is or not because the web doesn't cover the topic well in a 'non mathematician can understand it' way. Answer:
$$\int\frac{u}{\left(a^2+u^2\right)^{\frac{3}{2}}}\space\text{d}u=$$ --- Substitute $s=a^2+u^2$ and $\text{d}s=2u\space\text{d}u$: --- $$\frac{1}{2}\int\frac{1}{s^{\frac{3}{2}}}\space\text{d}s=\frac{1}{2}\int s^{-\frac{3}{2}}\space\text{d}s=\frac{1}{2}\cdot-\frac{2}{\sqrt{s}}+\text{C}=-\frac{1}{\sqrt{a^2+u^2}}+\text{C}$$
Let $w=$ some function of $u$ for which $dw = u\,du$.
Question: The way I understand the definition of a combination of a set is that, without repetition,for example, the combination of the set $\{1,2\}$ would be $(1,2)$, and not $(1,1)$, $(1,2)$ and $(2,2)$ because I thought I read that each element has to be unique. Is this the case? Also, What is the combination of a set that has only one element? like $\{2\}$ ? the empty set? or is it $(2,2)$ which would to violate the unique property, if uniqueness actually is a constraint. I'm not sure if it is or not because the web doesn't cover the topic well in a 'non mathematician can understand it' way. Answer:
Let $w=$ some function of $u$ for which $dw = u\,du$.
Besides the other answers, I would like to expose another way of doing it: $$\int \dfrac{x}{(a^2+x^2)^{3/2}} dx=-2\int \dfrac{1}{(a^2+x^2)^{1/4}}\cdot \dfrac {\dfrac{-x}{2} (a^2+x^2)^{-3/4}}{(a^2+x^2)^{1/2}} \, dx$$ We realise now that the second factor is the derivative of the first, so we use $f(x)=x$ and $g(x)=\dfrac{1}{(a^2+x^2)^{1/4}}$, to get $\int u$ $du= \dfrac{u^2}{2}$. Don't forget to multiply by the -2, by which we get $-u^2=-\dfrac{1}{(a^2+x^2)^{1/2}}$. Although I think this way to proceed is more intrincate than the other answers, it has the advantage of being generalizable: If $R, l \in \mathbb{R}$, $$\int \dfrac{x}{(R+x^2)^l} \, dx=\int \dfrac{1}{(R+x^2)^p}\cdot \dfrac{x}{(R+x^2)^{p+1}} \, dx$$ (here $p=\dfrac{l-1}{2}$) $$=\dfrac{-1}{2p} \int \dfrac{1}{(R+x^2)^{p}} \cdot \dfrac{-2px(R+x^2)^{p-1}}{(R+x^2)^{2p}} \, dx =\dfrac{-1}{2p} \cdot \dfrac{u^2}{2}=\dfrac{-1}{4p (R+x^2)^{2p}}$$ Recalling that $l=2p+1$, we finally get: $\dfrac{1}{(2-2l)(R+x^2)^{l-1}} + \text{Constant}$. Edit: I changed the $u$ of the OP by $x$ only for a matter of comfort.
Question: The way I understand the definition of a combination of a set is that, without repetition,for example, the combination of the set $\{1,2\}$ would be $(1,2)$, and not $(1,1)$, $(1,2)$ and $(2,2)$ because I thought I read that each element has to be unique. Is this the case? Also, What is the combination of a set that has only one element? like $\{2\}$ ? the empty set? or is it $(2,2)$ which would to violate the unique property, if uniqueness actually is a constraint. I'm not sure if it is or not because the web doesn't cover the topic well in a 'non mathematician can understand it' way. Answer:
Let $w=$ some function of $u$ for which $dw = u\,du$.
You can take the solution as I've presented [here](https://math.stackexchange.com/questions/3057298/solving-used-real-based-methods-int-0x-fractk-lefttn-a-rightm-d): \begin{equation} \int\_0^x \frac{t^k}{\left(t^n + a\right)^m}\:dt= \frac{1}{n}a^{\frac{k + 1}{n} - m} \left[B\left(m - \frac{k + 1}{n}, \frac{k + 1}{n}\right) - B\left(m - \frac{k + 1}{n}, \frac{k + 1}{n}, \frac{1}{1 + ax^n} \right)\right] \end{equation} Here $a$ is $a^2$, $k = 1$, $m = \frac{3}{2}$, thus: \begin{align} \int\_0^x \frac{t}{\left(t^{2} + a^{2}\right)^{\frac{3}{2}}}\:dt &= \frac{1}{2}\left(a^2\right)^{\frac{1 + 1}{2} - \frac{3}{2}} \left[B\left(\frac{3}{2} - \frac{1 + 1}{2}, \frac{1 + 1}{2}\right) - B\left(\frac{3}{2} - \frac{1 + 1}{2}, \frac{1 + 1}{2}, \frac{1}{1 + a^2x^2} \right)\right] \\ &= \frac{1}{\left|a\right|}\left[B\left(\frac{1}{2}, 1\right) - B\left(\frac{1}{2},1, \frac{1}{1 + a^2x^2} \right) \right] \end{align} Using the relationship between the [Beta and the Gamma function](https://en.wikipedia.org/wiki/Beta_function#Relationship_between_gamma_function_and_beta_function) we find that: \begin{equation} B\left(\frac{1}{2},1 \right) = \frac{\Gamma\left(\frac{1}{2} \right)\Gamma(1)}{\Gamma\left(1 + \frac{3}{2}\right)} = \frac{\Gamma\left(\frac{1}{2} \right)\Gamma(1)}{\frac{1}{2}\Gamma\left(\frac{1}{2}\right)} = 2\Gamma(1) = 2 \end{equation} Thus, \begin{equation} \int\_0^x \frac{t}{\left(t^{2} + a^{2}\right)^{\frac{3}{2}}}\:dt = \frac{1}{\left|a\right|}\left[2 - B\left(\frac{1}{2},1, \frac{1}{1 + a^2x^2} \right) \right] \end{equation}
Question: The way I understand the definition of a combination of a set is that, without repetition,for example, the combination of the set $\{1,2\}$ would be $(1,2)$, and not $(1,1)$, $(1,2)$ and $(2,2)$ because I thought I read that each element has to be unique. Is this the case? Also, What is the combination of a set that has only one element? like $\{2\}$ ? the empty set? or is it $(2,2)$ which would to violate the unique property, if uniqueness actually is a constraint. I'm not sure if it is or not because the web doesn't cover the topic well in a 'non mathematician can understand it' way. Answer:
$$\int\frac{u}{\left(a^2+u^2\right)^{\frac{3}{2}}}\space\text{d}u=$$ --- Substitute $s=a^2+u^2$ and $\text{d}s=2u\space\text{d}u$: --- $$\frac{1}{2}\int\frac{1}{s^{\frac{3}{2}}}\space\text{d}s=\frac{1}{2}\int s^{-\frac{3}{2}}\space\text{d}s=\frac{1}{2}\cdot-\frac{2}{\sqrt{s}}+\text{C}=-\frac{1}{\sqrt{a^2+u^2}}+\text{C}$$
Besides the other answers, I would like to expose another way of doing it: $$\int \dfrac{x}{(a^2+x^2)^{3/2}} dx=-2\int \dfrac{1}{(a^2+x^2)^{1/4}}\cdot \dfrac {\dfrac{-x}{2} (a^2+x^2)^{-3/4}}{(a^2+x^2)^{1/2}} \, dx$$ We realise now that the second factor is the derivative of the first, so we use $f(x)=x$ and $g(x)=\dfrac{1}{(a^2+x^2)^{1/4}}$, to get $\int u$ $du= \dfrac{u^2}{2}$. Don't forget to multiply by the -2, by which we get $-u^2=-\dfrac{1}{(a^2+x^2)^{1/2}}$. Although I think this way to proceed is more intrincate than the other answers, it has the advantage of being generalizable: If $R, l \in \mathbb{R}$, $$\int \dfrac{x}{(R+x^2)^l} \, dx=\int \dfrac{1}{(R+x^2)^p}\cdot \dfrac{x}{(R+x^2)^{p+1}} \, dx$$ (here $p=\dfrac{l-1}{2}$) $$=\dfrac{-1}{2p} \int \dfrac{1}{(R+x^2)^{p}} \cdot \dfrac{-2px(R+x^2)^{p-1}}{(R+x^2)^{2p}} \, dx =\dfrac{-1}{2p} \cdot \dfrac{u^2}{2}=\dfrac{-1}{4p (R+x^2)^{2p}}$$ Recalling that $l=2p+1$, we finally get: $\dfrac{1}{(2-2l)(R+x^2)^{l-1}} + \text{Constant}$. Edit: I changed the $u$ of the OP by $x$ only for a matter of comfort.
Question: The way I understand the definition of a combination of a set is that, without repetition,for example, the combination of the set $\{1,2\}$ would be $(1,2)$, and not $(1,1)$, $(1,2)$ and $(2,2)$ because I thought I read that each element has to be unique. Is this the case? Also, What is the combination of a set that has only one element? like $\{2\}$ ? the empty set? or is it $(2,2)$ which would to violate the unique property, if uniqueness actually is a constraint. I'm not sure if it is or not because the web doesn't cover the topic well in a 'non mathematician can understand it' way. Answer:
$$\int\frac{u}{\left(a^2+u^2\right)^{\frac{3}{2}}}\space\text{d}u=$$ --- Substitute $s=a^2+u^2$ and $\text{d}s=2u\space\text{d}u$: --- $$\frac{1}{2}\int\frac{1}{s^{\frac{3}{2}}}\space\text{d}s=\frac{1}{2}\int s^{-\frac{3}{2}}\space\text{d}s=\frac{1}{2}\cdot-\frac{2}{\sqrt{s}}+\text{C}=-\frac{1}{\sqrt{a^2+u^2}}+\text{C}$$
You can take the solution as I've presented [here](https://math.stackexchange.com/questions/3057298/solving-used-real-based-methods-int-0x-fractk-lefttn-a-rightm-d): \begin{equation} \int\_0^x \frac{t^k}{\left(t^n + a\right)^m}\:dt= \frac{1}{n}a^{\frac{k + 1}{n} - m} \left[B\left(m - \frac{k + 1}{n}, \frac{k + 1}{n}\right) - B\left(m - \frac{k + 1}{n}, \frac{k + 1}{n}, \frac{1}{1 + ax^n} \right)\right] \end{equation} Here $a$ is $a^2$, $k = 1$, $m = \frac{3}{2}$, thus: \begin{align} \int\_0^x \frac{t}{\left(t^{2} + a^{2}\right)^{\frac{3}{2}}}\:dt &= \frac{1}{2}\left(a^2\right)^{\frac{1 + 1}{2} - \frac{3}{2}} \left[B\left(\frac{3}{2} - \frac{1 + 1}{2}, \frac{1 + 1}{2}\right) - B\left(\frac{3}{2} - \frac{1 + 1}{2}, \frac{1 + 1}{2}, \frac{1}{1 + a^2x^2} \right)\right] \\ &= \frac{1}{\left|a\right|}\left[B\left(\frac{1}{2}, 1\right) - B\left(\frac{1}{2},1, \frac{1}{1 + a^2x^2} \right) \right] \end{align} Using the relationship between the [Beta and the Gamma function](https://en.wikipedia.org/wiki/Beta_function#Relationship_between_gamma_function_and_beta_function) we find that: \begin{equation} B\left(\frac{1}{2},1 \right) = \frac{\Gamma\left(\frac{1}{2} \right)\Gamma(1)}{\Gamma\left(1 + \frac{3}{2}\right)} = \frac{\Gamma\left(\frac{1}{2} \right)\Gamma(1)}{\frac{1}{2}\Gamma\left(\frac{1}{2}\right)} = 2\Gamma(1) = 2 \end{equation} Thus, \begin{equation} \int\_0^x \frac{t}{\left(t^{2} + a^{2}\right)^{\frac{3}{2}}}\:dt = \frac{1}{\left|a\right|}\left[2 - B\left(\frac{1}{2},1, \frac{1}{1 + a^2x^2} \right) \right] \end{equation}
Question: I have the data given below with other lines of data in a huge file to be more specific this is a .json file, I have stripped the whole file except for this one catch. **Data:** * ,"value":["ABC-DE","XYZ-MN"] * ,"value":["MNO-RS"],"sub\_id":01 * "value":"[\"NEW-XYZ\"]"," * ,"value":["ABC-DE","XYZ-MN","MNO-BE","FRS-ND"] I want the data to look like this * ,"value":["ABC-DE,XYZ-MN"]-Changed * ,"value":["MNO-RS"],"sub\_id":01-Unchanged * "value":"[\"NEW-XYZ\"]","-Unchnaged * ,"value":["ABC-DE,XYZ-MN,MNO-BE,FRS-ND"]-Changed So far I have this piece of code however it seems to be replacing the whole files "," with , and not the ones just within [] ``` sed 's/\(\[\|\","\|\]\)/\,/g' testfile_1.txt >testfile_2.txt ``` Any help would be great \*\*Note: Edited fourth condition Cheers. Answer:
That's tougher without the non-greedy matching perl regex offers, but this seems to do it. ``` sed -e 's/\([^\[]*\"[A-Z\-]*\)\",\"\(.*\)/\1,\2/' ```
Thank you for your contributions @clearlight Here is my solution to the problem with multiple occurrences; ``` sed -e ': a' -e 's/\(\[[^]]*\)","/\1,/' -e 't a' testfile_1.txt >testfile_2.txt ``` Using label 'a' till end of label 'a' pseudocode: ``` while (not end of line){ replace "," with ' } ```
Question: I'm trying to create a batch file which asks a user a question with multiple (four) options. The options that the user chooses should trigger the batch file to ignore one of the four options. Lets say that the commands that I would normally want to run is ECHO "A", ECHO "B", ECHO "C", ECHO "D". If the person puts A in, I would want them to still run all the other commands except ECHO "A". Currently the solution i have come up with is the following ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if %choice%==A ( ECHO "B" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==B ( ECHO "A" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==C ( ECHO "A" ECHO "B" ECHO "D" EXIT /b ) else if %choice%==D ( ECHO "A" ECHO "B" ECHO "C" EXIT /b ) ELSE ( ECHO Please select A, B, C or D! EXIT /b ) ``` However as you can imagine, i am using the echo commands as an example/abstraction. The actual commands are longer. It seems more efficient to define the commands under A, B, C and D once and then tell the batch file not to doA, B, C or D depending the users choice. Maybe it's because I started working early today but I cannot think of an easier way to do this right now. So I hope to hear your ideas on how to make this batch script less clogged up. Answer:
Something like this : ``` @echo off setlocal enabledelayedexpansion set "$Command=A B C D" set /p "$choice=Do you want not to do: A, B, C or D? " set "$Command=!$Command:%$choice%=!" for %%a in (!$command!) do echo %%a ```
This should do the trick. After a "CALL" the batch "jumps back" and will do the next step: ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if %choice%==A ( CALL :B CALL :C CALL :D EXIT /b ) else if %choice%==B ( CALL :A CALL :C CALL :D EXIT /b ) else if %choice%==C ( CALL :A CALL :B CALL :D EXIT /b ) else if %choice%==D ( CALL :A CALL :B CALL :C EXIT /b ) ELSE ( ECHO Please select A, B, C or D! EXIT /b ) :A <Function here> GOTO :EOF :B <Function here> GOTO :EOF :C <Function here> GOTO :EOF :D <Function here> GOTO :EOF ```
Question: I'm trying to create a batch file which asks a user a question with multiple (four) options. The options that the user chooses should trigger the batch file to ignore one of the four options. Lets say that the commands that I would normally want to run is ECHO "A", ECHO "B", ECHO "C", ECHO "D". If the person puts A in, I would want them to still run all the other commands except ECHO "A". Currently the solution i have come up with is the following ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if %choice%==A ( ECHO "B" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==B ( ECHO "A" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==C ( ECHO "A" ECHO "B" ECHO "D" EXIT /b ) else if %choice%==D ( ECHO "A" ECHO "B" ECHO "C" EXIT /b ) ELSE ( ECHO Please select A, B, C or D! EXIT /b ) ``` However as you can imagine, i am using the echo commands as an example/abstraction. The actual commands are longer. It seems more efficient to define the commands under A, B, C and D once and then tell the batch file not to doA, B, C or D depending the users choice. Maybe it's because I started working early today but I cannot think of an easier way to do this right now. So I hope to hear your ideas on how to make this batch script less clogged up. Answer:
The idea in this code is that it only skips the one that you choose. ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if "%choice%"=="" ( ECHO Please select A, B, C or D! EXIT /b ) if not %choice%==A ( ECHO "A" ) if not %choice%==B ( ECHO "B" ) if not %choice%==C ( ECHO "C" ) if not %choice%==D ( ECHO "D" ) exit /b ```
Something like this : ``` @echo off setlocal enabledelayedexpansion set "$Command=A B C D" set /p "$choice=Do you want not to do: A, B, C or D? " set "$Command=!$Command:%$choice%=!" for %%a in (!$command!) do echo %%a ```