text
stringlengths
64
81.1k
meta
dict
Q: Why ListList is List> but not List> I have a generic interface interface ListList<E> extends List<List<E>>. For some reasons, I can't cast ListList<? super T> to List<List<? super T>>. Is there any way of doing it and why it doesn't work? By this moment I've already tried the following: Simple assignment, this way I've managed to assign ListList<? super T> to List<? extends List<? super T>> (1), but when I try to assign ListList<? super T> to List<List<? super T>> I get Incompatible types compile-time error (1.1). Explicit type conversion, it doesn't work because of the same Incompatible types compile-time error (2). Casting to raw type ListList, it works (3), but I don't like raw types. Adding all elements from ListList<? super T> to List<? extends List<? super T>>, it works (4), but I need a more general solution which works not only with ListList<E>, but with any generic type. Here is my code: ListList<? super T> var = new ArrayListList<>(); List<? extends List<? super T>> work = var; // (1) List<List<? super T>> notWork = var; // (1.1) List<List<? super T>> explicit = (List<List<? super T>>) var; // (2) List<List<? super T>> raw = (ListList) var; // (3) List<List<? super T>> copy = new ArrayList<>(); // (4) copy.addAll(var); // (4) I've expected ListList<? super T> to be List<List<? super T>>, but it appeared to be List<? extends List<? super T>>. I need to know why it is and how I can cast it to List<List<? super T>> without raw types and copying of elements. A: At first, it looks like these assignments should all succeed, but they don't because of the inner wildcard ? super T. If we remove those wildcards, then all the assignments compile. public static <T> void test() { ListList<T> var = new ArrayListList<>(); List<? extends List<T>> work = var; // Compiles List<List<T>> notWork = var; // Compiles List<List<T>> explicit = (List<List<T>>) var; // Compiles List<List<T>> raw = (ListList) var; // Compiles with warning List<List<T>> copy = new ArrayList<>(); // Compiles copy.addAll(var); // Compiles } I still get the unchecked conversion warning for (3), but they all still compile. At first glance it looks like declaring the interface ListList<E> extends List<List<E>> makes a ListList equivalent to a List of Lists. However what you have done is take a nested type parameter and made it the main type parameter. The reason that that makes a difference is nested wildcards don't perform wildcard capture. A nested wildcard here means "a list of lists of any type matching the bound", but a main-level wildcard here means "a 'listlist' of a specific yet unknown type matching the bound". One cannot add an object that is a supertype of the lower bound to a collection, because the type parameter -- a specific yet unknown type -- may be the actual bound. List<? super Integer> test2 = new ArrayList<>(); test2.add(2); // Compiles; can add 2 if type parameter is Integer, Number, or Object test2.add((Number) 2); // Error - Can't add Number to what could be Integer test2.add(new Object()); // Error - Can't add Object to what could be Integer Because Java's generics are invariant, the types must match exactly when type parameters are involved, so similar cases for ListList all fail to compile. // My assumption of how your ArrayListList is defined. class ArrayListList<E> extends ArrayList<List<E>> implements ListList<E> {} ListList<? super Integer> llOfSuperI = new ArrayListList<>(); llOfSuperI.add(new ArrayList<Integer>()); // capture fails to match Integer llOfSuperI.add(new ArrayList<Number>()); // capture fails to match Number llOfSuperI.add(new ArrayList<Object>()); // capture fails to match Object However, a List of List compiles with all 3 cases. List<List<? super Integer>> lOfLOfSuperI = new ArrayList<>(); lOfLOfSuperI.add(new ArrayList<Integer>()); // no capture; compiles lOfLOfSuperI.add(new ArrayList<Number>()); // no capture; compiles lOfLOfSuperI.add(new ArrayList<Object>()); // no capture; compiles Your ListList is a different type than a List of Lists, but the differing generics behavior of where the type parameter is defined means that there is different generics behavior. This is why you cannot directly assign a ListList<? super T> to a List<List<? super T>> (1.1), and also why you can't cast it (2). You can cast to a raw type to get it to compile (3), but that introduces the possibilities of ClassCastException in future use of the casted object; that is what the warning is about. You can assign it to a List<? extends List<? super T>> (1), introducing another wildcard to capture a subtype relationship, but that introduces a wildcard to be captured; you won't be able to add anything useful to that list. These differences have arisen only because a wildcard introduces wildcard capture and the associated differences. Without using a wildcard, a ListList<E> is equivalent to a List<List<E>> and as shown at the top of this answer, shows no problems compiling the code. If you want all of your sub-lists to use the same exact type parameter, then go ahead and use your ListList interface, but don't use any wildcards. This forces the exact same type parameter for all lists that are added to your ListList, i.e. a ListList<Integer> can only hold List<Integer>s. If you want all of your sub-lists to simply match a wildcard, e.g. contain a List<Number>, List<Integer>, and List<Object> in the same list, then just use a List<List<? super T>> to avoid wildcard capture.
{ "pile_set_name": "StackExchange" }
Q: PersistenceException: Unable to build entity manager factory Caused by ClassNotFound i am using play jpa and encountered this.Searched complete Stackoverflow couldnt find the solution. What i am trying to is As localhost:9000 is hit , HomeController should add a table 'Product' in db "crud" which is already created in mysql. So that would complete my 1st jpa program Here is my Persistence.xml <persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1"> <persistence-unit name="test" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <non-jta-data-source>DefaultDS</non-jta-data-source> <class>models.Product</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/crud"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="toor"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> </properties> </persistence-unit> </persistence> Here is my application.conf play.modules.enabled += "play.filters.csrf.CSRFModule" play.filters.csrf { token { name = "csrfToken" sign = true } cookie { name = null secure = ${play.http.session.secure} httpOnly = false } body.bufferSize = ${play.http.parser.maxMemoryBuffer} bypassCorsTrustedOrigins = true header { name = "Csrf-Token" protectHeaders { Cookie = "*" Authorization = "*" } bypassHeaders {} } method { whiteList = ["GET", "HEAD", "OPTIONS"] blackList = [] } contentType { whiteList = [] blackList = [] } errorHandler = null } play.crypto.secret="VRZV/ppo<t?;NKZN? =PE<N;Yie_G^:sxQrL544YEl[fRsrE<:hMbT;Yj<WhG`bS@" db.default.driver=com.mysql.jdbc.Driver db.default.url="jdbc:mysql://localhost:3306/crud" db.default.user=root db.default.pass=toor db.default.jndiName=DefaultDS jpa.default = test Here is the stacktrace play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution exception[[PersistenceException: Unable to build entity manager factory]] at play.api.http.HttpErrorHandlerExceptions$.throwableToUsefulException(HttpErrorHandler.scala:255) at play.api.http.DefaultHttpErrorHandler.onServerError(HttpErrorHandler.scala:182) at play.core.server.AkkaHttpServer$$anonfun$$nestedInanonfun$executeHandler$1$1.applyOrElse(AkkaHttpServer.scala:252) at play.core.server.AkkaHttpServer$$anonfun$$nestedInanonfun$executeHandler$1$1.applyOrElse(AkkaHttpServer.scala:251) at scala.concurrent.Future.$anonfun$recoverWith$1(Future.scala:412) at scala.concurrent.impl.Promise.$anonfun$transformWith$1(Promise.scala:37) at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60) at play.api.libs.streams.Execution$trampoline$.execute(Execution.scala:70) at scala.concurrent.impl.CallbackRunnable.executeWithValue(Promise.scala:68) at scala.concurrent.impl.Promise$DefaultPromise.dispatchOrAddCallback(Promise.scala:312) Caused by: javax.persistence.PersistenceException: **Unable to build entity manager factory** at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:83) at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:54) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39) at controllers.HomeController.index(HomeController.java:29) at router.Routes$$anonfun$routes$1.$anonfun$applyOrElse$2(Routes.scala:174) at play.core.routing.HandlerInvokerFactory$$anon$3.resultCall(HandlerInvoker.scala:136) at play.core.routing.HandlerInvokerFactory$$anon$3.resultCall(HandlerInvoker.scala:135) at play.core.routing.HandlerInvokerFactory$JavaActionInvokerFactory$$anon$8$$anon$2$$anon$1.invocation(HandlerInvoker.scala:110) at play.core.j.JavaAction$$anon$1.call(JavaAction.scala:78) Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [models.Product] at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:245) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.buildHibernateConfiguration(EntityManagerFactoryBuilderImpl.java:1136) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:853) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850) at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849) at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:75) at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:54) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39) Caused by: java.lang.ClassNotFoundException: **Could not load requested class : models.Product** at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:230) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:348) at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:242) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.buildHibernateConfiguration(EntityManagerFactoryBuilderImpl.java:1136) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:853) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850) at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425) Product.java (The model class) package models; import java.util.ArrayList; import java.util.List; import javax.persistence.*; @Entity public class Product { private static List<Product> products; @Id @GeneratedValue private String ean; @Column private String name; @Column private String description; public Product() { } public Product(String ean, String name, String description) { this.ean = ean; this.name = name; this.description = description; } public String toString() { return String.format("%s -%s", this.ean, this.name); } static { products = new ArrayList<Product>(); products.add(new Product("11111111", "Clip 1", "description 1")); products.add(new Product("22222222", "Clip 2", "description 2")); products.add(new Product("33333333", "Clip 3", "description 3")); products.add(new Product("44444444", "Clip 4", "description 4")); products.add(new Product("55555555", "Clip 5", "description 5")); } public static List<Product> findAll() { return new ArrayList<Product>(products); } public static Product findByEan(String ean) { for (Product candidate : products) { if (candidate.ean.equals(ean)) { return candidate; } } return null; } public static List<Product> findByName(String term) { final List<Product> results = new ArrayList<Product>(); for (Product candidate : products) { if (candidate.name.toLowerCase().contains(term.toLowerCase())) { results.add(candidate); } } return results; } public static boolean remove(Product product) { return products.remove(product); } public void save() { products.remove(findByEan(this.ean)); products.add(this); } public static List<Product> getProducts() { return products; } public String getEan() { return ean; } public void setEan(String ean) { this.ean = ean; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } And Homecontroller.java package controllers; import models.Product; import org.hibernate.jpa.HibernatePersistenceProvider; import play.data.FormFactory; import play.libs.concurrent.HttpExecutionContext; import play.mvc.*; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class HomeController extends Controller { private final FormFactory formFactory; private final HttpExecutionContext ec; @Inject public HomeController(FormFactory formFactory, HttpExecutionContext ec) { this.formFactory = formFactory; this.ec = ec; } public Result index() { //Create a database and add some entries Product newproduct=new Product(); EntityManagerFactory entityManagerFactory= Persistence.createEntityManagerFactory("test"); //Stuck at the above statment EntityManager entityManager=entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); newproduct.setEan("111"); newproduct.setName("Lapy"); newproduct.setDescription("Uska description"); entityManager.persist(newproduct); entityManager.getTransaction().commit(); entityManager.close(); entityManagerFactory.close(); return ok(views.html.index.render("Database created check mysql")); } } EntitymanagerFactory is not able to load model class Product. I have tried various solution on this site otherwise i wouldnt post. A: I found the solution finally , the code of creating entity manager factory and entity manager and beginning the transaction should be written in the constructor of the controller (i have written it in index method of Homecontroller). The database is created in mysql.
{ "pile_set_name": "StackExchange" }
Q: File locked after uploaded by using HttpServletRequest in JAVA Here is the scenario, I try to upload a file, and after I uploaded it, I tried to access that file from the new directory (which i just write to), but I received error message: There was an error opening this document. The file is already open or in use by another application. Below is my coding. try{ conn = this.getConnection(); String getIP = "SELECT IP FROM TABLE WHERE ID='3'"; ps = conn.prepareStatement(getIP); rs = ps.executeQuery(); Part file = request.getPart("upload"); String fileName = extractFileName(request.getPart("upload")); String basePath = "//"+ipAdd+"/ns/"+fileName; File outputFilePath = new File(basePath + fileName); inputStream = file.getInputStream(); outputStream = new FileOutputStream(outputFilePath); int read = 0; final byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } }catch(Exception ex){ ex.printStackTrace(); throw ex; }finally{ if(!conn.isClosed())conn.close(); if(!ps.isClosed())ps.close(); if(!rs.isClosed())rs.close(); inputStream.close(); outputStream.close(); } Is it because that I open the file too quick after I start the upload function? I do realize that after 1/2minutes, I'm able to access the file. Is there anyway to solve this bug? A: In your code above, if an exception occurs whilst closing the JDBC Connection, then none of the other JDBC objects or Streams are closed. The finally block exits at that point. Since Java 7, closing Streams and JDBC objects (Connections, Statements, ResultSets etc) can be done in a proper exception handling framework nice and easily, since they all implement a common interface AutoCloseable So you can write a single close() method and handle the exception inside: public void close(AutoCloseable closeable) { try { closeable.close(); } catch (Exception e) { //Just log the exception. there's not much else you can do, and it probably doesn't //matter. Don't re-throw! } } So when closing your JDBC objects, you can do this in the finally block: close(conn); close(ps); close(rs); close(inputStream); close(outputStream); Now if an exception occurs whilst closing any of the objects, it is handled and the following objects are still closed.
{ "pile_set_name": "StackExchange" }
Q: DataTemplate to Linq I have a ListBox of Dockpanels which display "FieldName:, [_____] (user input textbox)". After the user populates the field, I'm looking for a LINQ way to take the pairs and throw them into a KeyValuePair object. <DataTemplate x:Key="ExtraLoginInfoTemplate"> <DockPanel> <TextBlock Name="CodeID" Text="{Binding Path=ID,Converter={BLL:CodeMarkupExtension}}" /> <TextBox Name="Input"/> </DockPanel> </DataTemplate> <ListBox Name="extraLoginInfoListBox" ItemsSource="{Binding}" ItemTemplate="{StaticResource ExtraLoginInfoTemplate}"/> //codebehind extraLoginInfoListBox.DataContext = cvList; //list of codevalue objects private void submitButton_click(object sender, RoutedEventArgs e) { KeyValuePair<string,string> myInputs = /* ? some linq query to get the data from extraLoginInfoListBox */ } A: You need a property to be bound with your Input textbox to store whatever value was entered by user: <TextBox Name="Input" Text="{Binding Path=IDValue, Mode=TwoWay}" /> And then, you can use following code: var keyValuePairs = cvList.ToDictionary((obj) => obj.ID, (obj) => obj.IDValue);
{ "pile_set_name": "StackExchange" }
Q: delete value from multiple cells in excel it is possible to delete values of multiple selected cells, how can I achieve this with JTable? In this sample code, only the value from one cell is deleted. Multiple cells selected Only one the value in one cell is deleted, and it also enters editing mode after the delete button is pressed which I don't want because it is not doing this in excel. SSCCE import java.awt.BorderLayout; import java.awt.Component; import java.awt.EventQueue; import java.awt.event.KeyEvent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.text.JTextComponent; import java.util.EventObject; public class table extends JFrame{ private static final long serialVersionUID = 1L; private JPanel contentPane; private JTable table; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { table frame = new table(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public table() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); JScrollPane scrollPane = new JScrollPane(); GroupLayout gl_contentPane = new GroupLayout(contentPane); gl_contentPane.setHorizontalGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addGap(2) .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 422, Short.MAX_VALUE)) ); gl_contentPane.setVerticalGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE) ); table = new JTable(){ /** * */ private static final long serialVersionUID = 1L; public boolean editCellAt(int row, int column, EventObject e){ boolean result = super.editCellAt(row, column, e); final Component editor = getEditorComponent(); if (editor == null || !(editor instanceof JTextComponent)) { return result; } if (e instanceof KeyEvent) { ((JTextComponent)editor).selectAll(); } return result; } }; table.setModel(new DefaultTableModel( new Object[][] { {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null} }, new String[] { "New column 1", "New column 2", "New column 3", "New column 4", "New column 5", "New column 6" } )); table.setCellSelectionEnabled(true); scrollPane.setViewportView(table); new PegarExcel(table); contentPane.setLayout(gl_contentPane); } } //********************************************************************************************************* //Clase que se encarga del pegado //********************************************************************************************************* import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.datatransfer.*; import java.util.*; import java.io.IOException; //---------------------------------------------------------------------------------------------------------------------- public class PegarExcel implements ActionListener{ private String rowstring,value; private Clipboard system; private StringSelection stringSelection,stsel; private JTable jTable1 ; //---------------------------------------------------------------------------------------------------------------------- public PegarExcel(JTable myJTable) { jTable1 = myJTable; KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V,ActionEvent.CTRL_MASK,false); jTable1.registerKeyboardAction(this,"Paste",paste,JComponent.WHEN_FOCUSED); system = Toolkit.getDefaultToolkit().getSystemClipboard(); } //---------------------------------------------------------------------------------------------------------------------- public JTable getJTable() { return jTable1; } //---------------------------------------------------------------------------------------------------------------------- public void setJTable(JTable jTable1) { this.jTable1=jTable1; } //---------------------------------------------------------------------------------------------------------------------- void showErrorMessage(String msg){ JOptionPane.showMessageDialog(null, msg,msg,JOptionPane.ERROR_MESSAGE); } //---------------------------------------------------------------------------------------------------------------------- void pasteAction(){ system = Toolkit.getDefaultToolkit().getSystemClipboard(); try{ String data= (String)system.getData(DataFlavor.stringFlavor); if(data==null) { showErrorMessage("No data on clipboard"); return; } int selectCol=jTable1.getSelectedColumn(); int selectRow=jTable1.getSelectedRow(); if(selectCol<0||selectRow<0) { showErrorMessage("Please Select cell"); return; } //devuelve clipboard contenido StringTokenizer st,stTmp; st=new StringTokenizer(data,"\n"); int pasteRows=st.countTokens (); st=new StringTokenizer(st.nextToken ().trim (),"\t"); int pasteCols=st.countTokens (); int marginCols=jTable1.getColumnCount()-selectCol; int marginRows=jTable1.getRowCount()-selectRow; //revisa espacio disponible if(marginCols<pasteCols || marginRows<pasteRows){ //showErrorMessage("La tabla no posee el espacio suficiente para pegar los datos"); //return; } st=new StringTokenizer (data,"\n"); int rowCount=0,colCount; //copia a la tabla while(st.hasMoreTokens()){ stTmp=new StringTokenizer (st.nextToken (),"\t"); colCount=0; DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); System.out.println("model.getRowCount():"+model.getRowCount()); System.out.println("rowCount+selectRow:"+(rowCount+selectRow)); System.out.println("pasteRows:"+(pasteRows)); System.out.println("marginRows:"+(marginRows)); System.out.println("rowCount:"+rowCount); if(rowCount+selectRow>model.getRowCount()-1){ if(0==model.getRowCount()) model.addRow(new Object[]{"","","",1,"MB",10000, true,true,"","",""}); else model.addRow(new Object[]{model.getValueAt(model.getRowCount()-1, 0),"","",1,"MB", 10000, true,true,"","",""}); } while(stTmp.hasMoreTokens ()){ String columnClassName =jTable1.getColumnClass(colCount+selectCol).getName(); if("java.lang.String"==columnClassName) jTable1.setValueAt(stTmp.nextToken(),rowCount+selectRow,colCount+selectCol); else if("java.lang.Integer"==columnClassName) jTable1.setValueAt(Integer.parseInt(stTmp.nextToken()),rowCount+selectRow,colCount+selectCol); else if("java.lang.Boolean"==columnClassName){ boolean bool = Boolean.parseBoolean(stTmp.nextToken()); jTable1.setValueAt(bool,rowCount+selectRow,colCount+selectCol); } else jTable1.setValueAt(stTmp.nextToken(),rowCount+selectRow,colCount+selectCol); System.out.println("columnClassName: "+columnClassName); //jTable1.setValueAt(stTmp.nextToken(),rowCount+selectRow,colCount+selectCol); colCount++; } rowCount++; } } catch(UnsupportedFlavorException uf){ System.out.println ("uf="+uf.getMessage ()); } catch(IOException io){ System.out.println ("io="+io.getMessage ()); } } //---------------------------------------------------------------------------------------------------------------------- public void actionPerformed(ActionEvent e){ if(e.getActionCommand ().compareTo ("Paste")==0){ pasteAction(); return; } } } A: IF I understand your probelm correctly, you need to attach an appropriate Key Binding to handle your requirements... For example, InputMap im = table.getInputMap(); ActionMap am = table.getActionMap(); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete"); am.put("delete", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { System.out.println("DeleteMe..."); } }); Take a look at How to use Key Bindings The reason the table is entering "editor" mode probably comes down to how the default editors are setup. They are accepting Delete as an initiator for the edit mode
{ "pile_set_name": "StackExchange" }
Q: Extract Decimal Value From A String I have 12.00 Php as a string and I'd like to get 12.00 only. Can someone please help me with this? I find it hard to Google for this. TryParse or any conversion doesn't work, or return 0. Dim i As String = "12.00Php" A: Dim regex As Regex = New Regex("\d+.\d+") Dim match As Match = regex.Match("12.00php") If match.Success Then Console.WriteLine(match.Value) End If
{ "pile_set_name": "StackExchange" }
Q: Tiling the square with rectangles of small diagonals For a given integer $k\ge3$, tile the unit square with $k$ rectangles so that the longest of the rectangles' diagonals be as short as possible. Call such a tiling optimal. The solutions are obvious in the easy cases when $k$ is the square of an integer and for a few small values of $k$ only (unpublished). In each of the solved cases, the sides of all rectangles turn out to be rational and their diagonals are equal. Question. In an optimal tiling, must the sides of all rectangles be rational and their diagonals be equal? The analogous question for tiling the $n$-dimensional cube with rectangular boxes can be asked for every $n\ge3$ as well. A: For $k=5$, is this the optimal partition? Rectangle sides $x=\frac{1}{6} \left(3-\sqrt{3}\right) \approx 0.21$ and $1-x$, and (now corrected) all diagonals of length$^2$ of $\frac{2}{3}$, and so length $\sqrt{2/3} \approx 0.816$.       And here is Wlodzimierz's much better partition. Each diagonal has length $\sqrt{2257}/72 \approx 0.660$:       For $k=8$, the $4 \times 2$ partition has diagonal $\sqrt{5}/4 \approx 0.559$. Here is a better, irrational partition, $x=\frac{2}{3}-\frac{\sqrt{\frac{7}{3}}}{6} \approx 0.412$:     A: In a new related question I give a conjecture for the unit square which agrees with the $k=5$ and $k=8$ solutions here. If $s^2 \lt k \lt (s+1)^2$ then the optimal solution has $s$ or $s+1$ rows (depending on which square is closer) each with $s$ or $s+1$ rectangles. More specifically: If $k=s^2+t$ with $0 \lt t \le s$ then the optimal solution has $s$ rows with $s-t$ rows having $s$ rectangles $b \times \frac1s $ and $t$ rows of $s+1$ rectangles $a \times \frac1{s+1}$ where $b^2+\frac{1}{s^2}=a^2+\frac1{(s+1)^2}$ and $(s-t)b+ta=1$ But if $k=s^2+t$ with $s \le t \lt 2s+1$ then the optimal solution has $s+1$ rows with $2s+1-t$ rows having $s$ rectangles $a \times \frac1s $ and $t-s$ rows of $s+1$ rectangles $\frac1{s+1} \times b$ where $a^2+\frac{1}{s^2}=b^2+\frac1{(s+1)^2}$ and $(2s-t+1)a+(t-s)b=1$ Note that in case $k=s^2+s,$ either description gives all rectangles $\frac1s \times \frac1{s+1}.$
{ "pile_set_name": "StackExchange" }
Q: How to recover files from a DVD with command line method? I do not see my DVD, I do not know how to access its corrupted data. What is the way to recover the data with command line? A: from this source get the path of your DVD with blkid #example: blkid /dev/sda1: UUID="4ea68146-163e-4ce6-aeda-4cc2d338c2ed" TYPE="ext4" /dev/sdb1: UUID="e1977a53-b9f4-4c96-9251-84af259d06b4" TYPE="swap" /dev/sdb5: UUID="a85b1b95-c5ce-4557-9ca4-503b1a9ddcc8" TYPE="ext4" /dev/sdb6: UUID="c71a7601-04b8-4808-8f7b-ec967ac967ba" TYPE="ext4" /dev/sr0: LABEL="Disc" TYPE="udf" sdaand sdbare Hard Disk. /dev/sr0 is the DVD then to acces the DVD content, use foremost (Install it with sudo apt-get install foremost) List the content of the DVD (even the erased one): sudo foremost -w /dev/sr0 Processing: /dev/sr0 |********************************************| Result is available with: sudo cat ~/output/audit.txt | more Foremost version 1.5.7 by Jesse Kornblum, Kris Kendall, and Nick Mikus Audit File Foremost started at Tue Jun 14 23:25:18 2016 Invocation: foremost -w /dev/sr0 Output directory: /home/yourlogon/output Configuration file: /etc/foremost.conf ------------------------------------------------------------------ File: /dev/sr0 Start: Tue Jun 14 23:25:18 2016 Length: 4 GB (4573593600 bytes) Num Name (bs=512) Size File Offset Comment 0: 1152.jpg 2 MB 589824 1: 7168.jpg 2 MB 3670016 2: 13292.jpg 2 MB 6805504 3: 19368.jpg 2 MB 9916416 4: 24808.jpg 2 MB 12701696 5: 30464.jpg 2 MB 15597568 6: 35132.jpg 2 MB 17987584 7: 40868.jpg 2 MB 20924416 8: 46916.jpg 2 MB 24020992 ... To recover all data sudo foremost all /dev/sr0 Processing: /dev/sr0 |********************************************| everything is then available in ~/output/ And to make files available sudo chmod -R 777 ~/output/
{ "pile_set_name": "StackExchange" }
Q: Taking JOINed data and making it a row instead of column I'm working on a query that uses a join to pull some information. SELECT ca.item_id ,ca.FIELD_ID ,ca.attr_val ,ca.upd_dtt ,ca.upd_usr ,mf.[ITEM_NAME] FROM contract_attr ca left JOIN mfr mf on ca.attr_val = mf.[ITEM_PK] The Joined data is coming in as another column for the row. I want this column to be another row: 12, 0, PAR PHARMA, current_timestamp, '' How do I do that? A: I think you require Union all to get those records as rows: SELECT ca.item_id ,ca.FIELD_ID ,ca.attr_val ,ca.upd_dtt ,ca.upd_usr FROM contract_attr ca UNION ALL SELECT ... cols along with, --If no columns available in mfr then provide nulls accordingly before providing column name Item_Name ,mf.[ITEM_NAME] FROM mfr mf Both columns list has to be identical order With JOIN to finish question: SELECT ca.item_id ,ca.FIELD_ID ,ca.attr_val ,ca.upd_dtt ,ca.upd_usr FROM contract_attr ca UNION ALL SELECT ca.item_id,9999,mf.[ITEM_NAME],'','' FROM mfr mf JOIN contract_attr ca on ca.attr_val = mf.[ITEM_PK] Order by ca.item_id
{ "pile_set_name": "StackExchange" }
Q: Making css work on all children I have the following HTML which I want which I want to format with some CSS HTML: <div class="photodetail table"> <div class="photodetail row"> <div class="photodetail cell">Date:</div> <div class="photodetail cell">Mar 24 2015 14:23:59</div> </div> <div class="photodetail row"> <div class="photodetail cell">Camera:</div> <div class="photodetail cell">SAMSUNG GT-I9300</div> </div> <div> <-- THIS DIV <div class="photodetail row"> <div class="photodetail cell">Country:</div> <div class="photodetail cell">Australia</div> </div> <div class="photodetail row"> <div class="photodetail cell">City:</div> <div class="photodetail cell">Sydney</div> </div> <div class="photodetail row"> <div class="photodetail cell">Adderss:</div> <div class="photodetail cell">123-125 York St, Sydney NSW 2000, Australia</div> </div> </div> <div class="photodetail row"> <div class="photodetail cell">Id:</div> <div class="photodetail cell">31</div> </div> </div> CSS: .table { display: table; .row { height: 26px; display: table-row; .cell { min-width: 53px; display: table-cell; } } } This works fine for the first two rows, because the row sits directly under the table class. But the next 3 rows are embedded in a which disturbes the picture. How do I fix the css to take this into account? I can not remove the extra - it injected by react. A: Given the above code, you could target it with the below and make the extra div display table .table > div:not(.table) { display: table; } https://jsfiddle.net/ktr6sa6y/1/ I added SCSS in the fiddle, if you are using LESS, it makes no difference in this case. The best way to fix this would be when you inject it, just give it the table class or not inject the div at all. Maybe react need to inject it, I am not sure I have never used react
{ "pile_set_name": "StackExchange" }
Q: How to pass Properties to jar from Powershell? I've been using Powershell-1.0 for command line needs for a while, instead of cmd.exe. Unfortunately, there are still some caveats when using Java. I need to pass a property to a jar, like that: java -jar -Duser.language=en any.jar This line works fine in cmd.exe, but not in Powershell as it searches for another jar: Unable to access jarfile user.language=en Using quotes doesn't help. Is it doable in Powershell-1.0, or do I miss something in Java? A: Take a look at my answer to this question. Note how you can use echoargs.exe to diagnose these sort of problems. Most likely the fix would be to quote the parameter e.g.: java -jar "-Duser.language=en" any.jar You can test that using echoargs (from PowerShell Community Extensions): echoargs -jar "-Duser.language=en" any.jar Arg 0 is <-jar> Arg 1 is <-Duser.language=en> Arg 2 is <any.jar> A: Using quotes works fine for me in PowerShell on Windows 7. java "-Dmy.property=value" -jar myjar.jar Be careful: the jar name must be placed right after -jar, and arguments placed after -jar myjar.jar will be passed to the program inside the jarFile.
{ "pile_set_name": "StackExchange" }
Q: When using SSH, the .bashrc alias on that server is not being read, even tough it is set correclty in .bash_profile and .bashrc I use SSH to login to a remote machine. I can save the alias like so, in .bashrc: alias l='ls -lla' but when I logout and SSH in again, the alias does not exist. It is set properly, however, in .bash_profile and in .bashrc. Why is this happening? Every time I SSH, I have to do . ~/.bashrc and I do not want to do that. What can I do to fix this? A: Check your user shell with getent passwd ${USER} And look at the end. If it is not /bin/bash, run chsh -s /bin/bash If you are a domain-defined user, it is possible your default shell is /bin/sh which might be a symlink to bash, but will not interpret your ~/.bashrc.
{ "pile_set_name": "StackExchange" }
Q: "Watch Your Step" isn't working I have been hit by dart traps hundreds of times since 1.3, not to mention boulder and bomb traps. They were naturally generated, and on separate worlds and characters. I have had no problem getting the other achievements (I haven't encountered any bugs), and yet I cannot seem to get this achievement (Watch Your Step). How can I get the 'Watch your Step' achievement? EDIT: Okay, so funny story, the day after I posted this, I died to a plunger trap, and got the achivement! Go figure... A: In order to get the achievement the trap you trigger needs to kill you, just getting hit by it isn't enough.
{ "pile_set_name": "StackExchange" }
Q: istio ingress 404 on docker desktop I have been trying to run a local cluster on kubernetes and istio on macOS using Docker desktop. I used the bookinfo example and everything runs fine. I have one of my own service and I am unable to get it to run. I try to hit it using postman and always get a 404. I am unable to debug it, I might just be missing something or doing something stupid. These are my yaml files gateway.yaml apiVersion: networking.istio.io/v1alpha3 kind: Gateway metadata: name: reeal-gateway spec: selector: istio: ingressgateway # use istio default controller servers: - port: number: 80 name: http protocol: HTTP hosts: - "*" --- apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: reeal spec: hosts: - "*" gateways: - reeal-gateway http: - match: - uri: exact: /feed route: - destination: host: feed port: number: 8080 service.yaml apiVersion: v1 kind: Service metadata: name: feed labels: app: feed service: feed spec: selector: app: feed ports: - port: 8080 name: http --- apiVersion: v1 kind: ServiceAccount metadata: name: reeal-feed labels: account: feed --- apiVersion: apps/v1 kind: Deployment metadata: name: feed-deployment labels: app: feed version: v1 spec: replicas: 1 selector: matchLabels: app: feed version: v1 template: metadata: labels: app: feed version: v1 spec: serviceAccountName: reeal-feed volumes: - name: firestore-key secret: secretName: firestore-cred containers: - name: feed-service image: reealadmin/feed-service:latest imagePullPolicy: Always ports: - containerPort: 8080 volumeMounts: - name: firestore-key mountPath: /var/secrets/google env: - name: GOOGLE_APPLICATION_CREDENTIALS value: /var/secrets/google/key.json imagePullSecrets: - name: regcred I have tested the service by exposing it using Nodeport and i can curl and get the respective response, however I am making some mistake to not be able to configure the ingress properly. URL I am using below for my URL. The url formed is localhost/feed export INGRESS_PORT=$(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.spec.ports[?(@.name=="http2")].port}') export SECURE_INGRESS_PORT=$(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.spec.ports[?(@.name=="https")].port}') export INGRESS_HOST=$(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].hostname}') echo $INGRESS_HOST echo $INGRESS_PORT echo $SECURE_INGRESS_PORT ERROR [2020-08-22T01:01:05.088Z] "GET /feed HTTP/1.1" 404 - "-" "-" 0 19 29 22 "192.168.65.3" "PostmanRuntime/7.26.3" "e5705c53-6e70-9dbe-b831-764f9c7be63e" "localhost" "10.1.0.41:8080" outbound|8080||feed.default.svc.cluster.local 10.1.0.25:40654 10.1.0.25:8080 192.168.65.3:59050 - - Really need help here. A: If you get 404 error, this means that your application is reached but does not have a /feed page. You either can change your app to serve all content on that contextPath or do a rewrite on your VirtualService: http: - match: - uri: exact: /feed rewrite: uri: / route: - destination: host: feed port: number: 8080
{ "pile_set_name": "StackExchange" }
Q: Keras. Concatenate layers. TypeError I want to create a siamese model, defined lower for colloborative filtration. First one creates users' embeddings, second one creates items' embeddings. import keras from keras import backend as K from keras.layers import Input, Embedding, Dense, Flatten, concatenate from keras.models import Model n_users, n_items = 100, 3000 users_input = Input(shape=(n_users,), dtype='int32', name='users') users_embedding = Embedding(output_dim=6, input_dim=n_users, input_length=1)(users_input) users_flatten = Flatten()(users_embedding) items_input = Input(shape=(n_items,), dtype='int32', name='items') items_embedding = Embedding(output_dim=6, input_dim=n_items, input_length=1)(items_input) items_flatten = Flatten()(items_embedding) layer_0 = concatenate([users_flatten, items_flatten]) layer_1 = Dense(8, activation='relu')(layer_0) layer_2 = Dense(1, activation='relu')(layer_1) model = Model(inputs=[users_input, items_input], outputs=[layer_2]) As you see, I have problems with concatenation. Here is my stack trace: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-bf475de5f9cc> in <module>() ----> 1 layer_0 = concatenate([users_flatten, items_flatten]) 2 layer_1 = Dense(8, activation='relu')(layer_0) 3 layer_2 = Dense(1, activation='relu')(layer_1) /home/vladimir/anaconda2/lib/python2.7/site-packages/keras/layers/merge.pyc in concatenate(inputs, axis, **kwargs) 506 A tensor, the concatenation of the inputs alongside axis `axis`. 507 """ --> 508 return Concatenate(axis=axis, **kwargs)(inputs) 509 510 /home/vladimir/anaconda2/lib/python2.7/site-packages/keras/engine/topology.pyc in __call__(self, inputs, **kwargs) 583 584 # Actually call the layer, collecting output(s), mask(s), and shape(s). --> 585 output = self.call(inputs, **kwargs) 586 output_mask = self.compute_mask(inputs, previous_mask) 587 /home/vladimir/anaconda2/lib/python2.7/site-packages/keras/layers/merge.pyc in call(self, inputs) 281 raise ValueError('A `Concatenate` layer should be called ' 282 'on a list of inputs.') --> 283 return K.concatenate(inputs, axis=self.axis) 284 285 def compute_output_shape(self, input_shape): /home/vladimir/anaconda2/lib/python2.7/site-packages/keras/backend/tensorflow_backend.pyc in concatenate(tensors, axis) 1679 return tf.sparse_concat(axis, tensors) 1680 else: -> 1681 return tf.concat([to_dense(x) for x in tensors], axis) 1682 1683 /home/vladimir/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/array_ops.pyc in concat(concat_dim, values, name) 998 ops.convert_to_tensor(concat_dim, 999 name="concat_dim", -> 1000 dtype=dtypes.int32).get_shape( 1001 ).assert_is_compatible_with(tensor_shape.scalar()) 1002 return identity(values[0], name=scope) /home/vladimir/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.pyc in convert_to_tensor(value, dtype, name, as_ref, preferred_dtype) 667 668 if ret is None: --> 669 ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) 670 671 if ret is NotImplemented: /home/vladimir/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/constant_op.pyc in _constant_tensor_conversion_function(v, dtype, name, as_ref) 174 as_ref=False): 175 _ = as_ref --> 176 return constant(v, dtype=dtype, name=name) 177 178 /home/vladimir/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/constant_op.pyc in constant(value, dtype, shape, name, verify_shape) 163 tensor_value = attr_value_pb2.AttrValue() 164 tensor_value.tensor.CopyFrom( --> 165 tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape, verify_shape=verify_shape)) 166 dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype) 167 const_tensor = g.create_op( /home/vladimir/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/tensor_util.pyc in make_tensor_proto(values, dtype, shape, verify_shape) 365 nparray = np.empty(shape, dtype=np_dt) 366 else: --> 367 _AssertCompatible(values, dtype) 368 nparray = np.array(values, dtype=np_dt) 369 # check to them. /home/vladimir/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/tensor_util.pyc in _AssertCompatible(values, dtype) 300 else: 301 raise TypeError("Expected %s, got %s of type '%s' instead." % --> 302 (dtype.name, repr(mismatch), type(mismatch).__name__)) 303 304 TypeError: Expected int32, got list containing Tensors of type '_Message' instead. As an example I used Keras documenation for functional API. I use TensorFlow as backend. A: Solution: update Keras and Tresorflow to the last versions.
{ "pile_set_name": "StackExchange" }
Q: What are the English font types already trained for tesseract 3.02 I want to know what are the different font types of English language already trained for tesseract 3.02. 1. Is there a way to find this ? 2. Is this information documented any where ? Any help, much appreciated. A: The names of the fonts can be found in eng.traineddata file itself. Unpack it and look at the .tr files or inside .inttemp file. References: https://code.google.com/p/tesseract-ocr/issues/detail?id=759 https://groups.google.com/forum/?fromgroups=#!topic/tesseract-ocr/QQsenFJkeNg http://tesseract-ocr.googlecode.com/svn-history/r757/trunk/tessdata/eng.cube.size
{ "pile_set_name": "StackExchange" }
Q: Creating a new column in pandas using for loop? I want to create a new column in my data-frame using combinations of multiple values from another column. I have tried the following code and it doesn't seem to work. the operator is not working that I can see. enter code here lst = [df1] for column in lst: column.loc[(column["booking_text"] in ['SEPA-Gutschrift','SEPA-Cash Management Gutsch','FASTER PAYMENTS','SCHECK-EV','BACS CREDIT','POS Gutschrift','Scheckeinreichung e.V.']) & (column["debit_credit"] == 'Credit'), "financial_category"] = 'Reveunue_Credit' df1['financial_category'] = df1['financial_category'] ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). A: lst = [df1] for column in lst: column.loc[(column["booking_text"].isin(['SEPA-Gutschrift','SEPA-Cash Management Gutsch','FASTER PAYMENTS', 'SCHECK-EV','BACS CREDIT','POS Gutschrift','Scheckeinreichung e.V.'])) & (column["debit_credit"] == 'Credit'), 'financial_category'] = 'Reveunue_Credit'
{ "pile_set_name": "StackExchange" }
Q: Chisel installation error While following the tutorial on the Chisel official website for installation, I came to the point where I should test if the installation was done correctly. Doing so yields this error: set -e -o pipefail; "sbt" -Dsbt.log.noformat=true -DchiselVersion="2.+" "run Parity --genHarness --compile --test --backend c --vcd --targetDir /home/me/chisel-tutorial/generated/examples " | tee /home/me/chisel-tutorial/generated/examples/Parity.out /bin/bash: sbt: command not found make: *** [/home/me/chisel-tutorial/generated/examples/Parity.out] Error 127 There is another question regarding the same problem here, where the suggestion to add SHELL=/bin/bash to the Makefile is made. That did not work for me. Another suggestion is to remove set -e -o pipefail: this suggestion actually works but is it OK to remove that option? what does it do? Edit_1: I have installed sbt and added its path to the PATH variable. $ which sbt /usr/bin/sbt But still I am getting this error when running make Parity.out set -e -o pipefail; "sbt" -Dsbt.log.noformat=true -DchiselVersion="2.+" "run Parity --genHarness --compile --test --backend c --vcd --targetDir /home/me/chisel-tutorial/generated/examples " | tee /home/me/chisel-tutorial/generated/examples/Parity.out /bin/sh: 1: set: Illegal option -o pipefail make: *** [/home/me/chisel-tutorial/generated/examples/Parity.out] Error 2 If I edit this part of the file suffix.mk: $(objdir)/%.dot: %.scala set -e -o pipefail; "$(SBT)" $(SBT_FLAGS) "run $(notdir $(basename $<)) --backend dot --targetDir $(objdir) $(CHISEL_FLAGS)" $(objdir)/%.out: %.scala set -e -o pipefail; "$(SBT)" $(SBT_FLAGS) "run $(notdir $(basename $<)) --genHarness --compile --test --backend c --vcd --targetDir $(objdir) $(CHISEL_FLAGS)" | tee $@ By deleting the -o option in the set -e -o pipefail it works, I get the PASSED and [success] message after running $ make Parity.out. So what is going on? Edit_2: It is working fine now after I added the SHELL=/bin/bash to the Makefile, so it was first a problem of not having sbt as Nathaniel pointed out then editing the Makefile to include SHELL=/bin/bash. A: set -e -o pipefail is a way of making sure that the execution of the bash script both works as expected and that if there is a failure, it halts immediately (rather than at some later stage). Removing it might work - but if there is a failure it might get swallowed and hide the fact it's broken. But I think your problem lies here, making the other question a bit of a red herring: /bin/bash: sbt: command not found Do you have sbt installed on your system? Run which sbt as the user that executes the script. For instance, on my system: $ which sbt /opt/local/bin/sbt If you don't have it on your system, nothing will be returned by running which. The script clearly needs access to sbt and is failing when it doesn't find it. If you do have it on your system, then there is a mismatch between the user running the script and access to that file. You'll need to post more information about how you're executing the script: in that case it is likely you'll have to update your PATH variables to be able to find the sbt executable. Given that, after fixing this, you still have a problem, you have to ensure that you're running in bash, and not another terminal type. The reason for this is that bash supports set -o pipefail but a lot of other terminals don't. We suspect this might be the case because of the error messages: /bin/sh: 1: set: Illegal option -o pipefail Here we see that /bin/sh (the shell) is being invoked by the program. Use ls -l /bin/sh to determine if your /bin/sh is pointing to a particular shell. If it is not pointed to a bash shell, then you either need to repoint it (be careful! this is probably another question in it's own right), or need to specify to your Scala program to use a specific shell.
{ "pile_set_name": "StackExchange" }
Q: Batch Clip in ModelBuilder of ArcGIS for Desktop? I have multiple rasters and feature classes that I want to clip to a study area. I am pretty new to ModelBuilder. I know you can right click the clip tool to batch clip outside of ModelBuilder but how do I bring that into ModelBuilder at ArcGIS 10.1 for Desktop? A: ModelBuilder functions differently than batch processing in ArcGIS. Typically, you use iterators to loop through individual files rather than a spreadsheet-type list of files and actions, as in batch mode. The following is an example of the type of model you would need to loop through a workspace containing rasters in order to clip them to study area bound. For clipping FC's simply replace "iterate rasters" with "iterate features" and change the clip raster tool to clip (analysis). Additional Resources: Quick tour of iterators Examples of iterators
{ "pile_set_name": "StackExchange" }
Q: Is it possible to have a Generic class not requiring new() with single method requiring new()? Is it possible in C# to have a method of a generic driven class require new, but not require new on the whole class? public class Response<T> //not where T:new() { public void AddTotal<T>() where T : new() { var totaledObject = new T(); // do all the useful stuff I need with the new generic } } I use this response for many different scenarios, the T does not always have a new(), and for those scenarios I will not use the AddTotal function, but for a few I would like to have it. Is this possible? Note: I know I can do a different generic variable name and just pass that to the function, but this breaks the indication that it has to be of the same type as T. A: Is it possible in C# to have a method of a generic driven class require new, but not require new on the whole class? Only if you specify different type parameter, which you don't want to do. A generic type parameter constraint exists for any generic type argument you specify. As you want T for the class and method declaration to be the same T, the constraint will exist for both. If you want to specify another generic type parameter, you could do something hacky like this: public class X<T> { public void Y<OtherT>() where OtherT : T, new() { } } Thus constraining OtherT to be of type T declared in the class or a derivative. There's no guarantee there will be an exact match on the type.
{ "pile_set_name": "StackExchange" }
Q: add option to collection_select rails 3 jquery I have this form: <%= form_for(@post) do |f| %> <%=f.collection_select :post_id, Board.where(:user_id => current_user.id), :id, :name %> <%= f.submit "Post it"%> <% end %> I want to know how add new option without reload page with input button through jquery: I want add the option to collection_select before submit form I'm using jquery ujs https://github.com/rails/jquery-ujs Example: A: if the option you want to add is already on the page this post has the answer. if you wanted to do it with ajax you would need to get the options though a call to ajax to get the array then iterate over it update: var input_value = $('#myInput').val() $('#mySelect').append( $('<option></option>').val(input_value.replace(' ', '_')).html(input_value) ); change append to prepend if you want it at the top which might be a bit more user friendly the replace element might need work depending on what the users are likely to input and how you want to store the new options. and was not sure how you wanted to fire this, so you need to bind it to the create i guess...
{ "pile_set_name": "StackExchange" }
Q: Display CPU usage on Azure App Service? I am trying to measure CPU usage for one of my Azure App Services by going to the "Site Metrics per Instance". The problem is that there is no option to check the CPU usage but CPU time and other stuff like "Average memory working set" and "Data In/Out". Does someone know how and where I can see the CPU usage for one App Service? A: You app is related to an App Service plan : monitoring the plan will give you a percentage, but the app can only be monitored about its own metric : its own CPU time. You can imagine changing the plan for the app then the % would be different. So, on the app itself you can only measure the app CPU time, as % is depending on the plan.
{ "pile_set_name": "StackExchange" }
Q: PHP How to replace spacific array value to another array value? I am getting this array results: Array ( [0] => Array ( [subscription_id] => 67 [user_id] => 156 [property_id] => 1036 [title] => Rotchild 50, Tel Aviv, Israel [subscription_plan_id] => 13 [transactionID] => VHHDLY2P5CC7V5K34UA5SUFWVM [transactionDisplayID] => 441486 [paid_with] => Visa [active] => 1 [start_date] => 2015-02-11 09:22:08 [end_date] => 2015-03-12 [s_start_date] => 2015-02-12 09:29:33 [s_subscription_id] => 70 ) [1] => Array ( [subscription_id] => 66 [user_id] => 156 [property_id] => 1036 [title] => Rotchild 50, Tel Aviv, Israel [subscription_plan_id] => 2 [transactionID] => VHHDLY2P5CC7V5K34UA5SUFWVM [transactionDisplayID] => 441486 [paid_with] => Visa [active] => 1 [start_date] => 2015-02-11 09:22:07 [end_date] => 2015-03-12 [s_start_date] => 2015-02-12 09:26:50 [s_subscription_id] => 69 ) ) Now How to replace end_date key value to start_date key value with incrementing with 1 day like: Array ( [0] => Array ( [subscription_id] => 67 [user_id] => 156 [property_id] => 1036 [title] => Rotchild 50, Tel Aviv, Israel [subscription_plan_id] => 13 [transactionID] => VHHDLY2P5CC7V5K34UA5SUFWVM [transactionDisplayID] => 441486 [paid_with] => Visa [active] => 1 [start_date] => 2015-03-13 [end_date] => 2015-03-12 [s_start_date] => 2015-02-12 09:29:33 [s_subscription_id] => 70 ) [1] => Array ( [subscription_id] => 66 [user_id] => 156 [property_id] => 1036 [title] => Rotchild 50, Tel Aviv, Israel [subscription_plan_id] => 2 [transactionID] => VHHDLY2P5CC7V5K34UA5SUFWVM [transactionDisplayID] => 441486 [paid_with] => Visa [active] => 1 [start_date] => 2015-03-13 [end_date] => 2015-03-12 [s_start_date] => 2015-02-12 09:26:50 [s_subscription_id] => 69 ) ) Any Idea how to replace spacific array value to another? A: You are looking at nested, associative arrays. If you know the indexes and keys then it's pretty easy: $endDate = str_replace('-', '/', your_array[0]['end_date']); your_array[0]['start_date'] = date('Y-m-d', strtotime($endDate.'+1 days')); $endDate = str_replace('-', '/', your_array[1]['end_date']); your_array[1]['start_date'] = date('Y-m-d', strtotime($endDate.'+1 days')); For more details about manipulating date/time you should review the manual for the strtotime and date functions.
{ "pile_set_name": "StackExchange" }
Q: How to import a file of classes in a Jenkins Pipeline? I have a file that contains classes. Example : abstract class TestBase { String name abstract def fTest() def bobby(){ return "bobby" } } class Test extends TestBase { def fTest(){ return "hello" } } class Test2 extends TestBase { def fTest(){ return "allo" } def func(){ return "test :)" } } I want to import the file in my Jenkins pipeline script, so I can create an object of one of my class. For example : def vTest = new Test() echo vTest.fTest() def vTest2 = new Test2() echo vTest2.func() How can I import my file in my Jenkins Pipeline ? Thx. A: you can do like this: Classes.groovy class A{ def greet(name){ return "greet from A: $name!" } } class B{ def greet(name){ return "greet from B: $name!" } } // this method just to have nice access to create class by name Object getProperty(String name){ return this.getClass().getClassLoader().loadClass(name).newInstance(); } return this pipeline: node{ def cl = load 'Classes.groovy' def a = cl.A echo a.greet("world A") def b = cl.B echo b.greet("world B") }
{ "pile_set_name": "StackExchange" }
Q: Time Series Interpolation I have two series of data (calibration and sample) and am trying to interpolate the calibration data from monthly to the frequency of the sample which randomly changes between minutely to secondly. I tried this (Interpolating timeseries) and here's my code: require(zoo) zc <- zoo(calib$MW2, calib$Date) zs <- zoo(sample$MW.2, sample$DateMW.2) z <- merge(zc, zs) zc <- zoo(calib$MW2, calib$Date) zs <- zoo(sample$MW.2, sample$DateMW.2) # "merge" gets data frames only zc <- data.frame(zc) zs <- data.frame(zs) z <- merge(zc, zs) z$zc <- na.approx(z$zc, rule=2) df <- z[index(zs),] Note: Convert outputs of zoo to data.frame (zc and zs) before merging. The problem is that instead of interpolation, it just repeats the calibration data-set; You can take a look at the part of the supposedly interpolated df and compare it to the original data above to confirm what I say; > df zc zs date 1 60.84440 61.40373 2016-06-02 18:15:00 2 58.85957 61.40373 2016-06-02 18:30:00 3 57.49543 61.40373 2016-06-02 18:45:00 4 56.32829 61.40373 2016-06-02 19:00:00 5 56.84261 61.40373 2016-06-02 19:15:00 6 57.76762 61.40373 2016-06-02 19:30:00 7 59.58310 61.40373 2016-06-02 19:45:00 8 59.95826 61.40373 2016-06-02 20:00:00 9 60.84440 61.41549 2016-06-02 20:15:00 10 58.85957 61.41549 2016-06-02 20:30:00 11 57.49543 61.41549 2016-06-02 20:45:00 12 56.32829 61.41549 2016-06-02 21:00:00 Data: sample <- structure(list(DateMW.2 = structure(1:15, .Label = c("6/2/2016 18:15:00", "6/2/2016 18:30:00", "6/2/2016 18:45:00", "6/2/2016 19:00:00", "6/2/2016 19:15:00", "6/2/2016 19:30:00", "6/2/2016 19:45:00", "6/2/2016 20:00:00", "6/2/2016 20:15:00", "6/2/2016 20:30:00", "6/2/2016 20:45:00", "6/2/2016 21:00:00", "6/2/2016 21:15:00", "6/2/2016 21:30:00", "6/2/2016 21:45:00"), class = "factor"), MW.2 = c(61.40373, 61.41549, 61.41549, 61.42451, 61.42752, 61.42478, 61.43107, 61.42369, 61.40564, 61.41056, 61.40592, 61.39416, 61.38432, 61.3753, 61.3753)), .Names = c("DateMW.2", "MW.2"), row.names = c(NA, 15L), class = "data.frame") calib <- structure(list(Date = structure(c(4L, 5L, 6L, 7L, 8L, 1L, 2L, 3L), .Label = c("10/31/2016 12:00:00", "11/30/2016 12:00:00", "12/31/2016 12:00:00", "5/31/2016 12:00:00", "6/30/2016 12:00:00", "7/31/2016 12:00:00", "8/31/2016 12:00:00", "9/30/2016 12:00:00" ), class = "factor"), MW2 = c(60.844402, 58.859566, 57.495434, 56.328285, 56.842606, 57.76762, 59.583103, 59.958263)), .Names = c("Date", "MW2"), class = "data.frame", row.names = c(NA, -8L)) A: If your data-set is already formatted as date-time you don't need to struggle with using zoo. Here, I simply used approx function and it gave me exactly what I wanted. You can get the data-set from the question to reproduce the code. ipc <- approx(calib$Date,calib$MW2, xout = sample$`DateMW-2`, rule = 1, method = "linear", ties = mean) You can see that the data is being interpolated linearly between the given data points. Thanks for your insightful comments.
{ "pile_set_name": "StackExchange" }
Q: Can't recognise multiple URL query parameters in spring boot, jax-rs, jersey Having a problem passing multiple query parameters in a curl command to my spring boot server which is using jersey and jax-rs to serve up a few end points. Here is my curl command: curl localhost:8080/players?pageStartIndex=3&pageSize=4 I use a filter to print out whats comming in @Provider public class APIRequestFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { System.out.println(">>filter(), uriPath=" + requestContext.getUriInfo().getRequestUri()); System.out.println(">>filter(), " + requestContext.getUriInfo().getQueryParameters()); ... Here is what is printed out... >>filter(), uriPath=http://localhost:8080/players?pageStartIndex=3 >>filter(), {pageStartIndex=[3]} For some reason, only the first query parameter is printed out. Any ideas? A: You need to wrap the url in the command line in quotes. & has a special meaning on the command line.
{ "pile_set_name": "StackExchange" }
Q: AngularJS, como mudar a tags colchetes ({{ e }}) para qualquer outro carácter de sua escolha? No AngularJS por padrão vem as tags colchetes ({{ e }}) para manipulação, queria alterar para %% e %%, como devo proceder ? Exemplo: {{name}} para %%name%% A: Para trocar, precisa configurar na sua aplicação dessa forma: no $interpolateProvider, coloque a startSymbol e endSymbol setando para %% var App = angular.module('App',[]); App.config(function($interpolateProvider) { $interpolateProvider.startSymbol('%%'); $interpolateProvider.endSymbol('%%'); }); Exemplo: Angular: var App = angular.module('App',[]); App.config(function($interpolateProvider) { $interpolateProvider.startSymbol('%%'); $interpolateProvider.endSymbol('%%'); }); function PeopleListCtrl($scope){ $scope.peoples = [ {'id': 1, 'name': 'Nome 1'}, {'id': 2, 'name': 'Nome 2'} ]; }; Html Completo com AngularJS: <!DOCTYPE HTML> <html ng-app="App"> <head> <meta charset="utf-8"> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.10/angular.min.js"></script> </head> <body> <div> <div ng-controller="PeopleListCtrl"> <br /> <p>Quantidade: %%peoples.length%%</p> <br /> <ol> <li ng-repeat="p in peoples">%%p.id%% - %%p.name%%</li> </ol> </div> </div> <script> var App = angular.module('App',[]); App.config(function($interpolateProvider) { $interpolateProvider.startSymbol('%%'); $interpolateProvider.endSymbol('%%'); }); function PeopleListCtrl($scope){ $scope.peoples = [ {'id': 1, 'name': 'Nome 1'}, {'id': 2, 'name': 'Nome 2'} ]; }; </script> </body> </html> Resultado: jsfiddle Referências: AngularJS $interpolateProvider ngRepeat
{ "pile_set_name": "StackExchange" }
Q: How do I restore old Empathy logs from a previous installation? I'm an absolute beginner at all of this. Please could someone CLEARLY explain (without assumption of any prior knowledge of operating Ubuntu, let alone 11.04) how I restore old Empathy logs now that I have 11.04. I know that I kept my old stuff in a partition but I don't know what to do to bring it back. The man who did this to my machine managed it last time but I'm without him and clueless. Please help. Thanks. A: You can restore saved logs only if your Ubuntu installation as been upgraded from a previous version or if you (or the man who supported you) backed up your data in advance. Reading your question I understand your helper put all your old data in a separate partition/position. If so, first of all, ask him where he put your old data, and take a note: from now on I'll call this path <OLD-PARTITION>. Then, note your user name: it is the name you can read in the top-right corner of your desktop in Ubuntu 11.04. I'll call this <your-new-username> from now on. Same for your old user-name before upgrading (in case it was different): <your-old-username>. Now, open Nautilus, the file browser. If you don't know how to do, just open a terminal and type nautilus <OLD-PARTITION>. Now you shall browse till you reach the path below. Starting from the <OLD-PARTION> part, you only need to right click folders between "/" to reach it. If you cannot see the .local folder, press CTRL+H in Nautilus to show hidden files. Once you reach the "TpLogger" folder, right click on the "logs" folder and select Copy: <OLD-PARTITION>/home/<your-old-username>/.local/share/TpLogger/logs Then, do the same to restore, using following path. Once you reach the "TpLogger" folder, right click folder list and select Paste: /home/<your-new-username>/.local/share/TpLogger/logs After this, restart Empathy.
{ "pile_set_name": "StackExchange" }
Q: root namespace is added into the library: apache Santuario + xades4j. using xpathto select elements and sign them. If I try to sign a simple XML without a namespace and verify the signature, it works well , but if the XML defines a namespace, for example the XML following: <ClinicalDocument xmlns="urn:hl7-org:v3"> <element1tobesigned.../> <element2tobesigned.../> </ClinicalDocument> and the exception was found when verifying the signature 858 WARN [main] org.apache.xml.security.signature.Reference - Verification failed for URI "#xmldsig-5fb20abe-b14c-4d84-a908-e22e776cd6f1-signedprops" 858 WARN [main] org.apache.xml.security.signature.Reference - Expected Digest: q0WnWFf9j0kcT46t5cXmcPnVvu5o51oAcmej/SjCazQ= 858 WARN [main] org.apache.xml.security.signature.Reference - Actual Digest: 41zXKVkRCsxUYpNZXW5b9KkZlTC9LM9WA8O7WHQz1Rg= xades4j.verification.ReferenceValueException: Reference '#xmldsig-5fb20abe-b14c-4d84-a908-e22e776cd6f1-signedprops' cannot be validated the cause is that XML namespace (urn:hl7-org:v3) was added into the xades:SignedProperties then the digest became different . 858 DEBUG [main] org.apache.xml.security.utils.DigesterOutputStream - Pre-digested input 858 DEBUG [main] org.apache.xml.security.utils.DigesterOutputStream - <xades:SignedProperties xmlns="urn:hl7-org:v3" ........./> here is the signature generation code XadesTSigningProfile profile = new XadesTSigningProfile(keyProvider); profile.withTimeStampTokenProvider(TestTimeStampTokenProvider.class) .withAlgorithmsProviderEx(ExclusiveC14nForTimeStampsAlgorithmsProvider.class); XadesSigner signer = profile.newSigner(); DataObjectDesc obj1 = new DataObjectReference("") .withTransform(new ExclusiveCanonicalXMLWithoutComments()) .withTransform( new XPathTransform(xPath); SignedDataObjects dataObjs = new SignedDataObjects().withSignedDataObject(obj1); changed 2012-11-20 begin // signer.sign(dataObjs, docToSign.getDocumentElement() ); new Enveloped(signer).sign(docToSign.getDocumentElement()); changed 2012-11-20 end and here is the verify code NodeList signatureNodeList = getSigElement(getDocument("my/my-document.signed.bes.countersign.xml")); for (int i = 0; i < signatureNodeList.getLength(); i++) { Element signatureNode = (Element) signatureNodeList.item(i); verifySignature(signatureNode, new XadesVerificationProfile(VerifierTestBase.validationProviderMySigs)); log.info("successful validation"); } public static XAdESForm verifySignature(Element sigElem, XadesVerificationProfile p) throws Exception { XAdESVerificationResult res = p.newVerifier().verify(sigElem, null); return res.getSignatureForm(); } It looks like that there is a document about this problem in Apache Santuario FAQ , 2.6. I sign a document and when I try to verify using the same key, it fails After you have created the XMLSignature object, before you sign the document, you must embed the signature element in the owning document (using a call to XMLSignature.getElement() to retrieve the newly created Element node from the signature) before calling the XMLSignature.sign() method, During canonicalisation of the SignedInfo element, the library looks at the parent and ancestor nodes of the Signature element to find any namespaces that the SignedInfo node has inherited. Any that are found are embedded in the canonical form of the SignedInfo. (This is not true when Exclusive Canonicalisation is used, but it is still good practice to insert the element node prior to the sign() method being called). If you have not embedded the signature node in the document, it will not have any parent or ancestor nodes, so it will not inherit their namespaces. If you then embed it in the document and call verify(), the namespaces will be found and the canonical form of SignedInfo will be different to that generated during sign(). also there is a document about this problem as following https://stackoverflow.com/a/12759909/1809884 It looks like that it is not a bug of xades4j, but a xml signature problem. --add 2012-11-15 here is how to get the docToSign . in fact , i just reused the code in class SignatureServicesTestBase . so i am sure that it is namespaceaware. static { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); db = dbf.newDocumentBuilder(); } public static Document getDocument(String fileName) throws Exception { String path = toPlatformSpecificXMLDirFilePath(fileName); Document doc = db.parse(new FileInputStream(path)); // Apache Santuario now uses Document.getElementById; use this convention for tests. Element elem = doc.getDocumentElement(); DOMHelper.useIdAsXmlId(elem); return doc; } and docToSign is return by calling SignatureServicesTestBase.getDocument() Document docToSign = SignatureServicesTestBase.getDocument("my/cdamessage.xml"); and the SignedProperties element as following <xades:SignedSignatureProperties> <xades:SigningTime>2012-11-15T13:58:26.167+09:00</xades:SigningTime> <xades:SigningCertificate> <xades:Cert> <xades:CertDigest> <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> <ds:DigestValue>4btVb5gQ5cdcNhGpvDSWQZabPQrR9jf1x8e3YF9Ajss=</ds:DigestValue> </xades:CertDigest> <xades:IssuerSerial> <ds:X509IssuerName>CN=Itermediate,OU=CC,O=ISEL,C=PT</ds:X509IssuerName> <ds:X509SerialNumber>-119284162484605703133798696662099777223</ds:X509SerialNumber> </xades:IssuerSerial> </xades:Cert> <xades:Cert> <xades:CertDigest> <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> <ds:DigestValue>vm5QpbblsWV7fCYXotPhNTeCt4nk8cLFuF36L5RJ4Ok=</ds:DigestValue> </xades:CertDigest> <xades:IssuerSerial> <ds:X509IssuerName>CN=TestCA,OU=CC,O=ISEL,C=PT</ds:X509IssuerName> <ds:X509SerialNumber>-46248926895392336918291885380930606289</ds:X509SerialNumber> </xades:IssuerSerial> </xades:Cert> <xades:Cert> <xades:CertDigest> <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> <ds:DigestValue>AUaN+IdhKQqxIVmEOrFwq+Dn22ebTkXJqD3BoOP/x8E=</ds:DigestValue> </xades:CertDigest> <xades:IssuerSerial> <ds:X509IssuerName>CN=TestCA,OU=CC,O=ISEL,C=PT</ds:X509IssuerName> <ds:X509SerialNumber>-99704378678639105802976522062798066869</ds:X509SerialNumber> </xades:IssuerSerial> </xades:Cert> </xades:SigningCertificate> </xades:SignedSignatureProperties> </xades:SignedProperties> also , i use xpath to get the elements to be signed, and namespace(xmlns="urn:hl7-org:v3" ) is add into the result as well . 543 DEBUG [main] org.apache.xml.security.utils.ElementProxy - setElement("ds:Transform", "null") 544 DEBUG [main] org.apache.xml.security.utils.ElementProxy - setElement("dsig-xpath:XPath", "null") 658 DEBUG [main] org.apache.xml.security.utils.DigesterOutputStream - Pre-digested input: 658 DEBUG [main] org.apache.xml.security.utils.DigesterOutputStream - <component xmlns="urn:hl7-org:v3" Id="ES" contextConductionInd="true" typeCode="COMP"> <section classCode="DOCSECT" moodCode="EVN"> <code code="ES" codeSystem="2.16.840.1.113883.6.1" codeSystemName="SectionCode" codeSystemVersion="1.0" displayName="english"></code> <text>english</text> </section> </component> something wrong with xpath ? xpath is driving my crazy . I think i have to study xpath from beginning now. chris A: You're creating an enveloped signature but the enveloped signature transform is missing! Since the whole document is being signed the signature node itself has to be excluded, because some of its contents change after signature calculation. Can't believe how I didn't see it until you mentioned the Enveloped class. Btw, this class is just an utility class for simple, straightforward enveloped sigantures. It robably shouldn't even be there. You can just add the transform yourself: DataObjectDesc obj1 = new DataObjectReference("") .withTransform(new EnvelopedSignatureTransform()) .withTransform(new ExclusiveCanonicalXMLWithoutComments()) ...
{ "pile_set_name": "StackExchange" }
Q: JQuery: find parent and another child I have the following markup: <div style="width: 660px; border-bottom: 1px solid #3A3F46;"> <div class="noplace_event_cont"> <div style="float: left;"> <span class="title">Usual</span> <span class="desc">Free: <span class="free_place">19</span></span> </div> <div style="float: right;"> <div class="spinner_cont"> <input type="text" data-type="1" class="event_spinner" value="0" maxlength="1" style="width: 24px; margin-right: 16px; text-align: right;"><span class="ui-spinner ui-widget"><div class="ui-spinner-buttons" style="height: 41px; left: -16px; top: -13.0833px; width: 36px;"><div class="ui-spinner-up ui-spinner-button ui-state-default ui-corner-tr" style="width: 16px; height: 20.5px;"><span class="ui-icon ui-icon-triangle-1-n" style="margin-left: 16.5px; margin-top: 15px;">&nbsp;</span></div><div class="ui-spinner-down ui-spinner-button ui-state-default ui-corner-br" style="width: 16px; height: 20.5px;"><span class="ui-icon ui-icon-triangle-1-s" style="margin-left: 16.5px; margin-top: 15px;">&nbsp;</span></div></div></span> </div> </div> </div> <div class="noplace_event_cont"> <div style="float: left;"> <span class="title">VIP</span> <span class="desc">Free: <span class="free_place">6</span></span> </div> <div style="float: right;"> <div class="spinner_cont"> <input type="text" data-type="2" class="event_spinner" value="0" maxlength="1" style="width: 24px; margin-right: 16px; text-align: right;"><span class="ui-spinner ui-widget"><div class="ui-spinner-buttons" style="height: 41px; left: -16px; top: -13.0833px; width: 36px;"><div class="ui-spinner-up ui-spinner-button ui-state-default ui-corner-tr" style="width: 16px; height: 20.5px;"><span class="ui-icon ui-icon-triangle-1-n" style="margin-left: 16.5px; margin-top: 15px;">&nbsp;</span></div><div class="ui-spinner-down ui-spinner-button ui-state-default ui-corner-br" style="width: 16px; height: 20.5px;"><span class="ui-icon ui-icon-triangle-1-s" style="margin-left: 16.5px; margin-top: 15px;">&nbsp;</span></div></div></span> </div> </div> </div> </div> I want to find text in span with free_place class: $(".event_spinner").each(function () { var max = $(this).parent(".noplace_event_cont").find(".free_place").text(); alert(max); }); But, this code not working. max is undefined. Thanks. A: var max = $(this).closest(".noplace_event_cont").find(".free_place").text(); or var max = $(this).closest(".free_place").text();
{ "pile_set_name": "StackExchange" }
Q: What is the reason behind this Eclipse behavior due to changing an Environment Variable? I have two versions of Eclipse that I use (Indigo for C++ and Helios for Java). I've used both for years without problems. Last week I needed to view Java Bytecode, so in my Environment Variables I added "C:\Program Files\Java\jdk1.6.0_26\bin;" to the Path variable (this let me use javap 'class' -c to view bytecode in a command prompt). I continued to use Helios just fine. Today I tried booting up Indigo to work on some C++ code, but I got the "Failed to load JNI shared library etc." error for it, causing it to force close. Eventually I tried removing that path I placed in environment variables, and Indigo boots up correctly again. Any idea why this happened? I don't fully understand paths, but I don't see why adding the path I did would cause my other Eclipse to break. I don't really need javap anymore so I removed the path, but I'm still curious as to why this happened. Thanks for any insight! A: With the change to the path Eclipse was probably trying to load 32 bit Eclipse with a 64 bit Java (or the other way round), they both have to be 32 bit or 64 bit.
{ "pile_set_name": "StackExchange" }
Q: Preferred Domain (in Webmaster Tools) and IIS7 Configuration I am setting up a new website and want to set the non-www version as the preferred domain in Google Webmaster tools. In IIS7 I was going to configure the non-www domain as the main site, then configure a redirect for the www domain to perform a 301 redirect to the non-www domain (as I want all traffic that requests www. regardless of whether it's the homepage or any page within the site) to redirect to the equivalent page on the non-www version. I have set the above up and all works fine, however, in order to set the preferred domain in Google Webmaster tools, I need to verify both the www and non-www domains. My question is, if I have set up a 301 redirect for all www requests to go to non-www, how can I verify the www domain (as google won't be able to reach a verification file on the www domain)? A: I just noticed that you can add a TXT entry to your DNS record and verify the domain in webmaster tools this way, which solves this problem.
{ "pile_set_name": "StackExchange" }
Q: Using results of query multiple times How do I use the result of a query multiple times $query=...; $resultsaved=mysql_query($query, $db); for($i=0;$i<100;$i++){ $result=$resultsaved; while($rowarray = mysql_fetch_array($result, MYSQL_NUM)){ //do stuff depending on $i and $rowarray } } However after its first iteration, $resultsaved is destroyed; is there a more efficient way than $result=mysql_query($query, $db); a hundred times A: You don't need a temporary variable. As the documentation about mysql_fetch_array says: Returns an array that corresponds to the fetched row and moves the internal data pointer ahead. So, after the while loop you need to reset the internal pointer with mysql_data_seek: $query=...; $result=mysql_query($query, $db); for($i=0;$i<100;$i++){ while($rowarray = mysql_fetch_array($result, MYSQL_NUM)){ //do stuff depending on $i and $rowarray } mysql_data_seek($result, 0); }
{ "pile_set_name": "StackExchange" }
Q: Python: how to extract "data-bind" html elements? I am trying to extract data from a website. The element is hidden. when i try to "view source", the header text is not displayed. <h4 data-bind="Text: Name"></h4> But when i try to inspect, there is text visible. <h4 data-bind="Text: Name">STM1F-1S-HC</h4> The code used is: def getlink(link): try: f = urllib.request.urlopen(link) soup0 = BeautifulSoup(f) except Exception as e: print (e) soup0 = 'abc' for row2 in soup0.findAll("h4",{"data-bind":"text: Name"}): Name = row2.text print(Name) #code to find all links to the products for further processing. i=1 global i for row in r1.findAll('a', { "class" : "col-xs-12 col-sm-6" }): link = 'https://www.truemfg.com/USA-Foodservice/'+row['href'] print(link) getlink(link) print(productcount) The output is: https://www.truemfg.com/USA-Foodservice/Products/Traditional-Reach-Ins C:\Users\Santosh\Anaconda3\lib\site-packages\bs4\__init__.py:181: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("lxml"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently. The code that caused this warning is on line 193 of the file C:\Users\Santosh\Anaconda3\lib\runpy.py. To get rid of this warning, change code that looks like this: BeautifulSoup([your markup]) to this: BeautifulSoup([your markup], "lxml") markup_type=markup_type)) https://www.truemfg.com/USA-Foodservice/Products/Specification-Series https://www.truemfg.com/USA-Foodservice/Products/Food-Prep-Tables https://www.truemfg.com/USA-Foodservice/Products/Undercounters https://www.truemfg.com/USA-Foodservice/Products/Worktops https://www.truemfg.com/USA-Foodservice/Products/Chef-Bases https://www.truemfg.com/USA-Foodservice/Products/Milk-Coolers https://www.truemfg.com/USA-Foodservice/Products/Glass-Door-Merchandisers https://www.truemfg.com/USA-Foodservice/Products/Air-Curtains https://www.truemfg.com/USA-Foodservice/Products/Display-Cases https://www.truemfg.com/USA-Foodservice/Products/Underbar-Refrigeration we find that there are no names printed. Could someone let me know a solution to print the names as well. Thanks, Santosh A: Required content generated dynamically by XHR. You can try below code to request data directly and avoid parsing HTML: import requests url = 'https://prodtrueservices.azurewebsites.net/api/products/productline/403/1?skip=0&take=200&unit=Imperial' r = requests.get(url) counter = 0 while True: try: print(r.json()['Products'][counter]['Name']) counter += 1 except IndexError: break This should allow you to get all names
{ "pile_set_name": "StackExchange" }
Q: how to pass DataTable var from jsf (primefaces) to managedBean? I have a first dataTable with a list of jobs, for each job of the list I wan't to create a second dataTable (inside the first ) with triggersList this is my jsf page : <p:dataTable id="jobs" var="job" value="#{jobBean.jobList}" rowKey="job.key"> <f:facet name="header"> Jobs List </f:facet> <p:column headerText="Name"> #{job.key.name} </p:column> <p:column headerText="Group"> #{job.key.group} </p:column> <p:column headerText="Triggers"> <p:dataTable id="triggers" var="trigger" value="#{jobBean.triggerList}"> <p:column headerText="Start Time"> #{trigger.startTime} </p:column> </p:dataTable> </p:column> </p:dataTable> So for each job var I wan't to have triggers List, this is my managedBean : public class JobBean implements Serializable { @ManagedProperty(value = "#{job}") private JobDetail job; private List<Trigger> triggerList; .... /** * @param triggerList * the triggerList to set */ public void setTriggerList(List<Trigger> triggerList) { this.triggerList = triggerList; } /** * @return the triggerList */ public List<Trigger> getTriggerList() { this.get(); return triggerList; } private void get(){ FacesContext ctx = FacesContext.getCurrentInstance(); JobDetail jb = ctx.getApplication().evaluateExpressionGet(ctx, "# {job}", JobDetail.class); this.triggerList = triggerListMap.get(jb.getKey()); } /** * @param job * the job to set */ public void setJob(JobDetail job) { this.job = job; } /** * @return the job */ public JobDetail getJob() { return job; } } The get() method return a null pointer Exception : Caused by: java.lang.NullPointerException at tti.frameworkBI.web.JobBean.get(JobBean.java:129) A: Resolved with findComponent and getRowData() : public List<Trigger> getTriggerList() { this.get(); return triggerList; } private void get() { DataTable dataTable = (DataTable) FacesContext.getCurrentInstance() .getViewRoot().findComponent("form:jobs"); JobDetail jb = (JobDetail) dataTable.getRowData(); this.triggerList = this.jobServiceImpl.getAllTriggers(scheduler, jb.getKey()); }
{ "pile_set_name": "StackExchange" }
Q: How close was the Japanese writing system from becoming abolished after World War II? I remember hearing that the Japanese government planned on abolishing the use of Chinese characters entirely after World War II. I also remember hearing that there was a movement by the American government to change the Japanese writing system to use an English-based alphabet system (maybe similar to romanization of Japanese). I have always wondered how close these movements were from actually being realized? EDIT When I say "how close", I basically want to know how far did these proposed policies reach in government before being voted down? Or did they never reach a voting stage within the parliament in Japan and were shot down by someone else before that? A: Undoubtedly the book Krazer suggested would make for the most thorough answer, but the Japanese wikipedia article on the 国語審議会 (the Japanese Language Council) has got some interesting details. From 1949 to 1961 the chairman was 土岐善麿, a supporter of the switch to romaji. Some of his work was published in romaji. (At least one example, Nakiwarai, is online if you'd like to see some period romaji text). Members of the カナモジカイ, a group promoting the use of kana only, were also involved. There was a sub-committee for dealing with issues around romaji, ローマ字調査分科審議会, from 1950 to 1962. This tackled issues like determining a standard for romaji, and the use of romaji in education. For example, here (1957 - official report) they report the improvement of results (referencing Japanese and maths classes), although they did want to do a greater number of tests. It also talks about romaji use in society in general - an interesting example given is that for punched tape, it took the least space to encode romaji compared to kana or kanji. The new technology of the time was not particularly kanji-friendly. At this point it seems there was still the intention to move towards script reform. However, conflicts between those in favour of (改革派) and against (慎重派) reform came to a head in 1961, when five of the 慎重派 walked out (see final remarks by 成瀬正勝 at the end of this page) over arguments about how elections were handled. Specifically, I think the feeling was that the 国語審議会 had been formed mostly from reformists under the control/influence of the occupying forces, and that the same people were being constantly re-elected. The Ministry of Education got involved, asking for a re-evaluation of reform plans. One of the outcomes of this was that the ローマ字調査分科審議会 was dissolved. 土岐善麿 was not only no longer chairman after this, he seems to have been removed entirely. This, from the next meeting after the walkouts, summarises some of the viewpoints that had come up critiquing the work of the council, including suggestions that the influence of the romaji and kanamoji groups had complicated things, and that the proposals of the council should not be forced on people. The final nail in the coffin seems to have come out of a 1966 meeting where the address given by the Minister for Education, 中村梅吉, included these lines stating that the use of mixed kana/kanji was pretty much a given: 今後のご審議にあたりましては,当然のことながら国語の表記は,漢字かなまじり文によることを前提とし,また現代国語の表記を平明にするという趣旨とともに,従来の諸施策との関連をご考慮の上,広い立場から国語の諸施策の改善の方途をじゅうぶんご検討願いたいのであります。 After this, the 国語審議会 focused more on subjects such as the daily-use kanji lists. In 1968 the amount of time given to teaching romaji in 小・中学校 was also reduced. A: There was a division of GHQ/SCAP known as the Civil Information and Education Section (CIE) which played a big role in reforming the Japanese education system. Many members of this group (and also some people on the Japan side) believed that romanization of the writing system would help increase the academic ability level in Japan (and also make it easier for non-native Japanese speakers). Many tests were performed to try to prove this was the case. For example, random literacy test were performed to see how well Japanese really understood Chinese characters and in some elementary schools romaji was adopted to see if there would be improvement in other subjects, such as Math. What I have said above seems to be agreed upon by all scholars, but the real reason why romanization was never adopted seems to be unclear. Some of the sites I read claim that the results of the tests proved that there was no benefit in changing to roma-ji and that is why the proposal was shot down, while the book pointed about by Krazer claims that the tests proved somewhat that there seemed to be a benefit in changing to romanization and there may have been some "cover up" done by the Ministry of Education in Japan at the time to prevent it. Also, other sites claim stuff like a leader change in CIE from a person who was for romanization to a person who was against romanization caused it to be shot down. (However, due to this reform, that is why everybody born after World War II can understand romaji). References 漢字かローマ字か日本時の読み書き能力調査 Literacy and Script Reform in Occupation Japan なぜローマ字化は実現しなかったのか 世界が驚嘆した識字率世界一の日本 Literacy in Japan (was Re: Statistics on education in Japan) (If anyone would like to try to answer this question, I will be glad to reward the bounty :)).
{ "pile_set_name": "StackExchange" }
Q: How to integrate PC-lint with Visual C++ 2008 My company has the PC-lint executable lint-nt.exe. I am trying to use this to integrate PC-lint with MS Visual Studio 2008 to analyze .c/.cpp sources. But I have no success with getting that to work. I read: http://www.gimpel.com/html/pub80/env-vc9.lnt and similar such info on one or two other sites, but no success. I followed the indicated steps to add an external tool in Visual C++ 8, but when I click on the newly added tool, the pc-lint window opens momentarily and is closed immediately, and I doubt it has run any analysis. So its not working for me. Then I tried running lint-nt.exe on a windows command prompt as lint-nt.exe +fce +fcp +cpp(cpp,cxx,cc) -i"C:\Program Files\Microsoft Visual Studio 9.0\VC\include" +libdir +libh myfile.cpp It did perform the analysis but it analyzed a lot of header files from the Visual C++ INCLUDE folder (limits.h sal.h iostream etc..), because my source file had #include <iostream> and so on. EDIT: I see pc-lint has options +/-libdir, +/-libh and such options, which might help, but I just could not use them correctly to avoid the analysis of compiler headers. Two questions: How do I prevent pc-lint from analyzing the compiler header files and only analyze my source code files? How to integrate pc-lint into Visual C++ 2008 Express edition, which I am using? A: If your company has the Lint executable, it will also have the PC-Lint manual in PDF form if not on paper. It is delivered on the CD-ROM together with the executable. That manual is your friend, to figure out how to use all the many options available. To your question: To get started quickly, remove the +fce, +fcp, +libdir and +libh options from your command line. I suppose you are just missing the -wlib(1) option to remain silent about the many warnings the MS libraries produce. Do not use -wlib(0): You will have silenced all options for the library headers, but incorrect configurations originating in those library headers may produce a truckload of warnings in your code where you could not find the culprit hidden in those compiler headers. The link of user34341 is not a bad start, although I have some problems following along precisely. And the env-vc9.lnt from the Gimpel website assumes that you have installed PC-lint with their installer. Reading between the lines of your question, I guess you have not. The details of creating such an installation including the generation of the PC-lint option file std.lnt take us too far for this answer, but I have written a PDF document "How to wield PC Lint" explaining this all in painful detail. If you combine the link from user34341, the options file from Gimpel and my document, you should be OK. Furthermore: The env-vc9.lnt only contains the option for using the VC9 environment (a.k.a Visual Studio); to support the C/C++ compiler you'll need the appropriate compile option file http://www.gimpel.com/html/pub80/co-msc90.lnt and its associated (Lint-only) header file http://www.gimpel.com/html/pub80/co-msc90.h. So before you start integration in VS2008, download them and try this command line: lint-nt.exe +cpp(cpp,cxx,cc) co-msc90.lnt myfile.cpp and see if the results are better than before. The -ioption was OK, but if you have the environment variables (e.g. %INCLUDE%) set up correctly for Visual Studio, it shouldn't be necessary. And one more hint: Assuming you have not done so already, look at the version of PC-lint you have available, and make sure to update to the latest patch level: 7.50ad, 8.00x, 9.00i (current version); the links under the version numbers take you to the appropriate website page. It will save you a lot of trouble. I know that getting the latest version is not always an option, even if highly preferable.
{ "pile_set_name": "StackExchange" }
Q: Do I have to pay taxes on income from my website or profits? I've started to generate a small amount of revenue on my website, I'm obviously tracking my income and expenses, but I'm not certain whether I need to declare this income to Inland Revenue. Is there a threshold of earnings before I need to declare? and do I deduct my expenses from the income? A: I am not an accountant, but I do run a business in the UK and my understanding is that it's a threshold thing, which I believe is £2,500. Assuming you don't currently have to submit self assessment, and your additional income from all sources other than employment (for which you already pay tax) is less than £2,500, you don't have to declare it. Above this level you have to submit self assessment. More information can be found here I also find that HMRC are quite helpful - give them a call and ask.
{ "pile_set_name": "StackExchange" }
Q: What is this white, ribbed, box shaped object attached to a somewhat-remote tree near Lake Chelan? While hiking near Lake Chelan (Washington, USA), I noticed this item affixed to the tree located at 48.150978, -120.493732: The tree in question is a short hike from a boat landing and right off a trail, but the area overall is fairly remote (designated wilderness). I was unable to find any markings or other identification clues on the object. It appears to have been placed a while ago, as the screws holding it have been pulled almost completely out of the tree. The item primarily comprises a white, ribbed, rounded rectangular prism approximately 7x5x6". A: Possibilities: Some form of remote sensor, Perhaps they wanted to monitor microclimate values of temp and humidity on a long term basis. Bug trap. The container fastens with wingnuts, while the bracket appears to be screwed or nailed. By implication the container was intended to be replaced/inspected multiple times. Bug trap would fit this, as would pollen trap. Finding more information. Since you have coordinates, find out what national/state forest/park that your location corresponds to. Drop by their office and see if they have a record of any research projects in that area. They are likely to redirect you to one or more scientists connected to a local university.
{ "pile_set_name": "StackExchange" }
Q: Table in Visualforce page using AngularJs Can anyone tell me how to create table in Visualforce page using angularJs. Below code is am trying to implement but it doesnt work <apex:page > <html> <head> <script src="https://code.angularjs.org/1.2.0-rc.3/angular.js"></script> <script src="https://bazalt-cms.com/assets/ng-table/0.3.0/ng-table.js"></script> <link rel="stylesheet" href="https://bazalt-cms.com/assets/ng-table/0.3.0/ng-table.css" /> <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" /> <style> body { padding: 10px !important; } .ng-table tr.emphasis td { background-color: #DDD; font-weight: bold; } </style> <script> //defining module var app = angular.module('main', ['ngTable']); main.controller('DemoCtrl', function($scope, $filter, ngTableParams) { var data = [{name: "Moroni", age: 50}, {name: "Tiancum", age: 43}, {name: "Jacob", age: 27}, {name: "Nephi", age: 29}, {name: "Enos", age: 34}, {name: "Tiancum", age: 43}, {name: "Jacob", age: 27}, {name: "Nephi", age: 29}, {name: "Enos", age: 34}, {name: "Tiancum", age: 43}, {name: "Jacob", age: 27}, {name: "Nephi", age: 29}, {name: "Enos", age: 34}, {name: "Tiancum", age: 43}, {name: "Jacob", age: 27}, {name: "Nephi", age: 29}, {name: "Enos", age: 34}]; $scope.tableParams = new ngTableParams({ page: 1, // show first page count: 5 // count per page }, { total: data.length, // length of data getData: function($defer, params) { // use build-in angular filter var orderedData = params.sorting() ? $filter('orderBy')(data, params.orderBy()) : data; $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); } }); }); </script> </head> <body ng-app="main" ng-controller="DemoCtrl"> <table ng-table="tableParams" class="table"> <tr ng-repeat="user in $data" > <td data-title="'Name'"> {{user.name}} </td> <td data-title="'Age'"> {{user.age}} </td> </tr> </table> </body> </html> </apex:page> My Expectation Result would be But It gives like I dono whats wrong in my code Thanks in advance Karthick A: If you look in the JavaScript console - when working on code like this you must use the techniques described in How do I start to debug my own Visualforce/JavaScript? - you will see these errors: GET https://bazalt-cms.com/assets/ng-table/0.3.0/ng-table.css net::ERR_INSECURE_RESPONSE ang:31 GET https://bazalt-cms.com/assets/ng-table/0.3.0/ng-table.js net::ERR_INSECURE_RESPONSE ang:29 letting you know that these files are not being loaded for security reasons because they are not hosted appropriately. I don't know of a reliable CDN location to load these from, so the simplest thing to do is to manually get hold of them and add them as static resources to your project so your can reference them from Salesforce's servers like this: <script src="{!$Resource.NgTableJs}"></script> <link rel="stylesheet" href="{!$Resource.NgTableCss}" /> There is also then the error that this: var app = angular.module('main', ['ngTable']); should be this: var main = angular.module('main', ['ngTable']); With these two changes the table is rendered. Note that there are other approaches to client-side paginated and sorted tables in Visualforce, such as adding DataTables to a normal Visualforce table.
{ "pile_set_name": "StackExchange" }
Q: Should BLK and GRN of Pro Mini be connected to upload sketch? Is the following connector is valid for Arduino Pro Mini (no BLK and GRN)? I was told to make a certain Arduino application, and got some Arduino Pro Mini (ATmeag328 3.3V 8 MHz) with the connector above. Everytime I tried to upload an example sketch 'Blink', the IDE complains (verbose enabled): avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x83 ... avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x83 resp may differ (I saw 0x1f and 0x83) But, according to the official document, I think that I should use some FTDI thing, which has 6 pins including BLK and GRN. I wonder whether I can use the existing 4-pin connector, or whether I must use 6-pin FTDI connector. A: If you look at the picture in your link, you would see that BLK is ground (GND) and GRN is DTR, that is used to reset the board and enter the bootloader for programming. As Majenko said, without DTR you will need to press the reset button at the right time, to enter the bootloader.
{ "pile_set_name": "StackExchange" }
Q: Print empty string for a missing key and converting the result to CSV I am trying to convert belowJSON to CSV using jq command but the final CSV is unable to place deviceName field properly as it's missing in some JSON lines. { "id": "ABC", "deviceName": "", "total": 100, "master": 20 } { "id": "ABC", "total": 100, "master": 20 } How can i make sure empty value gets when Key is missing ?. I Tried below command to generate CSV ./jq -r '[.[]] | @csv' > final.csv But it gives CSV like below as you can see when deviceName key is missing in JSON it's cell shifting left side. "ABC","",100,20 "ABC",100,20 I want output something like below which adds empty value if deviceName is missing. "ABC","",100,20 "ABC","",100,20 A: In jq you can use the alternate operator // that can be used to return default values. E.g. .foo // 1 will evaluate to 1 if there's no .foo element in the input Using that and appending an empty string "" if the key is not present, you can do jq -r '[.id // "", .deviceName // "", .total // "", .master // ""] | @csv' Note: The alternate operator .foo // 1 causes the evaluation to 1 for case when the value of foo is null or false. You may wish to modify the above program if your data contains null or false values.
{ "pile_set_name": "StackExchange" }
Q: Runtime Error Cannot read property 'environment' of null - Ionic Google Maps I'm setting up my Ionic app and I've followed the Google Maps API documentation precisely. However, I have not been able to escape this error I keep getting when I try to run the Maps API: And then this is my full code from the HomePage. I have made sure to put in a div in the home.html with the id="map_canvas" as well as set the height to 100% in the scss file for it. From what I've seen, the error seems to not like the Environment part, but I have made sure my API key is correct and I've run the correlating cordova commands to set up the google maps plug in. I just cannot see what could be causing this error. import { GoogleMaps, GoogleMap, GoogleMapsEvent, GoogleMapOptions, Marker, Environment } from '@ionic-native/google-maps'; import { Component } from "@angular/core/"; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { map: GoogleMap; constructor() { } ionViewDidLoad() { this.loadMap(); } loadMap() { // This code is necessary for browser Environment.setEnv({ 'API_KEY_FOR_BROWSER_RELEASE': 'I_ENTERED_MY_UNRESTRICTED_API_KEY_HERE', 'API_KEY_FOR_BROWSER_DEBUG': '' }); let mapOptions: GoogleMapOptions = { camera: { target: { lat: 43.0741904, lng: -89.3809802 }, zoom: 18, tilt: 30 } }; this.map = GoogleMaps.create('map_canvas', mapOptions); let marker: Marker = this.map.addMarkerSync({ title: 'Ionic', icon: 'blue', animation: 'DROP', position: { lat: 43.0741904, lng: -89.3809802 } }); marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe(() => { alert('clicked'); }); } } A: You need to build it for whatever platform that you want to use (ex. browser, android, ios) using ionic cordova build browser -l and then this will create the environment for it and thus it will be running. It does not simply work using ionic serve
{ "pile_set_name": "StackExchange" }
Q: How I can bypass "angular-in-memory-web-api" for a specific url I was using "angular-in-memory-web-api" to mock my REST web api, however now I am have started writing the actual web api and I want to replace the "angular-in-memory-web-api" step by step. Example: I have written following asp.net web api /api/values however when I issue http.get() request using above api url angular tries to serve it using "angular-in-memory-web-api", however in this case I want to bypass "angular-in-memory-web-api" so that request is entertained by my actual web api controller. A: you can set passThruUnknownUrl to forward to real backend for un-matching endpoints e.g., InMemoryWebApiModule.forRoot(InMemoryDataService, { passThruUnknownUrl: true }),
{ "pile_set_name": "StackExchange" }
Q: can I send some users to one url; others to another? I currently have a login page that sends all authenticated users to a main page. How do I configure my code such that one group of users are sent to a specific url (custom main page), and other groups are sent to other urls? The grouping of users would be done according the company they work for. Each group of company's employees would be directed to an area of the site where they could see records from their company, but not others. The existing login view is very simple: def login_page(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect("main_page.html") else: return HttpResponseRedirect('/') else: return HttpResponseRedirect('/') A: A relatively simple way to do it would be to create a field in the user profile to indicate that the user is a part of the special group of users you want to redirect to the special page. Then, upon logging in, check for the flag in the user's profile and redirect accordingly.
{ "pile_set_name": "StackExchange" }
Q: .htaccess not functioning as expected This seems super simple.. But I can't for the life of me figure it out. I am designing a page: index.html. I would like to redirect ALL traffic to index.html. The caveat is, that I have two images on this page. image1.jpg and image2.jpg ... That will end up being a redirect that will never complete. So I have come up with the following: # Turn On ReWrite Engine RewriteEngine On # Exclude image1.jpg and image2.jpg from redirecting RewriteCond %{REQUEST_URI} !^/(image1|image2)\.jpg # Redirect to index.html RewriteRule . index.html [NC,L] It works .. IE if I go to: http://mysite.com/nothing It works flawelessly. What I can't figure out, is if I go in one directory, the images won't show .. IE http://mysite.com/direcotry/file.whatever How do I get the images to show when URL is in "nth" number of directories?? A: This is very common problem people face when they start using so-called pretty URLs. Solution: Solution is to use absolute URLs for including your image, css and js files. Make sure URLs in src attribute always start with either a forward slash (/) or with http://.
{ "pile_set_name": "StackExchange" }
Q: about CONFIG_NO_HZ in kernel So if CONFIG_NO_HZ is set, I believe it will make a tickless kernel. But I believe this just means when the system is idle, it might become tickless in order to save energy. When it's working, it is still tick kernel, right? Thanks:> A: Essentially, yes. There are ongoing projects to make the periodic tick go away also when not idle, but that's a lot of work with many changes, and it's unclear whether it will ever be completed.
{ "pile_set_name": "StackExchange" }
Q: What does this spear & carpentry square symbol mean? What does this symbol (placed on the shield being held by an angel figure) mean? Is there any historical explanation for what it represents? A: The square and spear are emblems of St. Thomas, the Apostle, aka Doubting Thomas. He was well known as a builder in his lifetime, though I have my doubts that he participated in all the constructions listed on the site linked to above. This explains the builder's square in the emblem. St. Thomas was stabbed to death by the spear represented in the emblem, c 72 AD. This shield emblem might represent St. Thomas himself, or have denoted that the bearer regarded St. Thomas as a patron. Here is a link to a page of similar symbols for emblems of Thomas the Apostle.
{ "pile_set_name": "StackExchange" }
Q: How to assign a nullable object reference to a non-nullable variable? I am using VS2019 and has enabled nullable check semantics in project setting. I am trying to get the executable's path using assembly as below: var assembly = Assembly.GetEntryAssembly(); if (assembly == null) { throw new Exception("cannot find exe assembly"); } var location = new Uri(assembly.GetName().CodeBase);//doesn't compile. It says, "assembly" is a [Assembly?] type, while the Uri ctor requires a string, compilation error is: error CS8602: Dereference of a possibly null reference. How to fix my code to make it compile? Thanks a lot. A: Your problem is that AssemblyName.CodeBase is nullable: it's of type string?. You need to add extra code to handle the case where .CodeBase is null (or suppress it with !), e.g: var codeBase = Assembly.GetEntryAssembly()?.GetName().CodeBase; if (codeBase == null) { throw new Exception("cannot find exe code base"); } var location = new Uri(codeBase); or var location = new Uri(assembly.GetName().CodeBase!); The actual warning you get in this case is nothing to do with assembly, it's: warning CS8604: Possible null reference argument for parameter 'uriString' in 'Uri.Uri(string uriString)'. Source (expand the "Warnings" pane on the lower right). This tells you that the problem is with the string being passed into the Uri constructor, i.e. the string returned from .CodeBase. A: You can use null-forgiving operator ! to tell the compiler that CodeBase can't be null var location = new Uri(assembly.GetName().CodeBase!); or use a null-coalescing operator ?? with some default value var location = new Uri(assembly.GetName().CodeBase ?? string.Empty); The error CS8604: Possible null reference argument for parameter 'uriString' in 'Uri.Uri(string uriString)' usually treated as warning, it seems that you've enabled this option in project settings
{ "pile_set_name": "StackExchange" }
Q: code coverage with visual studio and gtest Has anyone ever used gtest with visual studio? if so, how did you get code coverage reports? I'd like to configure my project to produce coverage data, but it seems like nobody else uses gtest/visual studio with gcov or any other code coverage. A: I asked around the office, and someone suggested this tool: https://opencppcoverage.codeplex.com/ I will give it a try. I will come back and report the results.
{ "pile_set_name": "StackExchange" }
Q: LXC - Linux Containers - Add new network interface without restarting Searching on google, there's only way to add new network interface is adding to config file. Is there any lxc command that we can add lively, (don't need to restart the container)? The page mentioned how to add second network interface: http://box.matto.nl/lxctwonics.html Thanks! A: It would very much depend on the configuration of the interface you're trying to add to the container. If you have an existing interface on your host which you want to be visible inside the container: # on the host: pid=$(lxc-info -pHn foobar) ip link set dev eth3 netns $pid name eth1 This will cause your host's eth3 interface to be moved to the container foobar, renamed to eth1. This is roughly equal to this configuration: lxc.network.type=phys lxc.network.link=eth3 lxc.network.name=eth1 Another useful scenario would be to create a new interface inside the container, bridged to an existing bridge on the host: # on the host: pid=$(lxc-info -pHn foobar) ip link add name veth0 type veth peer name veth0_container brctl addif br0 veth0 ip link set dev veth0_container netns $pid name veth0 This will create a pair of connected virtual-ethernet interfaces (veth0 and veth0_container), add one of them to the br0 bridge, and move the other into the container foobar. This is roughly equivalent to this configuration: lxc.network.type=veth lxc.network.link=br0 lxc.network.name=veth0
{ "pile_set_name": "StackExchange" }
Q: Implementing my own ArrayList using arrays I have a project I have been assigned in java and I have to basically create my own class that mimics basic features of the ArrayList class. I have to do it in the format shown below using these variables but I am stuck on one part. When the array fills up I want to make a new one with 10 extra spaces, then copy all the old array elements to the new one and use that from now on. How do I make my program automatically use this array from now on? Because it will continue to use the first array. public MyArrayList() { array = new String[10]; arraySize = 10; arrayElements = 0; } public void add (String string) { if (arrayElements < arraySize) { array[arrayElements] = string; arrayElements++; } else { arraySize += 10; arrayElements++; String[] array2 = new String[arraySize]; for (int i = 0; i < arrElements;i++) { array2[i] = array[i]; } //missing code here I think? array2[arrayElements] = string; } } A: Assign array2 to the array reference. Something like, //missing code here I think? array2[arrayElements] = string; array = array2; Or, use Arrays.copyOf(int[], int) and something like arraySize += 10; arrayElements++; array = Arrays.copyOf(array, arraySize); // <-- will pad with zeros.
{ "pile_set_name": "StackExchange" }
Q: Physical meaning of NCP (not completely positive) maps 1) Even with not completely positive maps, if we can find a domain in which the action of the map is positive, why should we restrict the reduced dynamics of an open system to being exclusively completely positive? Also, what could such maps indicate physically about the system? 2) What are the arguments put forward to justify completely positive maps for describing reality? Is it always possible to decouple the system from the environment and vanish the correlation terms to ensure the evolution of the joint state to be CP (completely positive)? A: If a map $\mathcal E$ is NCP, then it will produce unphysical states for some input states that are correlated with other "external" systems. Therefore, either you say that it is not possible (as in, it makes no physical sense) for that map to act on those states, or QM is to be changed to make sense of non-positive output states. The former case is also weird though, because the restriction on the input state is really a restriction over the possible extensions of such states. In other words, you are not saying that $\mathcal E$ cannot act on $\rho$ for whatever reason, but that $\mathcal E$ can act on $\rho$ as long as $\rho$ is not correlated with something else. Physically speaking, the existence of an NCP map would mean that you can build a box such that when you put in states correlated with some external systems, you get output states which on a first glance may appear to be proper states (as the output reduced state is still a physical state), but that when you look more carefully (that is, you look at the global output state, taking into consideration also the other system the input was correlated with) you realize has produced something which makes no sense. Note that while this means that NCP maps are not physically meaningful maps, they are still of the utmost importance, among other things, for the theory of entanglement. Indeed, it is a standard result that a state is separable if and only if its positivity is preserved by all positive maps. In this sense, the separability problem is equivalent to the classification of all positive maps.
{ "pile_set_name": "StackExchange" }
Q: Import Data different column length Lets assume, i have this data.txt file. s1/km t1/h s2/km t2/h 20 1 40 1 40 2 80 2 60 3 I define myself a function for processing deleteRows[expr_] := Replace[expr, x_List :> DeleteCases[x, {}], {0, Infinity}] Then import the file: data = deleteRows@Import["data.txt", "Table"][[2 ;;]] Everythings works fine till now. But if I want to select the 3rd column it breaks. data[[All, 3]] How do I deal with such situations? A: Maybe this: dataraw = Import["data.txt", "Table", "IgnoreEmptyLines" -> True, "HeaderLines" -> 1] {{20, 1, 40, 1}, {40, 2, 80, 2}, {60, 3}} Then for example: data = PadRight[dataraw, {Automatic, Automatic}, "NA"] {{20, 1, 40, 1}, {40, 2, 80, 2}, {60, 3, "NA", "NA"}} Finally, data[[All, 3]] {40, 80, "NA"} A: Using R/RLink Since this scenario happens fairly often when doing data analysis here is a solution using R (through RLink): Needs["RLink`"] InstallR[] rres = REvaluate[ "read.table( file = \"./data.txt\", quote = \"\", header = TRUE, fill = TRUE, stringsAsFactors = FALSE)"] (* RDataFrame[RNames["s1.km", "t1.h", "s2.km", "t2.h"], RData[{20, 40, 60}, {1, 2, 3}, {40, 80, Missing[]}, {1, 2, Missing[]}], RRowNames[1, 2, 3]] *) data = Transpose[ List @@ rres[[2]] ]; data[[All, 3]] (* {40, 80, Missing[]} *) Note the parallels with the solution by SquareOne.
{ "pile_set_name": "StackExchange" }
Q: Intrinsic vs. Extrinsic Undoubtedly, these terms play essential roles in (pure) mathematics. My problem is that I have feelings what they mean in different fields, such as, differential geometry (abstract manifolds vs. embedded ones), algebraic geometry (more down to earth, the study of Riemann surfaces and algebraic curves) when our objects can be embedded differently and each embedding gives us (I think) extrinsic properties rather than intrinsic ones, and intrinsic properties do not have anything to do with embeddings. What I would like to know are as follows; Can they be defined, precisely? How can one recognize which properties are coming from intrinsic properties and which are not? I would appreciate any comments in helping me understand them better. A: Intrinsic properties are those which are invariant under isomorphism, whatever that notion happens to mean in the category under consideration. Edit: I guess I would say also that an extrinsic property of an object is not a property of the object itself but a property of the object together with some other data, for example the object together with a map to or from some other specified object. A: Premise: The adjectives intrinsic and extrinsic come from the Latin intrinsecus ("inner") and extrinsecus ("outer"), from the adverbs intra resp. extra, and the p.p. secutus of the verb sequor ("follow"). In the context of category theory, if we want to play the game of "non-philological (i.e. a posteriori) etymology", it is tempting to refer follow to arrows. I would therefore say that intrinsic is a categorical property of an object, which is stated by means of its only structure and self-maps, while extrinsic is a categorical property of an object which also depends from other objects and maps with different domains or co-domains. In this sense, compactness is an intrinsic property of topological spaces, while e.g. the homotopy extension property, or being an ANR, are extrinsic properties; in fact, most universal properties are. (But, I repeat, this is just a suggestion).
{ "pile_set_name": "StackExchange" }
Q: Python Imports Convention I've noticed in Python code it's usually preferred to import explicitly the parts of a module you need, eg from django.core.urlresolvers import reverse from django.db import models However, I've noticed that this doesn't seem to be the case for Python standard library modules, where I'd typically see, eg: import os import sys something = os.path.join('home', 'ludo') other = sys.argv('dunno') instead of from os.path import join from sys import argv something = join('home', 'ludo') other = argv('dunno') Is there any reasoning or documented convention for this? A: The holy style guide is pretty loose regarding this subject: When importing a class from a class-containing module, it's usually okay to spell this: from myclass import MyClass from foo.bar.yourclass import YourClass If this spelling causes local name clashes, then spell them import myclass import foo.bar.yourclass and use "myclass.MyClass" and "foo.bar.yourclass.YourClass". There aren't really any 'rules' for this, just some pointers as mentioned above. If you are not obstructed by e.g. name clashing, you are free to do as you see fit. However, as also mentioned in the link, you should keep in mind that Wildcard imports ( from import * ) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools.
{ "pile_set_name": "StackExchange" }
Q: When Profiling Javascript in Chrome how do I know I've handled Memory Leaks? I've been working on a game in for HTML 5 using the canvas tag, and I've build up quite a code base to cover my requirements. I also want to make sure I'm covering up all my memory leaks. I have doubts I'm doing it correctly because the feedback I'm getting from Chrome's task manager and profiling tools seem to suggest my cleanup is having no effect in the end. Here's an image so you can see what I mean: So as you can see, once I do my cleanup memory usage just freezes and doesn't drop. Is this a memory leak? When I ran my webpage in the Profiler and checked the heap before and after cleanup it does appear to remove all the references to my objects (and they disappear) but my usage only drops by only a few kilobytes leaving about 1.3mb of arrays, strings, and other objects behind. Is it impossible to catch all this or is there something majorly wrong? Thanks. A: At the bottom of the profiler window there is an icon that looks like a trash can, it will force a GC pass. Hit it and see if it clears up the rest of the memory. It's possible Chrome/V8 just doesn't think the memory situation is bad enough to require garbage collection to run.
{ "pile_set_name": "StackExchange" }
Q: Towards a Stackexchange-like comment/reputation system for research papers We have had quite a few discussions on how to gauge the quality of research papers and academic journals. The consensus is that it is tough to identify a single metric which could reveal this quality factor. I had an idea in this context. In the past newspapers used to have a single "Letters to Editor" section to which comments on all articles were sent. With the advent of the Net, we have a comments section under every article. Similarly, why don't reputable journals introduce a comment space for their published papers, where fellow researchers could appreciate/criticise/query the works? What hinders us from having a reputation system for published papers - something where registered users could vote based on their perceived utility? A: Similarly, why don't reputable journals introduce a comment space for their published papers, where fellow researchers could appreciate/criticise/query the works? They don't need to create such a space, since these comments can already appear elsewhere on the internet. Nevertheless, some journals have tried, but they typically attract very few comments, and nobody knows how to create a viable community this way. See that link (and the blog posts it links to) for further discussion. What hinders us from having a reputation system for published papers - something where registered users could vote based on their perceived utility? One major obstacle is that not enough people seem to want to use such a system. There have been many attempts to set one up, but none have caught on. However, there's a deeper obstacle. In order to get any meaningful results at all, you need to solve at least three problems: ensuring that votes come only from competent researchers, ensuring that nobody can deliberately manipulate the system or cheat, and ensuring that voters have the right incentives even if they are not trying to be dishonest. In principle, it might be possible to solve these problems, but it would take a nontrivial infrastructure. However, the more elaborate the system becomes, the harder it will be to get lots of users. A large majority of researchers won't pay any attention to a system like this, and some of the ones who do care will be strongly opposed, so getting widespread adoption will be an uphill battle. A: As a follow up to Anonymous Mathematician's answer, I think the answer lies in Arxiv: a lot of people already use it, there is no profiting involved and even if a paper is moved to a given journal, the paper's page main remain online with all discussions In it (except that the PDF is replaced with a link). So it can create a solid up/down voting system. As for reputation, everyone may start equally but a Web of Science citation analysis,for example, may be used to yield a larger starting reputation to get things going. Going further, this may also replace the reviewing process: the paper is uploaded, everyone may read it and someone who thinks it is interesting may then apply as a candidate reviewer. This would avoid reviewers who don't really understand about your work (as is certainly not uncommon to happen). It is a leap of faith to trust a reputation system rather than a faculty hierarchy. Notwithstanding, note that the current review system is already embalmed in such trust: even a high school student can publish a paper if it is reviewed to be interesting; conversely, if you publish nice papers you are invited to review nice papers. In a sense, this shifts the focus away from the periodicals themselves. A: For an update, you might want to have a look at probably the largest organized group discussing this and similar issues - FORCE http://www.force11.org/ - stands for "The future of research communication and e-scholarship" In Manifesto they say that new models of reputation are required, etc. However, a ready to use system is not yet developed
{ "pile_set_name": "StackExchange" }
Q: Change the view's path on the fly I have this class: public abstract class MyController : Controller { protected override void OnActionExecuting(ActionExecutingContext filterContext) { string viewPath = filterContext/*... .ViewPath*/; viewPath = "Some new View Path"; } } And I'd like to retrieve and replace the executing view's path by another one. I have tried to debug-view the filter context on a web call, however I did not manage to find a view which is about to render. How do I do that? A: From MSDN: Controller.OnActionExecuting Method: Called before the action method is invoked. At this stage, no ActionResult exists since the Action didn't execute yet. You better use the OnResultExecuting instead: protected override void OnResultExecuting(ResultExecutingContext filterContext) { var viewResult = filterContext.Result as ViewResult; if (viewResult != null) { var razorEngine = viewResult.ViewEngineCollection.OfType<RazorViewEngine>().Single(); var viewName = !String.IsNullOrEmpty(viewResult.ViewName) ? viewResult.ViewName : filterContext.RouteData.Values["action"].ToString(); var razorView = razorEngine.FindView(filterContext.Controller.ControllerContext, viewName, viewResult.MasterName, false).View as RazorView; var currentPath = razorView.ViewPath; var newPath = currentPath.Replace("..", "..."); viewResult.View = new RazorView(filterContext.Controller.ControllerContext, newPath, razorView.LayoutPath, razorView.RunViewStartPages, razorView.ViewStartFileExtensions); } base.OnResultExecuting(filterContext); }
{ "pile_set_name": "StackExchange" }
Q: DNS Server and Private HTTP / SOCKS Proxy this is just a small hacking attemp to our router. I'm trying to setup a small DNS and forward webpages through proxy behind the scene. I've successfully implement the DNS server that will do the resolving or anything involved in address resolve. But is there anyway I can forward the user using DNS to a proxy instead of request directly to the server? Are there any software/opensource that I can use? I notice on paid wireless, they can provide a login page if user is not login yet, i think this is a way of implementing proxy. Also the hardware is very basic with linksys and netgear router which connect directly to the internet. It's a basic LAN A: I may be answering the wrong question because you are talking about using DNS to give false replies, but I will give this answer any way in case this is what you really want to be doing (if you want to implement a login-type page for all users). You want to implement something known as a "Walled Garden" or, if you look in Wikipedia, a "Captive Portal". Learn IPTables - you will most likely want a default rule that forwards all traffic to your HTTP server. Your HTTP server will then have an intelligent page that updates a database or similar with the IP addresses that have a valid login and consequently a script will update your iptables rules with those ip addresses permitted access to the Internet. You would create a chain called "garden", and add the following rules to it which would force all traffic except DNS to be forwarded to 192.168.1.1: iptables -A garden -p tcp --dport ! 53 -j DNAT --to 192.168.1.1 iptables -A garden -p udp --dport ! 53 -j DNAT --to 192.168.1.1 Then in the appropriate chain (be it NAT or whatever) add a rule to jump to the "garden" chain if not a registered valid IP address.
{ "pile_set_name": "StackExchange" }
Q: Multiple Sink for Azure Data Factory pipeline In Azure Data Factory pipeline, Can I have a copy activity with two SINKs? I have one source and 2 sinks (One Azure Data lake store for downstream processing and the other for archival on Blob Storage). A: That’s definitively possible. Just add a second activity in the same pipeline with the same Input dataset but a different output dataset. The JSON will then look something like this: { "$schema": "http://datafactories.schema.management.azure.com/schemas/2015-09-01/Microsoft.DataFactory.Pipeline.json", "name": "CopyActivity1", "properties": { "description": "Copy data from blob to a sql server table", "activities": [ { "name": "CopyActivityTemplate", "type": "Copy", "inputs": [ { "name": "AzureBlobLocation1" } ], "outputs": [ { "name": "AzureSqlTableLocation1" } ], "typeProperties": { "source": { "type": "BlobSource" }, }, { "name": "CopyActivityTemplate2", "type": "Copy", "inputs": [ { "name": "AzureBlobLocation1" } ], "outputs": [ { "name": "AzureSqlTableLocation2" } ], "typeProperties": { "source": { "type": "BlobSource" }, }, } ], "start": "2016-12-05T22:00:00Z", "end": "2016-12-06T01:00:00Z" } }
{ "pile_set_name": "StackExchange" }
Q: Which signal >(process) receives after main shell exits? This is a Zshell question, although Bash, if it has >(command) syntax (i.e. process substitution of such kind), can hint a solution too. This really basic code explains all: % fun() { setopt localtraps trap "echo waiting >> /tmp/out; sleep 2; echo bye >> /tmp/out; exit 1;" EXIT echo "My PID: $sysparams[pid]" # needs zsh/system module repeat 1000; do read -r -t 1 line done } % exec {MYFD}> >(fun) % exit Above works – fun() will receive the trap, the two messages will appear in /tmp/out and "exit 1" will close the process. My question: can be "EXIT" replaced by some actual signal? I've tried PIPE, HUP, INT, TERM and they didn't work. A: Your code doesn't explain all. I have no idea what you're trying to do. However, I can answer the question in your title: the >(…) process does not receive a signal when the main shell exits. It exits because it reaches the end of the script, and at this point it runs the EXIT trap until it executes the exit builtin. If you thought that the script is getting killed early because you thought the read -t 1 calls would take one second each: no, they don't, they return immediately as soon as the parent exits. When the parent exits, the read calls in the subshell are trying to read from a closed pipe, and the underlying read system call returns immediately with no data available.
{ "pile_set_name": "StackExchange" }
Q: Making a Gripper Changer for a Robotic Arm How do you make a gripper changer for a robotic arm like this? I don't see how you could connect power/control wires or what you use to hold the gripper to the arm. A: Mechanically, there are a variety of ways to fix the gripper to the arm. I think the easiest way is to have a little tab rotate under an overhang. At least one of the grippers shown in your video is pneumatic. (It is quite possible both are). In which case, the pneumatic connection is just a hole with a gasket or O-ring to seal it. Electrically, you can have pins on a connector slide into the housing on the other end. But i think that requires some pretty tight tolerances, and might wear out quickly. More likely, you can use something called "pogo pins". these are spring loaded contacts made for just this type of thing. it is also possible that your end-effector gripper can be actuated mechanically. this can be accomplished with gears, splines, or push rods i think.
{ "pile_set_name": "StackExchange" }
Q: Why am I getting the warning Hardware is initialized using a generic method in alsa setup? I am getting the warning in the alsa setup when my raspbain is booting. The error or warning is: Hardware is initialized using a generic method Why am I getting this one? I changed few alsa controls in my machine driver, thats all, after changing this I am getting that warning. A: If everything is working ok, I don't think this is anything other than informative. Why do you think it indicates an error? Not every message spit to console at boot indicates a problem -- in fact, most of them don't. Different software may use different priorities with the system logger in order to force stuff to the screen but that does not mean it is really urgent. Of course, if stuff is not working ok, then it might be a clue as to why. You might try this: grep -R "Hardware is initialized using a generic method" /var/log To see if this is being logged to file to, then you could have a look in the file to see if anything else pertinent was logged at the same time.
{ "pile_set_name": "StackExchange" }
Q: How to drop tables with no constraint checking I need to update the data and schema from dev to staging dbs where I want to DROP/CREATE a group of tables. I need to over-ride the FK constraint checks. Looking at the MS's ALTER TABLE syntax tree - i know it's there but i can't identify the correct syntax. @Rup: It looks like the hangup is from other tables' FKs. Is there a way to turn all constraint checking off or do i need to produce the list of tables/FKs? A: ALTER TABLE yourtable NOCHECK CONSTRAINT ALL and a variation on this theme is to disable all the constraints of all the tables delete all the data, and then add all the constraints back again. exec sp_MSforeachtable @command1='alter table ? nocheck constraint all', @whereand='and substring(o.name,1,1) <> ''_''' exec sp_MSforeachtable @command1='delete from ?' exec sp_MSforeachtable @command1='alter table ? check constraint all', @whereand='and substring(o.name,1,1)<> ''_''' The nice thing here is that with all the constraints disabled, you can delete the data in any order
{ "pile_set_name": "StackExchange" }
Q: Porting from 32-bit to 64-bit - any alternative to -Wp64 switch? I'm porting my 32-bit (Win32) application to 64-bit using VS 2012. I read on MSDN that -Wp64 switch helps with porting by generating warnings on pointer trunction et al so we can address them during the compilation phase before they become an issue at run-time. However, MSDN as well as the compiler output (in the output window) says that this option has been deprecated and in fact won't even be supported by later Visual Studio releases. I want to know if there's a better alternative to -Wp64 that will be supported by future Visual Studio versions too. A: This article is to answer some questions related to safe port of C/C++ code on 64-bit systems. The article is written as an answer to the topic often discussed on forums and related to the use of /Wp64 key. Try PVS-Studio 64-bit Rules Set for detect 64-bit issues (support Visual Studio 2010-2017). Also I am recommend read this: the course will consider all steps in creating a new safe 64-bit application, or migrating the existing 32-bit code to a 64-bit system.
{ "pile_set_name": "StackExchange" }
Q: Tkinter new window I'm relatively new to Tkinter and I need help. I have created a new window when a button is clicked from the parent window. The new window is the def new_Window. But I can't seem to get the information in the window as coded below: from tkinter import * from tkinter import ttk #User Interface Code root = Tk() #Creates the window root.title("Quiz Game") def new_window(): newWindow = Toplevel(root) display = Label(newWindow, width=200, height=50) message = Label(root, text="Welcome") display.pack() message.pack() display2 = Label(root, width=100, height=30) button1 = Button(root, text ="Continue", command=new_window, width=16, bg="red") message_label = Label(root, text="Click 'Continue' to begin.", wraplength=250) username = StringVar() #Stores the username in text user_entry = Entry(root, textvariable=username) #Creates an entry for the username user_entry.pack() display2.pack() button1.pack() message_label.pack() root.mainloop()#Runs the main window loop Thanks for your help. A: You did not pack the hello label into the new window. A tip is also to use background colors to visualize labels when developing. Here is a functioning code for you. I only changed 2 lines, added foreground and background. from tkinter import * from tkinter import ttk # User Interface Code root = Tk() # Creates the window root.title("Quiz Game") def new_window(): newWindow = Toplevel(root) display = Label(newWindow, width=200, height=50,bg='RED') message = Label(newWindow, text="HEEEY",fg='BLACK',bg='GREEN') message.pack() display.pack() display2 = Label(root, width=100, height=30) button1 = Button(root, text ="Continue", command=new_window, width=16, bg="red") message_label = Label(root, text="Click 'Continue' to begin.", wraplength=250) username = StringVar() # Stores the username in text user_entry = Entry(root, textvariable=username) # Creates an entry for the username user_entry.pack() display2.pack() button1.pack() message_label.pack() root.mainloop() # Runs the main window loop
{ "pile_set_name": "StackExchange" }
Q: JavaScript: How to create an object having its string name I have a namespace and class declared in the client. In fact, I have a whole bunch of classes declared in several namespaces. I just need to get an instance of one of them when I get a string from the server on page load that contains the "dotted" namespace.class names. Currently I use eval to do that but this causes a memory leak, so I'm trying to find an alternative way of instantiating a declared object by knowing only its name. Things like var obj = "myNamespace.myObjectName"(); won't work, obviously. If I have an object name as a string variable I can use the eval() function to create an instance of that object: window["myNamespace"] = {}; myNamespace.myObjectName = function() { /* blah */ }; var name = "myNamespace.myObjectName"; var obj = eval("new " + name + "()"); But for several reasons I don't want/cannot to use the eval. How can I create an object by its name without using the eval? A: It sounds like you don't control the content of the name variable, so you're stuck with the . being part of the string. Therefore, you can .split() the string into its name parts, and use .reduce() to traverse from the base object. window["myNamespace"] = {}; myNamespace.myObjectName = function() { this.foo = "bar" }; var name = "myNamespace.myObjectName"; var obj = newObjectFromStringPath(name); document.querySelector("pre").textContent = JSON.stringify(obj, null, 4); function newObjectFromStringPath(path, base) { return new (name.split(".").reduce(function(obj, name) { return obj != null ? obj[name] : null }, base || window)) } <pre></pre> The newObjectFromStringPath is coded to specifically target a function and call it as a constructor. You can easily make this work to fetch any value by simply removing the new in that function.
{ "pile_set_name": "StackExchange" }
Q: copy folder, subfolders and files from a path to another path in python via a recursive function I want to copy some folders and files from a path to another path. for example, I want to copy the folder(called folder1) which has some other subfolders and some files inside itself to another folder(dst). In my program, at the first, I want to check if there is a folder named folder1 in destination folder and if not, create a folder with folder1 name and then copy the content of folder1 to target. In addition, maybe we have folder1 in the target path, but there are some subfolders of folder1 which don't exist in target and we must use a recursive function for that. Here is my recursive function for this purpose: def CopyFol_Subfolders(src, src_folder, dst): Dir = next(os.walk(src))[1] sub_files = "" sub_files = next(os.walk(src))[2] if not os.path.exists(dst + "/" + src_folder): os.makedirs(dst + "/" + src_folder) shutil.copy2(src + "/" + src_folder, dst + "/" + src_folder) elif os.path.exists(src + "/" + src_folder) and is_exist_file(src+"/"+src_folder,dst+"/"+src_folder,sub_files): copy_files(sub_files, src+"/"+src_folder, dst+"/"+src_folder) else: subfolders = "" subfolders = next(os.walk(src + "/" + src_folder+"/"))[1] for folder in subfolders: CopyFol_Subfolders(src + "/" + src_folder, folder, dst + "/" + src_folder) the copy_files function will copy the files from src +"/"+src_folder to dst+"/"+src_folder I be confused and this does not work. I got different errors in shutil.copy2 which tell me x is not a file or x is a directory. Can please some one check logic of my recursive function and let me know what is this problem? A: Use os.path.isdir instead of os.path.exists to ensure that it can only be a directory not a file. And os.path.join is better than concatenating path strings by ourselves. def CopyFol_Subfolders(src, dst): for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): CopyFol_Subfolders(s, d) else: shutil.copy2(s, d)
{ "pile_set_name": "StackExchange" }
Q: Python Open a txt file without clearing everything in it? file = io.open('spam.txt', 'w') file.write(u'Spam and eggs!\n') file.close() ....(Somewhere else in the code) file = io.open('spam.txt', 'w') file.write(u'Spam and eggs!\n') file.close() I was wondering how I can keep a log.txt file that I can write to? I want to be able to open a txt file, write to it, then be able to open it later and have the contents of the previous write still be there. A: Change 'w' to 'a', for append mode. But you really ought to just keep the file open and write to it when you need it. If you are repeating yourself, use the logging module.
{ "pile_set_name": "StackExchange" }
Q: Do I have to have an 'unregister' button on my users on an email altering application? Hey guys - I know this is not a strictly programming question but I'm building an application where users sign up to traffic alerts. I have the whole thing dusted but I haven't got an 'unregister button' I know its good UI to have one, but I was hoping if someone knew the legalities of the topic? The user can sign in and uncheck what alerts to receive, but not scrub their details - On the email sent I have an unsubscribe button. Seeing as this is going to the public, can I turn round to my boss and say "by law we need one" else he might just turn around and try and charge the client, and I don't agree with that for something so rudimentary A: Check out CAN-SPAM. One of the requirements for mass email marketing is a one-click unsubscribe button. See http://en.wikipedia.org/wiki/E-mail_marketing Specifically: To comply with the Act's regulation of commercial e-mail, services typically require users to authenticate their return address and include a valid physical address, provide a one-click unsubscribe feature, and prohibit importing lists of purchased addresses that may not have given valid permission.
{ "pile_set_name": "StackExchange" }
Q: AS3: Adding function to population loop Basically I have 2 movieclip objects with some code, currently just to trace them. The blue circles when clicked will say 'Blue' and the red ones when clicked will say 'Red'. This works fine in theory until I add a population loop, which adds more of them. Then only 1 of each colour correctly works, the rest are just 'mock' circles. I wish for each circle to tell me their colour. This is my code for the .fla: import flash.events.MouseEvent; BlueBall.addEventListener(MouseEvent.CLICK, fun1) function fun1(e:MouseEvent){ trace("Blue!"); } RedBall.addEventListener(MouseEvent.CLICK, fun2) function fun2(e:MouseEvent){ trace("Red!"); } and this is the population loop in an .as file: private function PopulateCircles():void { for (var i:int=0; i < 10; i++) { var blueCircle:BlueCircle = new BlueCircle(); this.addChild(blueCircle); var redCircle:RedCircle = new RedCircle(); this.addChild(redCircle); } } tldr; how do I get the on-click events to occur on every newly populated circle? A: Pretty easy, actually. Just as you subscribe method to listen the predesigned instances' events, you can subscribe via temporary variable references. As long, as the variable holds the reference (or a pointer in C++ terms), you can address the instance and do anything you could do to a predesigned MovieClip: private function PopulateCircles():void { var aRed:RedCircle; var aBlu:BlueCircle; for (var i:int = 0; i < 10; i++) { // If there are no mandatory constructor arguments, // you can omit the () brackets. aRed = new RedCircle; aBlu = new BlueCircle; // Disperse clips to random places. aBlu.x = 500 * Math.random(); aBlu.y = 500 * Math.random(); aRed.x = 500 * Math.random(); aRed.y = 500 * Math.random(); // Subscribe methods to newly created instances. aRed.addEventListener(MouseEvent.CLICK, fun2); aBlu.addEventListener(MouseEvent.CLICK, fun1); // You're operating inside 'this' object, // no need to explicitly point it out. addChild(aRed); addChild(aBlu); } }
{ "pile_set_name": "StackExchange" }
Q: Getting transactionid(xid) from SQL Is there a way to get transactionid(xid) from SQL query, or from plpgsql function body? version of PostgreSQL 9.3 A: http://www.postgresql.org/docs/9.3/static/functions-info.html#FUNCTIONS-TXID-SNAPSHOT txid_current() is probably what you are after. A: In PostgreSQL 10 or later consider txid_current_if_assigned() instead. The manual: same as txid_current() but returns null instead of assigning a new transaction ID if none is already assigned
{ "pile_set_name": "StackExchange" }
Q: Splitting field of cyclotomic polynomials over $\mathbb{F}_2$. Let $\Phi_5$ be the 5th cyclotomic polynomial and $\Phi_7$ the 7th. These polynomials are defined like this: $$ \Phi_n(X) = \prod_{\zeta\in\mathbb{C}^\ast:\ \text{order}(\zeta)=n} (X-\zeta)\qquad\in\mathbb{Z}[X] $$ I want to calculate the splitting field of $\Phi_5$ and the splitting field of $\Phi_7$ over $\mathbb{F}_2$. In $\mathbb{F}_2[X]$ we have $$ \Phi_5(X) = X^4 + X^3 + X^2+X+1 $$ and $$ \Phi_7(X) = (X^3+X+1)(X^3+X^2+1) $$ My question is: what are the splitting fields of the polynomials? I already know it should be of the form $\mathbb{F}_{2^k}$ for some $k\in\mathbb N$. Also the degree of every irreducible factor of a cyclotomic polynomial in $\mathbb{F}_q[X]$ is equal to the order of $q\in(\mathbb{Z}/n\ \mathbb{Z})^\ast$, assuming $(q,n)=1$. A: Since we want the degree of an irreducible factor to be equal to one, we want $$ \text{order} (2^k) =1 $$ in $(\mathbb{Z} / 5\mathbb{Z})^\ast$. The only element with this order is 1. Therefore we search the smallest $k$ such that $2^k\equiv 1\mod 5$. A bit puzzzling gives us $$ 2^1=2\\ 2^2=4\\ 2^3=8=3\\ 2^4=16=1. $$ Therefore the splitting field of $\Phi_5$ should be $\mathbb{F}_{2^4}$. Is this correct?
{ "pile_set_name": "StackExchange" }
Q: Convert decimal to binary in C I am trying to convert a decimal to binary such as 192 to 11000000. I just need some simple code to do this but the code I have so far doesn't work: void dectobin(int value, char* output) { int i; output[5] = '\0'; for (i = 4; i >= 0; --i, value >>= 1) { output[i] = (value & 1) + '0'; } } Any help would be much appreciated! A: The value is not decimal. All values in computer's memory are binary. What you are trying to do is to convert int to a string using specific base. There's a function for that, it's called itoa. http://www.cplusplus.com/reference/cstdlib/itoa/ A: First of all 192cannot be represented in 4 bits 192 = 1100 0000 which required minimum 8 bits. Here is a simple C program to convert Decimal number system to Binary number system #include <stdio.h> #include <string.h> int main() { long decimal, tempDecimal; char binary[65]; int index = 0; /* * Reads decimal number from user */ printf("Enter any decimal value : "); scanf("%ld", &decimal); /* Copies decimal value to temp variable */ tempDecimal = decimal; while(tempDecimal!=0) { /* Finds decimal%2 and adds to the binary value */ binary[index] = (tempDecimal % 2) + '0'; tempDecimal /= 2; index++; } binary[index] = '\0'; /* Reverse the binary value found */ strrev(binary); printf("\nDecimal value = %ld\n", decimal); printf("Binary value of decimal = %s", binary); return 0; }
{ "pile_set_name": "StackExchange" }
Q: Confronting "unacceptable character #x0095: special characters are not allowed in "", position 268" Error in Python yaml.load I am confronting "unacceptable character #x0095: special characters are not allowed in "", position 25" error message when transferring YAML format to Python dictionary object. What would be the possible solution? d = 'tended (Journaled)"\n - "\x95 Support plug and play"\n' a = yaml.load(d) The string to be transferred is abridged, not a proper YAML format, but I guess it's irrelevant in this case. I'm using Python3 A: The YAML specification clearly states that a YAML stream only uses the printable subset of the Unicode character set. Except for NEL (\x85), characters in the C1 control block is not allowed (i.e. characters \x80-\x9F). This is almost valid YAML: d = 'tended (Journaled)"\n - " Support plug and play"\n' You just need a " in front of it and : after the key: d = '"tended (Journaled)":\n - " Support plug and play"\n' (although I'm not sure if Journaled is correct English) The following is not YAML: d = '"tended (Journaled)":\n - "\x95 Support plug and play"\n' because \x95 is in the C1 control block. You will have to replace those characters by hand, or drop them. There is not much in ruamel.yaml that helps you convert such illegal characters, but you can use the Reader's illegal character regex to scan for the illegal characters and drop them: from ruamel.yaml import YAML from ruamel.yaml.reader import Reader yaml = YAML(typ='safe') def strip_invalid(s): res = '' for x in s: if Reader.NON_PRINTABLE.match(x): # res += '\\x{:x}'.format(ord(x)) continue res += x return res d = '"tended (Journaled)":\n - "\x95 Support plug and play"\n' print(yaml.load(strip_invalid(d))) which gives: {'tended (Journaled)': [' Support plug and play']} without any further manual intervention. If you uncomment the line # res += '\\x{:x}'.format(ord(x)) you get as output: {'tended (Journaled)': ['\x95 Support plug and play']}
{ "pile_set_name": "StackExchange" }
Q: Can't resolve all parameters for File I am trying to implement https://ionicframework.com/docs/native/file-transfer/ Therefor I need to install https://ionicframework.com/docs/native/file/ When I use "File" in my service I get the error: Can't resolve all parameters for File: (?, ?, ?, ?, ?). I know that the question marks can resemble a circular reference tough I've never user my service anywhere else, nor did i use "File" before. import {Injectable} from '@angular/core'; import {File} from "@ionic-native/file"; import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer'; @Injectable() export class ImageService { constructor(private file: File, private transfer: FileTransfer) { } public getImagesOfSchedule() { const fileTransfer: FileTransferObject = this.transfer.create(); const url = 'http://techbooster.be/wp-content/uploads/2017/11/logo-long-white.png'; fileTransfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => { console.log('download complete: ' + entry.toURL()); }, (error) => { // handle error }); } } app.module.ts providers: [ StatusBar, AuthenticationService, ScheduleService, ToastService, StorageService, FacebookService, GoogleService, ImageService, Facebook, GooglePlus, PushService, File, <---------------- FileTransfer, <-------------- Push, ScreenOrientation, { provide: HttpService, useFactory: HttpFactory, deps: [XHRBackend, RequestOptions] }, { provide: HttpNoAuthService, useFactory: HttpFactory, deps: [XHRBackend, RequestOptions] }, SplashScreen, {provide: ErrorHandler, useClass: IonicErrorHandler} A: Ok I found out that the File class automatically imported in app.module.ts was not: import { File } from '@ionic-native/file'; Instead it was some standard "lib.es6.d.ts" automatically imported. So make sure you import the correct "File" class!
{ "pile_set_name": "StackExchange" }
Q: Fuse/Camel: How to stop after downloading just one file Fuse/Camel newbie here. I'm trying to automate a manual process where .done files are downloaded from an FTP host, then renamed "fileout.txt", and finally an AS/400 program is executed on that file. However, the department hosting the AS/400 program doesn't have resources to update their programming. The solution I'm working toward is to have Camel download one file at a time, save it as "fileout.txt", then execute a JT400 program to process it. Individually those steps work but I'm left with one problem. What I pray you, dear reader, can help me with is "How can I stop Camel after downloading just one file? (since overwriting, appending, or downloading multiple files won't work for the following step)". A: How can I stop Camel after downloading just one file? You can set following parameters in FTP consumer maxMessagesPerPoll=1 (Limit number of message to be download in single batch) delay=500000 (Increase the time interval between each poll, so you have time to stop the route) Then, your ftp route can trigger an asynchronous message (maybe wireTap component) to another route to trigger controlBus component to stop the ftp route by route id. I'm trying to automate a manual process where .done files are downloaded from an FTP host, then renamed fileout.txt, and finally an AS/400 program is executed on that file Other than stop/start your route, you may try pollEnrich component with FTP usage. Using pollEnrich, you can trigger FTP consumer once when needed if you know the target file name already.
{ "pile_set_name": "StackExchange" }
Q: Replace text in ComboBox upon selecting an item I have an editable ComboBox that should contain a path. The user can select several default paths (or enter his own) from a dropdown list, such as %ProgramData%\\Microsoft\\Windows\\Start Menu\\Programs\\ (All Users). The items in the dropdown list contain a short explanation, like the (All Users) part in the former example. Upon selection of such an item, I want to remove this explanation, so that a valid path is displayed in the ComboBox. I currently strip the explanation out of the string and try to change the text via setting the Text property of the ComboBox. But this doesn't work, the string is parsed correctly, but the displayed text won't update (it stays the same as in the dropdown list, with the explanation). private void combobox_TextChanged(object sender, EventArgs e) { //.. string destPath = combobox.GetItemText(combobox.SelectedItem); destPath = destPath.Replace("(All Users)", ""); destPath.Trim(); combobox.Text = destPath; //.. } A: I found the solution in a similar question, by using BeginInvoke() Using Nikolay's solution, my method now looks like this: private void combobox_SelectedIndexChanged(object sender, EventArgs e) { if (combobox.SelectedIndex != -1) { //Workaround (see below) var x = this.Handle; this.BeginInvoke((MethodInvoker)delegate { combobox.Text = combobox.SelectedValue.ToString(); }); } } The workaround is required, since BeginInvoke requires the control to be loaded or shown, which isn't necessarily the case if the program just started. Got that from here.
{ "pile_set_name": "StackExchange" }
Q: Why I do not have access rights on the server? I use Elmah in local - alright. On the server however, it issues the followed error, and I cannot figure out what how to gain access. 403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied. A: Maybe you should enable remote access <elmah> <security allowRemoteAccess="1" /> </elmah>
{ "pile_set_name": "StackExchange" }
Q: Updating single Listview item in Flutter using a showdialog and textfield We have created a flutter app that displays a listview from a list of items. We want to be able to update these based on user preference. Sort of like if you had a to-do list and wanted to correct or update one of the items on the list using a modal or a dialog box. I have been trying to update a single item in the listview with a dialog box which the user types on and then closes on submit. So far I've had no luck, but I feel I am very close. How can I get the name on the tile to update on submit and re-render the page? What is it that I am missing? import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { List<Animal> animals = new List(); String newName; TextEditingController nctrl = TextEditingController(); @override void initState() { super.initState(); animals = [ Animal(id: 1, name: 'cat'), Animal(id: 2, name: 'dog'), Animal(id: 3, name: 'mouse'), Animal(id: 4, name: 'horse'), Animal(id: 5, name: 'frog'), ]; } _changePetName() { newName = nctrl.text; Navigator.pop(context); return newName; } _showDialog(String name) { nctrl.text = name; showDialog( context: context, builder: (BuildContext context) { // return object of type Dialog return AlertDialog( elevation: 5, backgroundColor: Colors.blue, title: Text( "Rename this pet", ), content: Container( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ TextField( controller: nctrl, onChanged: (e) { setState(() {}); }, ), ], )), actions: <Widget>[ // usually buttons at the bottom of the dialog FlatButton( child: Text("Close"), onPressed: () { Navigator.of(context).pop(); }, ), FlatButton( color: Colors.green, child: Text( "Submit", ), onPressed: () { var updateName = _changePetName(); return updateName; }, ), ], ); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ListView.builder( scrollDirection: Axis.vertical, shrinkWrap: true, itemCount: animals.length, itemBuilder: (BuildContext context, int index) { var pet = animals[index]; return ListTile( key: ValueKey(pet.id), enabled: true, onTap: () async { var rename = await _showDialog(pet.name); if (rename != null) { pet.name = rename; setState(() {}); } // setState(() { // pet.name = 'bob'; // }); }, title: Text(pet.name), ); }, ), ], ), ), ); } } class Animal { final int id; String name; Animal({this.id, this.name}); factory Animal.fromJson(Map<dynamic, dynamic> json) { return new Animal( id: json['id'], name: json['name'], ); } Map<dynamic, dynamic> toJson() { final Map<dynamic, dynamic> data = new Map<dynamic, dynamic>(); data['id'] = this.id; data['name'] = this.name; return data; } } A: Few corrections that will make your code work: show dialog should be of type String so that the result it returns is of type String. While poping dialog box you have to pass data in pop(). await showDialog method to receive it's result. Following is the working code for your reference: import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { List<Animal> animals = new List(); String newName; TextEditingController nctrl = TextEditingController(); @override void initState() { super.initState(); animals = [ Animal(id: 1, name: 'cat'), Animal(id: 2, name: 'dog'), Animal(id: 3, name: 'mouse'), Animal(id: 4, name: 'horse'), Animal(id: 5, name: 'frog'), ]; } _changePetName() { newName = nctrl.text; Navigator.pop(context, newName); return newName; } Future<String> _showDialog(String name) async { nctrl.text = name; return await showDialog<String>( context: context, builder: (BuildContext context) { // return object of type Dialog return AlertDialog( elevation: 5, backgroundColor: Colors.blue, title: Text( "Rename this pet", ), content: Container( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ TextField( controller: nctrl, onChanged: (e) { // setState(() {}); }, ), ], )), actions: <Widget>[ // usually buttons at the bottom of the dialog FlatButton( child: Text("Close"), onPressed: () { Navigator.of(context).pop(nctrl.text); }, ), FlatButton( color: Colors.green, child: Text( "Submit", ), onPressed: () { var updateName = _changePetName(); return updateName; }, ), ], ); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ListView.builder( scrollDirection: Axis.vertical, shrinkWrap: true, itemCount: animals.length, itemBuilder: (BuildContext context, int index) { var pet = animals[index]; return ListTile( key: ValueKey(pet.id), enabled: true, onTap: () async { var rename = await _showDialog(pet.name); if (rename != null) { pet.name = rename; setState(() {}); } // setState(() { // pet.name = 'bob'; // }); }, title: Text(pet.name), ); }, ), ], ), ), ); } } class Animal { final int id; String name; Animal({this.id, this.name}); factory Animal.fromJson(Map<dynamic, dynamic> json) { return new Animal( id: json['id'], name: json['name'], ); } Map<dynamic, dynamic> toJson() { final Map<dynamic, dynamic> data = new Map<dynamic, dynamic>(); data['id'] = this.id; data['name'] = this.name; return data; } } If this solution works for you please accept and up-vote the answer.
{ "pile_set_name": "StackExchange" }
Q: On delete cascade android 2.2 I have 2 tables: Table 1- create table table1(_id integer primary key, content text not null ); Table 2- create table table2(_id integer primary key, id_parent integer, content text not null , CONSTRAINT [FK_table2_id_parent] FOREIGN KEY (id_parent) REFERENCES table1 (_id) ON DELETE CASCADE ); But the DELETE CASCADE doesn't do anything... Anyone know what I'm doing wrong? [EDIT: When I try to delete rows from table1 I can, but when I look for table2 the records are all there ... even those who have the id_parent that no longer exists from Table1.] I'm using android 2.2. A: First make sure your used create table commands are syntactically and logically right. If yes then this is due to following: Declaring and defining foreign key does not apply them really to act. You need to explicitly on the foreign key constraint in your database. if (!db.isReadOnly()) { // Enable foreign key constraints db.execSQL("PRAGMA foreign_keys=ON;"); }
{ "pile_set_name": "StackExchange" }
Q: Swift: Is there a way to test if object cast as AnyObject conforms to Equatable? I have an object that has keyed properties: func value(key: String) -> AnyObject? func setValue(value: AnyObject?, key: String) I wish to check if the value returned from the value function with the same key from two different objects are Equatable. Swift complains because Equatable has a Self reference and can only be used in generics. Is there a way I can check to see if the AnyObject object returned from the value function conforms to Equatable? A: Due to changes in Swift 2, I'm editing m'y answer To check protocol conformance, simply use is keyword. But you can't do it when the protocol is using Self (note the capital S). So you could do: if let myValue = myObject.value(myKey) as? Equatable { ... }
{ "pile_set_name": "StackExchange" }
Q: Is it possible to use both L and E letters to initializing 'Long' numeric literal? If I declare a long variable as: long n = 1E+12L; The compiler throws a syntax error. And when I declare it as: long n = 1E+12; It throws an incompatible types error. On the other hand, it is happy to accept two letters in floats and doubles: double n = 1E+12D; float n = 1E+12F; Why is it not working for long literals? do I have to drop the L letter and cast it to long every time? A: No, this is not possible. The use of e or E in a numeric literal (i.e. scientific notation) is not allowed by the Java Language Specification for integer literals: IntegerLiteral: DecimalIntegerLiteral HexIntegerLiteral OctalIntegerLiteral BinaryIntegerLiteral DecimalIntegerLiteral: DecimalNumeral [IntegerTypeSuffix] ... IntegerTypeSuffix: (one of) l L It is allowed for floating-point literals, but these cannot have an l or L suffix: FloatingPointLiteral: DecimalFloatingPointLiteral HexadecimalFloatingPointLiteral DecimalFloatingPointLiteral: Digits . [Digits] [ExponentPart] [FloatTypeSuffix] . Digits [ExponentPart] [FloatTypeSuffix] Digits ExponentPart [FloatTypeSuffix] Digits [ExponentPart] FloatTypeSuffix ExponentPart: ExponentIndicator SignedInteger ExponentIndicator: (one of) e E ... So, you either have to cast from double, or write out your long literal in full. For convenience, though, you can use underscores to group the digits, like 1_000_000_000_000L, in order to make the number of zeros clear.
{ "pile_set_name": "StackExchange" }
Q: How to populate a cascading Dropdown with JQuery i have the following problem: I started to create a form with HTML an JS and there are two Dropdowns (Country and City). now i want to make these two dynamic with JQuery so that only the cities of the selected countries are visible. I've started with some basic JS which worked fine but makes some trouble in IE. Now i'm trying to convert my JS to JQuery for a better compatibility. My original JS looks like this: function populate(s1, s2) { var s1 = document.getElementById(s1); var s2 = document.getElementById(s2); s2.innerHTML = ""; if (s1.value == "Germany") { var optionArray = ["|", "magdeburg|Magdeburg", "duesseldorf|Duesseldorf", "leinfelden-echterdingen|Leinfelden-Echterdingen", "eschborn|Eschborn"]; } else if (s1.value == "Hungary") { var optionArray = ["|", "pecs|Pecs", "budapest|Budapest", "debrecen|Debrecen"]; } else if (s1.value == "Russia") { var optionArray = ["|", "st. petersburg|St. Petersburg"]; } else if (s1.value == "South Africa") { var optionArray = ["|", "midrand|Midrand"]; } else if (s1.value == "USA") { var optionArray = ["|", "downers grove|Downers Grove"]; } else if (s1.value == "Mexico") { var optionArray = ["|", "puebla|Puebla"]; } else if (s1.value == "China") { var optionArray = ["|", "beijing|Beijing"]; } else if (s1.value == "Spain") { var optionArray = ["|", "barcelona|Barcelona"]; } for (var option in optionArray) { var pair = optionArray[option].split("|"); var newOption = document.createElement("option"); newOption.value = pair[0]; newOption.innerHTML = pair[1]; s2.options.add(newOption); } }; and here my Jquery: http://jsfiddle.net/HvXSz/ i know it is very simple but i can't see the wood for the trees. A: It should as simple as jQuery(function($) { var locations = { 'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'], 'Spain': ['Barcelona'], 'Hungary': ['Pecs'], 'USA': ['Downers Grove'], 'Mexico': ['Puebla'], 'South Africa': ['Midrand'], 'China': ['Beijing'], 'Russia': ['St. Petersburg'], } var $locations = $('#location'); $('#country').change(function () { var country = $(this).val(), lcns = locations[country] || []; var html = $.map(lcns, function(lcn){ return '<option value="' + lcn + '">' + lcn + '</option>' }).join(''); $locations.html(html) }); }); Demo: Fiddle A: I'm going to provide a second solution, as this post is still up in Google search for 'jquery cascade select'. This is the first select: <select class="select" id="province" onchange="filterCity();"> <option value="1">RM</option> <option value="2">FI</option> </select> and this is the second, disabled until the first is selected: <select class="select" id="city" disabled> <option data-province="RM" value="1">ROMA</option> <option data-province="RM" value="2">ANGUILLARA SABAZIA</option> <option data-province="FI" value="3">FIRENZE</option> <option data-province="FI" value="4">PONTASSIEVE</option> </select> this one is not visible, and acts as a container for all the elements filtered out by the selection: <span id="option-container" style="visibility: hidden; position:absolute;"></span> Finally, the script that filters: <script> function filterCity(){ var province = $("#province").find('option:selected').text(); // stores province $("#option-container").children().appendTo("#city"); // moves <option> contained in #option-container back to their <select> var toMove = $("#city").children("[data-province!='"+province+"']"); // selects city elements to move out toMove.appendTo("#option-container"); // moves city elements in #option-container $("#city").removeAttr("disabled"); // enables select }; </script> A: I have created cascading Dropdown for Country, State, City and Zip It may helpful to someone. Here only some portion of code are posted you can see full working example on jsfiddle. //Get html elements var countySel = document.getElementById("countySel"); var stateSel = document.getElementById("stateSel"); var citySel = document.getElementById("citySel"); var zipSel = document.getElementById("zipSel"); //Load countries for (var country in countryStateInfo) { countySel.options[countySel.options.length] = new Option(country, country); } //County Changed countySel.onchange = function () { stateSel.length = 1; // remove all options bar first citySel.length = 1; // remove all options bar first zipSel.length = 1; // remove all options bar first if (this.selectedIndex < 1) return; // done for (var state in countryStateInfo[this.value]) { stateSel.options[stateSel.options.length] = new Option(state, state); } } Fiddle Demo
{ "pile_set_name": "StackExchange" }
Q: Start server node.js with forever on ubuntu I been searching alot and no result with same problem as me. I have a Node.js application and I want to start it with forever start app.js, the process starts but no website found when i try in browser. The process is in the list when I write forever list. Npm start works fine but I cant use nodejs/node app.js or my_file.js.. It gives no error or something just new command line with no output in terminal. So anyone know why I cant start the app with nodejs app.js or forever start app.js .. No files works. Thanks! A: In express 4 you should write : forever ./bin/www And if you check your package.json file you can see : "scripts": { "start": "node ./bin/www" } It's the npm start script
{ "pile_set_name": "StackExchange" }
Q: what is the difference between refresh rate and frame rate? please can any one explain for me , what is the difference between refresh rate and frame rate? in the Wikipedia I found this definition for refresh rate "is the number of times in a second that a display hardware updates its buffer" , but what that mean , does that mean that if we wrote a JavaScript function that changes a style of an element periodically we have to wait until my screen refresh to see that change ???? please help me I am confused a little. A: Frame rate Frame rate, also known as frame frequency and frames per second (FPS), is the frequency (rate) at which an imaging device produces unique consecutive images called frames. The term applies equally well to film and video cameras, computer graphics, and motion capture systems. Frame rate is most often expressed in frames per second (FPS) and is also expressed in progressive scan monitors as hertz (Hz). Source: Wikipedia Refresh rate The refresh rate (most commonly the "vertical refresh rate", "vertical scan rate" for cathode ray tubes) is the number of times in a second that a display hardware updates its buffer. This is distinct from the measure of frame rate in that the refresh rate includes the repeated drawing of identical frames, while frame rate measures how often a video source can feed an entire frame of new data to a display. Source: Wikipedia
{ "pile_set_name": "StackExchange" }
Q: PHPMailer - authentication problems Im trying to create an email service with PHPMailer and im receiving and authentication error and the username and password are correct . This is my code: <?php require 'PHPMailer/PHPMailerAutoload.php'; $mail = new PHPMailer; //Tell PHPMailer to use SMTP $mail->isSMTP(); $mail->SMTPDebug = 1; $mail->Debugoutput = 'html'; $mail->Host = 'smtp.gmail.com'; $mail->Port = 587; $mail->SMTPSecure = 'tls'; $mail->SMTPAuth = true; $mail->Username = “[email protected]"; $mail->Password = “my gmail password”; //Set who the message is to be sent from $mail->setFrom(‘[email protected]', 'Nicolas El Mir'); //Set who the message is to be sent to $mail->addAddress('[email protected]', 'Nicolas Mir'); //Set the subject line $mail->Subject = 'PHPMailer GMail SMTP test'; $mail->Body = 'This is a plain-text message body'; $mail->AltBody = 'This is a plain-text message body'; //send the message, check for errors if (!$mail->send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message sent!"; } ?> Thanks for your help ! A: Your problem starts here: $mail->Username = “[email protected]"; $mail->Password = “my gmail password”; //Set who the message is to be sent from $mail->setFrom(‘[email protected]', 'Nicolas El Mir'); You see those curly/smart quotes? “ ” ‘ “myemail... “my gmail password” ‘example... They're choking your script. $mail->Username = "[email protected]"; $mail->Password = "my gmail password"; //Set who the message is to be sent from $mail->setFrom('[email protected]', 'Nicolas El Mir'); Had you error reporting set to catch/display, it would have told you about it. http://php.net/manual/en/function.error-reporting.php I'm really hoping that is your actual code too, rather than just a bad Word Processor paste. Plus, make sure you do have a Webserver/PHP installed and that mail is enabled on it. Add error reporting to the top of your file(s) which will help find errors. <?php error_reporting(E_ALL); ini_set('display_errors', 1); // Then the rest of your code Sidenote: Displaying errors should only be done in staging, and never production. Plus, pulled from this answer https://stackoverflow.com/a/16048485/ which may be the same problem for you, the port number, etc. $mail = new PHPMailer(); // create a new object $mail->IsSMTP(); // enable SMTP $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only $mail->SMTPAuth = true; // authentication enabled $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail $mail->Host = "smtp.gmail.com"; $mail->Port = 465; // or 587 $mail->IsHTML(true); $mail->Username = "[email protected]"; $mail->Password = "password"; $mail->SetFrom("[email protected]"); $mail->Subject = "Test"; $mail->Body = "hello"; $mail->AddAddress("[email protected]"); if(!$mail->Send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message has been sent"; } This code above has been tested and worked for me. It could be that you needed $mail->SMTPSecure = 'ssl'; Also make sure you don't have two step verification switched on for that account as that can cause problems also. UPDATED You could try changing $mail->SMTP to: $mail->SMTPSecure = 'tls'; It's worth noting that some SMTP servers block connections. Some SMTP servers don't support SSL (or TLS) connections. and pulled from another answer https://stackoverflow.com/a/31194724/ in that question: The solution was that I had to remove this line: $mail->isSMTP();
{ "pile_set_name": "StackExchange" }
Q: Invalid Resx file. Could not load type error why? I'm getting designer error on code: The Component i'm willing to define a List of properties for: using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; namespace TestProjectForProperty.Test { public class MyTreeView : TreeView { private List<TypeDescriptorBase> _descriptorsAvailable = new List<TypeDescriptorBase>(); [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List<TypeDescriptorBase> DescriptorsAvailable { get { return _descriptorsAvailable; } set { _descriptorsAvailable = value; } } } } The Descriptor itself: using System; namespace TestProjectForProperty.Test { [Serializable] public class TypeDescriptorBase { public string Name { get; set; } public override string ToString() { return Name; } } } I am getting the following error if i try to use the component for example on a form and add any items on the property sheet or in the component's constructor to the DescriptorsAvailable property Error 1 Invalid Resx file. Could not load type System.Collections.Generic.List`1[[TestProjectForProperty.Test.TypeDescriptorBase, TestProjectForProperty, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 which is used in the .RESX file. Ensure that the necessary references have been added to your project. Line 134, position 5. ...\visual studio 2010\Projects\TestProjectForProperty\TestProjectForProperty\Form1.resx 134 5 TestProjectForProperty In the Resx file there is data field with base64 encoded stuff inside when this error is present. I have been searching for an answer, but the best i got is to restart everything, it didn't help me, do you guys have any suggestions? I'm using .net 4 client and visual studio 2010 A: In my experience, this is due to a change of version of a referenced library, or a change of the lib itself, which contains the backing type of a property you have defined in your user control. The solution is to "force" the visual studio designer to re-initialize it's designer code for that type, and not expect to retrieve a "canned" version of it from the .resx file of the control. 1) Delete the offending data section in the .resx file of your control. This will be a section in the xml of the .resx file associated with your user control, which has a node: <data></data> - the name attribute will be set to whatever you've named that object in the properties of whatever you added this type to. The <data>/data> section contains a base64 encoded string that is the encoded form of the name and version of the library the type comes from. This is where the problem ism, because it now contains an encoded version of the library and/or version number you are no longer referencing in order to include the type. Delete the entire <data>/data> section, from opening to closing tag, save the change and close the file. Now the "artifact" is gone. 2) Now find the place in the designer file for your control, where the type is instantiated; this is initialization code generated for you by visual studio, and it is the place that is expecting to load a "canned" definition of the type from the base64 encoded string contained within the .resx file. The line will look something like this: this.myCtrlFoo.MyPropertyFroo = ((MyNamespaceFoo.MyTypeFoo)(resources.GetObject("myCtrlFoo.MyPropertyFroo"))); ...now just replace the resources.GetObjec call with the instantiation of a new instance of the appropriate type like so: this.myCtrlFoo.MyPropertyFroo = ((MyNamespaceFoo.MyTypeFoo)(new MyNamespaceFoo.MyTypeFoo())); ...now save the change to the file, close it, rebuild, and everything should now build & run OK. A: Put the MyTreeView and TypeDescriptorBase classes into another project and reference it from your GUI project will resolve the issues. I'm not sure why exactly the problem occurs - I guess it has something to do with the way the serializing process is generating the base64 string for the DescriptorsAvailable Property. Maybe somebody else can give us some insight.
{ "pile_set_name": "StackExchange" }
Q: Writing MATLAB with the original font in modernCV I'm wondering if I can write MATLAB with the original font in my CV using class moderncv: Thank you for your willingness. A: Well, if you have a look to the german page of MATLAB about Trademarks you will find: As you can see it the registered mark set with only uppercase letters. About the font was nothing said, but it is a font without serif! Because an cv is usualy set in non serif font (class option sans) you can use the following code: \documentclass[10pt,a4paper,sans]{moderncv} % <========================= \moderncvtheme{classic} \usepackage[top=1.1cm, bottom=1.1cm, left=2cm, right=2cm]{geometry} \usepackage{textcomp} % <=============================================== \name{Joe}{Doe} \begin{document} MATLAB\textsuperscript{\textregistered} % <============================= MATLAB\textsuperscript{\texttrademark} \end{document} In this way you respect the layout on the homepage but use your font in the cv. On the homepage of MATLAB the name of the software is printed without registered mark, but uppercase. So it seems okay to use only MATLAB in your cv. The printed logos with class moderncv are then: That is near enouph to the original logo so one would recognize the used software as MATLAB. If you realy want to use the completely original logo you need to contact the owner of the logo, and ask for the specifications for the logo: font, fontsize, color, needed space around the logo other specifications they have to allow using there logo to be used. That could get problematic if you want to add more than one logo to your cv in its original form. Please note that it is not very good to use a lot of different fonts perhaps in different font sizes in one document ... Please note that there can be -- depending on the place you live -- a legal problem using logos in the original font: Often logos are set in commercial fonts, you need to own to be allowed to use them in your cv. That can be get very explensive soon ... Or you simply are not allowed to use the original logo ... At last: to be sure ask a layer what is allowed in the place you live ...
{ "pile_set_name": "StackExchange" }
Q: .NET Framework get running processor architecture There is an enum of all supported processor architectures here: http://msdn.microsoft.com/en-us/library/system.reflection.processorarchitecture.aspx Is there any way to determine which one corresponds to the running environment? System.Reflection.Assembly.GetExecutingAssembly().ProcessorArchitecture returns MSIL -- obviously wrong. EDIT: Bojan Resnik posted an answer and deleted it. I see that some clarification is needed from the partial trace I got. The assembly needs to run on multiple architectures and do different things based on what assembly instructions the running process accepts. Essentially, I need to select which version of a native DLL to load. I have one for each architecture. A: P/Invoking GetSystemInfo is trivial from .Net and is much lighter weight than WMI. Also, it returns the architecture as seen by the process so on a x64 machine a WOW process will see x86 and a native process will see x64.
{ "pile_set_name": "StackExchange" }
Q: Keep location service alive when the app is closed I have a service which sends a notification when the user changes his/her location. This service is working fine, but the problem arises when the user closes the app as the service closes too. How I can make the service still alive even though the application was closed? My Service is: public class LocationService extends Service implements LocationListener { public final static int MINUTE = 1000 * 60; boolean isGPSEnabled = false; boolean isNetworkEnabled = false; boolean canGetLocation = false; Location location; // location double latitude = 0; // latitude double longitude = 0; // longitude String provider; // The minimum distance to change Updates in meters private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // The minimum time between updates in milliseconds private static final long MIN_TIME_BW_UPDATES = 1 * MINUTE; // Declaring a Location Manager protected LocationManager locationManager; // Binder given to clients private final IBinder mBinder = new LocalBinder(); /** * Class used for the client Binder. Because we know this service always * runs in the same process as its clients, we don't need to deal with IPC. */ public class LocalBinder extends Binder { public LocationService getService() { // Return this instance of LocalService so clients can call public // methods return LocationService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } public Location getLocation() { try { locationManager = (LocationManager) getBaseContext().getSystemService(LOCATION_SERVICE); // getting GPS status isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); // getting network status isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (!isGPSEnabled && !isNetworkEnabled) { // no network provider is enabled. DEFAULT COORDINATES } else { this.canGetLocation = true; if (isNetworkEnabled) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("Network", "Network Enabled"); if (locationManager != null) { location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } // if GPS Enabled get lat/long using GPS Services if (isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("GPS", "GPS Enabled"); if (locationManager != null) { location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } } } catch (Exception e) { e.printStackTrace(); } Log.i("LOCATION", "Latitude: " + latitude + "- Longitude: " + longitude); return location; } @Override public void onLocationChanged(Location arg0) { NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); Intent intent = null; intent = new Intent(this, CompleteSurveyActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true) .setContentIntent(contentIntent).setContentTitle(this.getString(R.string.app_name)).setContentText("text"); // mBuilder.setContentIntent(contentIntent); mNotificationManager.notify((int) System.currentTimeMillis() % Integer.MAX_VALUE, mBuilder.build()); double longitude = location.getLongitude(); double latitude = location.getLatitude(); Log.i("LOCATION", "Latitude: " + latitude + "- Longitude: " + longitude); } @Override public void onProviderDisabled(String arg0) { } @Override public void onProviderEnabled(String arg0) { } @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) { } } I called from here: public class MyActivity extends Activity { LocationService mService; boolean mBound = false; private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get // LocalService instance LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.my_activity); exampleButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { initService(); } }); } public void initService() { if (mBound) mService.getLocation(); } @Override protected void onStart() { super.onStart(); // Bind to LocalService Intent intent = new Intent(this, LocationService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); // Unbind from the service if (mBound) { unbindService(mConnection); mBound = false; } } } Manifest.xml <service android:name=".LocationService" android:enabled="true"></service> A: Oppositely to what @sven-menschner said, I think an unbound Service is exactly what you need, as bound services are subject to bind/unbind mechanisms that would kill your service. That's what I would do: In your Manifest file, define your service: <service android:name=".YourService" android:enabled="true" android:exported="true" android:description="@string/my_service_desc" android:label="@string/my_infinite_service"> <intent-filter> <action android:name="com.yourproject.name.LONGRUNSERVICE" /> </intent-filter> </service> Note: There's a list of already implemented actions, but you can define your own actions for the intent to launch the service. Simply create a singleton class and define the strings assigning them a String that should be unique. The "enabled" set to true is just to instantiate the service, and exported set to true is just in the case you need other applications sending intents to your Service. If not, you can safely set that last to false. The following step would be starting your service from your activity. That can be easily done by: public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent servIntent = new Intent("com.yourproject.name.LONGRUNSERVICE"); startService(servIntent); ... } } The final step is to define your Service initializations. Keep an eye on the onBind() method. Since you don't want it to be bound, simply return null. It would be something like this: public class MyService extends Service { @Override public IBinder onBind(Intent intent) { // This won't be a bound service, so simply return null return null; } @Override public void onCreate() { // This will be called when your Service is created for the first time // Just do any operations you need in this method. } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } } Now your service will run even if you close your main Activity. There's just one step left: To help your Service not being finished, run it as a foreground service (do that within your Service). This will basically create a notification icon in the status bar. This doesn't mean your main Activity is running too (this is why you don't want a bound service), as Activities and Services have different life-cycles. In order to help that Service run for so long, try keeping your heap as low as possible so it will avoid the Android SO killing it. One more acclaration: You cannot test whether the Service is still running killing the DVM. If you kill the DVM, you'll killing everything, thus also the Service.
{ "pile_set_name": "StackExchange" }
Q: Avoid inserting duplicate records? I have an application which have a table called Products. My background service is inserting data from an excel file. The problem is taht some times excel file include some duplicate data. My sample statement is, INSERT INTO Products SELECT Name, Phone, SKU, ModelNumber FROM BlahBlah The problem is that I want to make sure that SKU and ModelNumber should be unique. Means it can be null. But if the value is there then the combination should always be unique. So if there are more than one value of SKU adn ModelNumber then I should only insert the first one. A: taking into account that maybe you have multiple excel files and already have data in your table and also looking at null-values, try this: INSERT INTO Products SELECT Name, Phone, SKU, ModelNumber FROM BlahBlah where not exists (select * from Products where coalesce(Products.SKU,'{NULL}') = coalesce(BlahBlah.SKU,'{NULL}') and coalesce(Products.ModelNumber,-1) = coalesce(BlahBlah.ModelNumber, -1) i am assuming SKU is text and ModelNumber numeric. if you want to update the Products table, instead of just not inserting a value when it already exists, try merge: MERGE INTO Products USING BlahBlah ON coalesce(Products.SKU,'{NULL}') = coalesce(BlahBlah.SKU,'{NULL}') and coalesce(Products.ModelNumber,-1) = coalesce(BlahBlah.ModelNumber, -1) WHEN MATCHED THEN update set Products.Name = BlahBlah.Name, Products.Phone = BlahBlah.Phone WHEN NOT MATCHED THEN insert (Name, Phone, SKU, ModelNumber) values (BlahBlah.Name, BlahBlah.Phone, BlahBlah.SKU, BlahBlah.ModelNumber); A: Try this one - INSERT INTO dbo.Products SELECT /*DISTINCT*/ Name, Phone, SKU = NULL, ModelNumber = NULL FROM BlahBlah WHERE SKU IS NULL AND ModelNumber IS NULL UNION ALL SELECT MAX(Name), MAX(Phone), SKU, ModelNumber FROM BlahBlah WHERE SKU IS NOT NULL OR ModelNumber IS NOT NULL GROUP BY SKU, ModelNumber
{ "pile_set_name": "StackExchange" }
Q: Diferença entre comandos onClick no React Quando se tratando de funções de callback no ReactJS, qual é a diferença entre as opções abaixo? onClick={() => this.onFunctionCickCall()} onClick={this.onFunctionClickCall()} onClick={this.onFunctionClickCall.bind(this)} onClick={this.onFunctionClickCall} A: Todos fazem a mesma coisa porém alguns usam uma syntax mais atual. Caso 1: onClick={() => this.onFunctionClickCall()} Este é o modelo mais novo de se escrever pois você não precisa dar um "fix" no bind da função dentro do contrutor. Veja a documentação Também é bom dizer que neste caso ele retorna uma função que executa outra função. Úlil quando você precisa passar algum tipo de parametro para as função. Ex.: class Foo extends Component { handleClick() { console.log('Click happened'); } render() { return <button onClick={() => this.handleClick()}>Click Me</button>; } } Você também poderia escrever assim (Exemplo abaixo), que teria o mesmo efeito do caso acima. ex.: class Foo extends Component { handleClick = () => () => { console.log('Click happened'); } render() { return <button onClick={this.handleClick}>Click Me</button>; } Caso 2 e 4: Nestes caso faz necessário o uso do "bind fix" no construtor. Veja a documentação. Ou usar arrow function syntax não tão usada porém mais simples de escrever. Nestes casos se você tentar usar com o () no final irá executar assim que o código for carregado. Ex.: class Foo extends Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { console.log('Click happened'); } render() { return <button onClick={this.handleClick}>Click Me</button>; } } E o caso 3: onClick={this.onFunctionClickCall.bind(this)} É só um jeito de dar um "bind fix" sem precisa colocar dentro do construtor como foi usado no caso 2 ou 4. De todos os jeitos que você escrever vão estar certo, porém alguns são syntax mais atuais/simples porém é interessante você saber o que está acontecendo por trás antes. Essa pode ser uma boa leitura para você entender mais
{ "pile_set_name": "StackExchange" }
Q: jQuery autocomplete and handling the value / label issue I'm trying to have a jQuery autocomplete. I have specified some data but when I select an item on the drop down, it always pushes the value into the meta-area elements. I want the label. How to do this? Trying to get it to show the label in #meta-area rather than the value. HTML: ... area:<input type='text' size='20' id='meta-area' /> <input type='hidden' id='meta_search_ids' value='' /> ... JavaScript: $(document).ready(function(){ var data =[ {'label':'Core','value':1}, {'label':' Selectors','value':2}, {'label':'Events' ,'value':3}]; $("#meta-area").autocomplete({source:data, select: function(e, ui) { $("#meta_search_ids").val(ui.item.value); // this part is not working //$(this).val(ui.item.label); $('#meta-area').text('this is what I want'); } }); //alert("this loaded"); }); A: The default action of a select event places ui.item.value inside the input. You need to use preventDefault with your event handler: $(document).ready(function(){ var data =[ {'label':'Core','value':1}, {'label':' Selectors','value':2}, {'label':'Events' ,'value':3}]; $("#meta-area").autocomplete({ source:data, select: function(e, ui) { e.preventDefault() // <--- Prevent the value from being inserted. $("#meta_search_ids").val(ui.item.value); $(this).val(ui.item.label); } }); //alert("this loaded"); }); Example: http://jsfiddle.net/UGYzW/6/
{ "pile_set_name": "StackExchange" }
Q: pyqt - QFileSystemModel without subdirectories? is possible to make a QFileSystemModel in a QTreeWidget only showing folders in a path without their subfolders? also, can i get the folders size (with anything in them) using QFileSystemModel? this is my code filtering to only folders: m_index = r"C:/folder" model = QtGui.QFileSystemModel() model.setRootPath(m_index) model.setFilter(QtCore.QDir.Dirs|QtCore.QDir.NoDotAndDotDot) view = QtGui.QTreeView() view.setModel(model) view.setColumnHidden(2, True) view.setColumnHidden(3, True) view.setRootIndex(model.index(m_index)) A: Never mind, view.setItemsExpandable(False) did the job...
{ "pile_set_name": "StackExchange" }
Q: How does this follow from Chebyshev's inequality My textbook claims that the following inequality follows from chebshev's inequality $\int_{|x|\geq B}(1+|x|^{p})dL_{A}\leq B^{-p-2q}\int(1+x^{2(p+q)})dL_{A},$ where $L_{A}$ is the empirical spectral disribution of some random matrix, that is of the form $L_{A}=\frac{1}{N}\sum_{i=1}^{N}\delta_{\lambda_{i}}$ where $N$ is the size of the matrix (In fact $L_{A}$ could be any probability measure). This inequality is not clear for me. I have separated the LHS into a sum of two integrals, for the first integral there is no problem, for the second I use $g(u)=u^{\frac{2(p+q)}{p}}$ to find $\int_{|x|\geq B}|x|^{p}dL_{A}\leq \frac{1}{B^{\frac{2(p+q)}{p}}}\int x^{2(p+q)}dL_{A},$ which is not what I want. A: $$ \int_{|x|\ge B} |x|^p \, dL_A = \int_{|x|\ge B} |x|^{2(q+p)} |x|^{-p-2q} \, dL_A $$ Since $|x|\ge B$ inside the integral, we get $|x|^{-p-2q} \le B^{-p-2q}$ inside the integral.
{ "pile_set_name": "StackExchange" }
Q: Javascript nodeValue not accepting new variable Here's what I have: I create this markup on the fly: <p id="amount"><span></span></p> Now I need to fill up the span: if (amount.firstChild.nodeType == 1) { amount.firstChild.nodeValue = text; alert(description.firstChild.nodeType); //this shows SPAN } amount is a variable created with getElementbyId and text is a variable that it works and shows just a figure. Now, why isn't accepting text as a value? It renders and empty span... and text is working just fine.... thanks a lot fellas! A: You can test for a nested text node in the span, and if there isn't one, create it. var span = amount.firstChild if (!span.firstChild) span.appendChild(document.createTextNode(text)); else span.firstChild.nodeValue = text;
{ "pile_set_name": "StackExchange" }
Q: Does this code follow duck typing? The principle of duck typing says that you shouldn't care what type of object you have - just whether or not you can do the required action with your object. For this reason the isinstance keyword is frowned upon. - -Definition In below snippet(function) group_tweets_by_state, following definition of duck typing, action setdefault is performed on the object tweets_by_state by appending object tweet def group_tweets_by_state(tweets): tweets_by_state = {} USA_states_center_position = {n: find_center(s) for n, s in us_states.items()} for tweet in tweets: # tweets are list of dictionaries if hassattr(tweet, 'setdefault'): # tweet is a dictionary state_name_key = find_closest_state(tweet, USA_states_center_position) tweets_by_state.setdefault(state_name_key, []).append(tweet) return tweets_by_state My understanding is, function hasattr(tweet, 'setdefault') is type checking tweet to be of <class 'dict'> type in duck typing style, before append. Is my understanding correct? Does function group_tweets_by_state follow duck typing? A: A test like hassattr(tweet, 'setdefault') to make sure tweet is a dictionary is not a good one, since it obviously does not assure tweet provides all methods/properties of a dictionary. So as long tweet.setdefault is not the only method called by find_closest_state (which I think is unlikely), this test is not strict enough. On the other hand, a test like isinstance(tweet, dict) is too strict, because it forbids the usage of other, dictionary-like structures, which is exactly the idea of duck typing. In your example the requirement is not really that tweet is a dictionary, the requirement is that find_closest_state can process the tweet, whatever methods it calls from a tweet, independently of the real type. The following solution will handle this in a generic manner, without the need of knowing exactly what methods inside find_closest_state are used: def group_tweets_by_state(tweets): tweets_by_state = {} USA_states_center_position = {n: find_center(s) for n, s in us_states.items()} for tweet in tweets: # a tweet should behave like a dictionary try: state_name_key = find_closest_state(tweet, USA_states_center_position) tweets_by_state.setdefault(state_name_key, []).append(tweet) except (AttributeError, TypeError): pass return tweets_by_state The code checks for an AttributeError because that is the exception you get when find_closest_state calls a method not provided by tweet. It also checks for a TypeError, because that is what you get when you call tweet["abc"] on a non-dictionary. You may need to add some other exceptions, depending on how find_closest_state is implemented internally, but you should not add any artificial constraints. And that's how duck typing should really be applied - by not making assumptions about the type of the object passed, only by testing whether or not you can do the required action (here: call find_closest_state without getting one of the above exceptions). A: First, I want to say that by far not everybody agrees that duck typing is a good thing at all, let alone that it is some sort of holy principle that should be followed. Often duck typing leads to error prone, hard to debug code, although it can be very flexible in how you can use it. Duck typing just takes an object and does with the object what it wants to do E.g. if it expects an open file object that it wants to call .write() on, then it just does that. If that throws an exception because the object doesn't have that method, then you passed in a non-duck. Your fault. If you passed in a completely different kind of object that also works because it has a .write(), that is the benefit of duck typing. So your code would use "duck typing" if it simply assumes that tweets is a list of dictionaries (like the comment says), and doesn't go to any trouble to check that. def group_tweets_by_state(tweets): tweets_by_state = {} USA_states_center_position = {n: find_center(s) for n, s in us_states.items()} for tweet in tweets: # tweets are list of dictionaries state_name_key = find_closest_state(tweet, USA_states_center_position) tweets_by_state.setdefault(state_name_key, []).append(tweet) return tweets_by_state
{ "pile_set_name": "StackExchange" }
Q: Svg line not displayed on google charts? I am trying to add one line on top of google line chart. I am using svg for transforming line. If i dont use google.load('visualization', '1', {packages: ['corechart'], callback: drawChart}); to draw line then a moving vertical line is working but if i draw chart then vertical line is not displayed. Following is my code of drawing moving vertical line on google line chart. <!DOCTYPE html> <html> <head> <script type="text/javascript" src="http://www.google.com/jsapi?.js"></script> <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script type="text/javascript" src="http://d3js.org/d3.v2.js"></script> <script type="text/javascript" src="underscore.js"></script> <style> .selection_line { stroke: rgba(0, 0, 0, 0.6); shape-rendering: crispEdges; } </style> <script type="text/javascript"> $(function() { // Handler for .ready() called. var graph = d3.select('#graph') .append('svg') .attr('width', '100%') .attr('height', 600); var line = graph.append('line') .attr('transform', 'translate(0, 50)') .attr({'x1': 0, 'y1': 0, 'x2': 0, 'y2': 300}) .attr('class', 'selection_line'); var x = 0; graph.on('mousemove', function() { x = d3.mouse(this)[0]; }); var draw = function() { line .transition() .duration(18) .attrTween('transform', d3.tween('translate(' + x + ', 50)', d3.interpolateString)) .each('end', draw); }; draw(); google.load('visualization', '1', {packages: ['corechart'], callback: drawChart}); }); function drawChart() { // Create and populate the data table. var data = new google.visualization.DataTable(); data.addColumn('number', 'x'); // add an "annotation" role column to the domain column data.addColumn({type: 'string', role: 'annotation'}); data.addColumn('number', 'y'); // add 100 rows of pseudorandom data var y = 50; for (var i = 0; i < 100; i++) { y += Math.floor(Math.random() * 5) * Math.pow(-1, Math.floor(Math.random() * 2)); data.addRow([i, null, y]); } // add a blank row to the end of the DataTable to hold the annotations data.addRow([null, null, null]); // get the index of the row used for the annotations var annotationRowIndex = data.getNumberOfRows() - 1; var options = { height: 400, width: 600 }; // create the chart var chart = new google.visualization.LineChart(document.getElementById('graph')); // draw the chart chart.draw(data, options); } </script> </head> <body> <div id="graph"></div> </body> A: To achieve this, you have to append a line to the SVG that is generated by the Google chart and move it according to the position of the mouse pointer, ignoring the x component: var line = graph.append('line') .attr('transform', 'translate(100, 50)') .attr({'x1': 0, 'y1': 0, 'x2': 400, 'y2': 0}) .attr('class', 'selection_line'); graph.on('mousemove', function() { line.attr("y1", d3.event.y - 50); line.attr("y2", d3.event.y - 50); }); Complete example here.
{ "pile_set_name": "StackExchange" }