source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0040433598.txt" ]
Q: Create a sequence of two letters of length 10 using Linq I have been trying to create a sequence of two letters based on a length. I know a similar question has been asked in python Strings of two letters and fixed length but it differs slightly. [Edit] Example abababababa is a string sequence of a , b and fixed length 11 I came up with this quick solution but I feel there is a much smarter way to do this. The fixed length can be even or odd number. For instance, string b =String.Concat(Enumerable.Repeat(String.Concat("a", "b"), 11)); Console.WriteLine(b.Substring(0,11)); How do I achieve this? A: "Best" would probably be char[] or StringBuilder with a for loop, but here are few shorter ways: string a = new string('a', 11).Replace("aa", "ab"); string b = string.Concat(Enumerable.Range(0, 11).Select(i => "ab"[i & 1])); string c = new StringBuilder().Insert(0, "ab", ((11 + 1) / 2)).ToString(0, 11);
[ "stackoverflow", "0012475764.txt" ]
Q: XDomainRequest not giving response while status is 200 XDomainRequest not giving response while status is 200 var httpRequest = new XDomainRequest(); httpRequest.open('POST', url, true); httpRequest.send(xmlDocument); alert(httpRequest.responseText); return httpRequest; it is giving response text null. plz guide me where i am missing. A: try doing: var httpRequest = new XDomainRequest(); httpRequest.onload=function() { alert(httpRequest.responseText); } httpRequest.open('POST', url, true); httpRequest.send(xmlDocument);
[ "ru.stackoverflow", "0000849125.txt" ]
Q: Хотелось бы по кнопке останавливать код другой кнопки, где задержка у меня код у кнопки, где задержка на закрытие активити, как я бы мог по нажатию другой кнопки останавливать его? package com.talk.talktools; import android.app.Fragment; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.Toast; public class fragment1 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment1, container, false); return v; } @Override public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ImageView imageView2 = view.findViewById(R.id.imageView2); ImageView imageView = view.findViewById(R.id.imageView); ImageView imageView3 = view.findViewById(R.id.imageView3); imageView3.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(view.getContext(), "Ты нашел пасхалку! Теперь закрытие приложения! :)", Toast.LENGTH_SHORT).show(); Toast.makeText(view.getContext(), "У тебя десять секунд!", Toast.LENGTH_SHORT).show(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { getActivity().finish(); } }, 10000); //specify the number of milliseconds return false; } }); View.OnClickListener ocltg = new View.OnClickListener() { @Override public void onClick(View v) { String url = "SECRET"; Intent h = new Intent(Intent.ACTION_VIEW); h.setData(Uri.parse(url)); startActivity(h); } }; imageView3.setOnClickListener(ocltg); View.OnClickListener ocltgchat = new View.OnClickListener() { @Override public void onClick(View v) { String url = "SECRET"; Intent g = new Intent(Intent.ACTION_VIEW); g.setData(Uri.parse(url)); startActivity(g); } }; imageView.setOnClickListener(ocltgchat); View.OnClickListener oclf0x1d = new View.OnClickListener() { @Override public void onClick(View v) { String url = "SECRET"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }; imageView2.setOnClickListener(oclf0x1d); } } A: Создать переменную как параметр класса boolean b = true; При нажатии на кнопку отмены закрытия пиложения b = false; Код закрытия приложения Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { if (b) getActivity().finish(); } }, 10000); //specify the number of milliseconds return false; Не забыть где-то снова менять значение переменной b, чтобы можно было всё таки закрыть приложение через 10 секунд Помимо этого можно попробовать следующее 1.Измените handler.postDelayed(Runnable r, long delayMillis) на handler.postDelayed(Runnable r, Object token, long delayMillis) 2.Если кнопка Отмены была нажата то removeCallbacks(Runnable r, Object token) 3.При этом необходимо создать Runnable не внутри, а внешним, так же, как и Handler handler. Ссылка для доп информации https://developer.android.com/reference/android/os/Handler
[ "stackoverflow", "0004106996.txt" ]
Q: java.lang.IllegalArgumentException: Sniffers with type [ejb] and type [appclient] should not claim the archive at the same time Environment: GlassFish 3.0.1, NetBeans 6.9, JDK 6u21 Also tested with GlassFish 3.0.1, NetBeans 6.9.1, JDK 6u22, but results are the same. Problem: Unable to run app-client in an enterprise application (app-client, ejb, war). The EJB jar has only Local interfaces and contains no main methods. GlassFish Message SEVERE: Exception while deploying the app java.lang.IllegalArgumentException: Sniffers with type [ejb] and type [appclient] should not claim the archive at the same time. Please check the packaging of your archive [C:\Users\myUser\.netbeans\6.9\config\GF3\domain1\applications\fabench-app-client] at com.sun.enterprise.v3.server.SnifferManagerImpl.validateSniffers(SnifferManagerImpl.java:221) at com.sun.enterprise.v3.server.ApplicationLifecycle.setupContainerInfos(ApplicationLifecycle.java:426) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:262) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:183) at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:272) at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:305) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:320) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1176) at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$900(CommandRunnerImpl.java:83) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1235) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1224) at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:365) at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:204) at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:166) at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:100) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:245) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57) at com.sun.grizzly.ContextTask.run(ContextTask.java:69) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309) at java.lang.Thread.run(Thread.java:619) NetBeans run message Building jar: F:\NetBeansProjects\fabench\fabench-app-client\dist\fabench-app-client.jar dist: pre-run-deploy: Distributing F:\NetBeansProjects\fabench\fabench-app-client\dist\fabench-app-client.jar to [GlassFish Server 3] deploy?path=F:\NetBeansProjects\fabench\fabench-app-client\dist\fabench-app-client.jar&name=fabench-app-client&force=true failed on GlassFish Server 3 F:\NetBeansProjects\fabench\fabench-app-client\nbproject\build-impl.xml:716: The module has not been deployed. BUILD FAILED (total time: 0 seconds) application-client.xml This contains only the <display-name> tag filled, but <ejb-ref> can also be specified with a <remote> interface. There is no <local> tag, so I guess app-client is only able to work with Remote interfaces. Is this true? What could be the problem here? Any help or ideas would be appreciated! Thanks in advance, wheelie A: App-client accesses EJBs via Remote interfaces Since GlassFish v3, Remote interfaces has to be packed inside a Java Class Library, so interfaces are distributable. App-client has to be inside an enterprise application EAR (but not strictly the same EAR with EJB and WAR). The tutorial under http://netbeans.org/kb/docs/javaee/entappclient.html explains how to create an app-client, however it doesn't work for me; there is also a question for that matter: Unable to run app-client that is accessing an EJB on GlassFish v3.
[ "stackoverflow", "0006763623.txt" ]
Q: What is the best way of describing day of week? I planning my inaugural data load into GAE and really want to get my ducks in a row. The language I am using is Python. My question is about the storing of storing read only temporal data in app engine. I have a spreadsheet with ~50k rows times 30 columns. It is historic data and the table will be read-only. I envisage a lot of sorting by day of week (show me weekends in July and so on) and also time (not necessarily always with date - but sometimes with) so my initial thought would be to create an extra row and fill that in a previously-computed "day of week". eg. date, time, dayofweek, event, geolocation, etc 27-02-2009, 08:20:00, 'Friday' ... That date and time shown above reflects how it is coming from the spreadsheet ATM. If I am going to go to the trouble of computing the "dayofweek", which is I presume a good idea, and given your experience of GAE's Datastore models should I: -just have a single datetime? (and let GAE work out the day of week during future sorts/requests?) -create a dayofweek but have a single daydate? '2009-02-27 08:10:00' -store day of week as an integer instead? (0 = Monday in Python IIRC) -store date as '2009-02-27' instead? Output will always be English, and may also be JSON. It is for a data visulatisation study and some extra temporal animation could be done on the client - but my primary concern is to keep the work done in GAE down, which I admit might just be a n00bish fetish. A: If you plan to query based on day-of-week - that is, you need to select several Fridays, but not the neighbouring days - you should absolutely break this out into a separate property, as it'll make it possible to do efficient queries for it. To do the query 'Fridays in July', as you suggest, you've got several options: Without a separate 'day of week' property, you could do four or five queries for each of the valid days With a separate 'day of week' property, you can do a single query on day-of-week and date range. This will use your inequality filter for the date range, so you couldn't also do an inequality filter on any other property in that query. With separate 'day of week' and 'month' properties, you could do the above query without using any inequality filters.
[ "stackoverflow", "0011278165.txt" ]
Q: Overlay two listview with no transparency Ho I have two list view on a frame layout. I want one overlay the other and it has not a transparent background. I have do this <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:id="@+id/autocompleteCompany" android:layout_width="100dip" android:layout_height="wrap_content" android:drawSelectorOnTop="true" android:paddingLeft="30dip" > </ListView> <ListView android:id="@+id/list" android:layout_width="wrap_content" android:layout_height="wrap_content" > </ListView> </FrameLayout> but don't work correctly. Thankyou A: try using <RelativeLayout> instead of <FrameLayout> Edit: To get rid of transparency you need to set the background color of the listView or the items in the listView's adapter. These questions would help you do that: Changing background color of ListView items on Android listview item background color change
[ "askubuntu", "0000009634.txt" ]
Q: Current Exaile song in Empathy status I switched to Exaile a while back, and the only thing I find lacking is the Empathy integration, if I may call it that. I wish to be able to set my IM status as the currently playing music track. Rhythmbox did that out of the box. Exaile doesn't. Any ideas? A: There's a bug on Exaile Launchpad, actually a plugin doesn't exist and the bug is marked as wishlist. On exaile-users group on Google Groups you can find an interesting answer by Adam Olsen (Exaile Developper), the same guy who marked as wishlist the bug. By the way here there's the old working plugin.
[ "stackoverflow", "0029639410.txt" ]
Q: How to use Pygments in Pelican with Markdown? TLDR: I am trying to do CSS line numbering in pelican, while writing in markdown. Pygments is used indirectly and you can't pass options to it, so I can't separate the lines and there is no CSS selector for "new line". Using Markdown in Pelican, I can generate code blocks using the CodeHilite extension. Pelican doesn't support using pygments directly if you are using Markdown...only RST(and ... no to converting everything to RST). So, what I have tried: MD_EXTENSIONS = [ 'codehilite(css_class=highlight,linenums=False,guess_lang=True,use_pygments=True)', 'extra'] And: :::python <div class="line">import __main__ as main</div> And: PYGMENTS_RST_OPTIONS = {'classprefix': 'pgcss', 'linenos': 'table'} Can I get line numbers to show up? Yes. Can I get them to continue to the next code block? No. And that is why I want to use CSS line numbering...its way easier to control when the numbering starts and stops. Any help would be greatly appreciated, I've been messing with this for a few hours. A: The only way I'm aware of is to fork the CodeHilite Extension (and I'm the developer). First you will need to make a copy of the existing extension (this file), make changes to the code necessary to effect your desired result, and save the file to your PYTHONPATH (probably in the "sitepackages" directory, the exact location of which depends on which system you are on and how Python was installed). Note that you will want to create a unique name for your file so as not to conflict with any other Python packages. Once you have done that, you need to tell Pelican about it. As Pelican's config file is just Python, import your new extension (use the name of your file without the file extension: yourmodule.py => yourmodule) and include it in the list of extensions. from yourmodule import CodeHiliteExtension MD_EXTENSIONS = [ CodeHiliteExtension(css_class='highlight', linenums=False), 'extra'] Note that the call to CodeHiliteExtension is not a string but actually calling the class and passing in the appropriate arguments, which you can adjust as appropriate. And that should be it. If you would like to set up a easier way to deploy your extension (or distribute it for others to use), you might want to consider creating a setup.py file, which is beyond the scope of this question. See this tutorial for help specific to Markdown extensions. If you would like specific help with the changes you need to make to the code within the extension, that depends on what you want to accomplish. To get started, the arguments are passing to Pygments on line 117. The simplest approach would be to hardcode your desired options there. Be ware that if you are trying to replicate the behavior in reStructuredText, you will likely be disappointed. Docutils wraps Pygments with some of its own processing. In fact, a few of the options never get passed to Pygments but are handled by the reStructeredText parser itself. If I recall correctly, CSS line numbering is one such feature. In fact, Pygments does not offer that as an option. That being the case, you would need to modify your fork of the CodeHilite Extension by having Pygments return non-numbered code, then applying the necessary hooks yourself before the extension returns the highlighted code block. To do so, you would likely need to split on line breaks and then loop through the lines wrapping each line appropriately. Finally, join the newly wrapped lines and return. I suspect the following (untested) changes will get you started: diff --git a/markdown/extensions/codehilite.py b/markdown/extensions/codehilite.py index 0657c37..fbd127d 100644 --- a/markdown/extensions/codehilite.py +++ b/markdown/extensions/codehilite.py @@ -115,12 +115,18 @@ class CodeHilite(object): except ValueError: lexer = get_lexer_by_name('text') formatter = get_formatter_by_name('html', - linenos=self.linenums, + linenos=self.linenums if self.linenumes != 'css' else False, cssclass=self.css_class, style=self.style, noclasses=self.noclasses, hl_lines=self.hl_lines) - return highlight(self.src, lexer, formatter) + result = highlight(self.src, lexer, formatter) + if self.linenums == 'css': + lines = result.split('\n') + for i, line in enumerate(lines): + lines[i] = '<div class="line">%s</div>' % line + result = '\n'.join(lines) + return result else: # just escape and build markup usable by JS highlighting libs txt = self.src.replace('&', '&amp;') You may have better success in attaining what you want by disabling Pygments and using a JavaScript library to do the highlighting. That depends on which JavaScript Library you choose and what features it has. A: TL; DR in the pelicanconf.py, add this: # for highlighting code-segments # PYGMENTS_RST_OPTIONS = {'cssclass': 'codehilite', 'linenos': 'table'} # disable RST options MD_EXTENSIONS = ['codehilite(noclasses=True, pygments_style=native)', 'extra'] # enable MD options Obviously, you need to have these properly installed pip install pygments markdown
[ "stackoverflow", "0006829452.txt" ]
Q: htaccess rewrite to create friendly urls The following rule works, but it changes the URL in the address bar, which is not intended. RewriteRule ^network/(.*)$ http://www.example.com/network.php?networkUrl=$1 [L] The following rule redirects, the URL stays the same, but all the images, includes in the network.php file become referenced incorrectly... RewriteRule ^network/(.*)$ network.php?networkUrl=$1 [L] Is there a way to make this work? A: This is because your browser interprets paths as relative. To solve this reference your images and CSS with absolute paths, i.e. <img href="image.jpg" /> becomes <img href="/image.jpg" /> Same applies for css so <link href="stylesheets/foo.css" media="print" rel="stylesheet" type="text/css"/> becomes <link href="/stylesheets/foo.css" media="print" rel="stylesheet" type="text/css"/> In this way all resources links works as expected when referenced from any depth as /foo/bar/baz/script.php and so on.
[ "stackoverflow", "0024522781.txt" ]
Q: Get Cloud Service Name in a Web Role We have a requirement of logging Cloud Service Name where Web Role is deployed. We are getting Role Name & Role Instance Id from RoleEnvironment class in Azure ServiceRuntime library. But not finding Cloud Service Name. A: You can't find this information via RoleEnvironment class. You would need to use Service Management API for that purpose. Basically the trick is to get the deployment id from RoleEnvironment class and then invoke Service Management API operations to First list the cloud services in the subscription Then iterate over each cloud service to get its deployment properties. Find the one with matching deployment id. That would give you the information you need. To invoke Service Management API operations, you could use Azure Management Library or write your own REST wrapper. I did a blog post long ago where I did similar thing using REST API: http://gauravmantri.com/2012/03/16/programmatically-finding-deployment-slot-from-code-running-in-windows-azure/.
[ "askubuntu", "0000057506.txt" ]
Q: unity home quicklist not working hello i have tried adding some quicklists to the unity launcher i added some to the gnome-terminal and they work fine added some to the nautilus-home but cannot get them to display here is my .desktop file [Desktop Entry] Name=Home Folder Comment=Open your personal folder TryExec=nautilus Exec=nautilus --no-desktop Icon=user-home Terminal=false StartupNotify=true Type=Application Categories=GNOME;GTK;Core; OnlyShowIn=GNOME;Unity X-GNOME-Bugzilla-Bugzilla=GNOME X-GNOME-Bugzilla-Product=nautilus X-GNOME-Bugzilla-Component=general X-Ubuntu-Gettext-Domain=nautilus X-Ayatana-Desktop-Shortcuts=bin;Documents;Downloads;Pictures;Video;Music;Ubuntu One;src; [bin Desktop Shortcut Group] Name=bin Exec=nautilus bin TargetEnvironment=Unity [Documents Desktop Shortcut Group] Name=Documents Exec=nautilus Documents TargetEnvironment=Unity [Downloads Desktop Shortcut Group] Name=Downloads Exec=nautilus Downloads TargetEnvironment=Unity [Pictures Desktop Shortcut Group] Name=Pictures Exec=nautilus Pictures TargetEnvironment=Unity [Video Desktop Shortcut Group] Name=Video Exec=nautilus Video TargetEnvironment=Unity [Music Desktop Shortcut Group] Name=Music Exec=nautilus Music TargetEnvironment=Unity [Ubuntu One Desktop Shortcut Group] Name=Ubuntu One Exec=nautilus Ubuntu\ One TargetEnvironment=Unity [src Desktop Shortcut Group] Name=src Exec=nautilus src TargetEnvironment=Unity A: A few things wrong - here is a suggested revision: [Desktop Entry] Name=Home Folder Comment=Open your personal folder TryExec=nautilus Exec=nautilus --no-desktop Icon=user-home Terminal=false StartupNotify=true Type=Application Categories=GNOME;GTK;Core; OnlyShowIn=GNOME;Unity X-GNOME-Bugzilla-Bugzilla=GNOME X-GNOME-Bugzilla-Product=nautilus X-GNOME-Bugzilla-Component=general X-Ubuntu-Gettext-Domain=nautilus X-Ayatana-Desktop-Shortcuts=bin;Documents;Downloads;Pictures;Video;Music;UbuntuOne;src; [bin Shortcut Group] Name=bin Exec=nautilus bin TargetEnvironment=Unity [Documents Shortcut Group] Name=Documents Exec=nautilus Documents TargetEnvironment=Unity [Downloads Shortcut Group] Name=Downloads Exec=nautilus Downloads TargetEnvironment=Unity [Pictures Shortcut Group] Name=Pictures Exec=nautilus Pictures TargetEnvironment=Unity [Video Shortcut Group] Name=Video Exec=nautilus Video TargetEnvironment=Unity [Music Shortcut Group] Name=Music Exec=nautilus Music TargetEnvironment=Unity [UbuntuOne Shortcut Group] Name=Ubuntu One Exec=nautilus "Ubuntu One" TargetEnvironment=Unity [src Shortcut Group] Name=src Exec=nautilus src TargetEnvironment=Unity Suggested changes: the group names (the bits between the square brackets) cannot have spaces I've quoted "Ubuntu One" - not sure if necessary but makes it easier to read.
[ "apple.stackexchange", "0000085520.txt" ]
Q: uptime: /dev/ttys003: No such file or directory When I use the uptime command on OS X, this error is printed: $ uptime uptime: /dev/ttys003: No such file or directory 20:57 up 36 days, 22:10, 3 users, load averages: 1.77 1.37 1.75 By running the who command, I see that there is another terminal logged in -- but I don't have any other terminals or SSH sessions. $ who Kevin console Mar 10 17:49 Kevin ttys000 Mar 14 17:45 kevin ttys003 Mar 14 20:59 This is kind of annoying. How do I get rid of the "No such file" message? A: Terminals are numbered sequentially. The first terminal opened was 000, so I opened 3 more so that the 003 number would be used. I closed all extra terminals and uptime worked without error again.
[ "stackoverflow", "0007195020.txt" ]
Q: Type of listener for updates to given cells/columns in JTable and incrementing focus I am trying to use a JTable with the first column predefined. The user enters data into the 2nd column only (Quantity). Then I calculate the final income by multiplying the Service and Quantity columns and display it in the third column, Income. |Service | Quantity | Income |$40.00 | X | |$40.00 | 3 | 120 Here user inputs "3" because she did "3" of service X today at $40 each. The user can only update the Quantity column. The Income column will be calculated by the system. What type of listener should I use? I was using a TableModelListener but when I want to update Income to 120 by calling setValue = $120 it fires off a TableListenerEvent and hence an infinite loop. Should I use an ActionEvent, a ColumnListener or something else? Also, I want the "focus" to increment down the rows, always staying on the second column (the column the user edits). A: for Listning changes into TableCell you have to implements TableModelListener for example import java.awt.event.KeyEvent; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; public class TableProcessing extends JFrame { private static final long serialVersionUID = 1L; private JTable table; private String[] columnNames = {"Item", "Quantity", "Price", "Cost"}; private Object[][] data = { {"Bread", new Integer(1), new Double(1.11), new Double(1.11)}, {"Milk", new Integer(1), new Double(2.22), new Double(2.22)}, {"Tea", new Integer(1), new Double(3.33), new Double(3.33)}, {"Cofee", new Integer(1), new Double(4.44), new Double(4.44)}}; private TableModelListener tableModelListener; public TableProcessing() { DefaultTableModel model = new DefaultTableModel(data, columnNames); table = new JTable(model) { private static final long serialVersionUID = 1L; @Override// Returning the Class of each column will allow different renderers public Class getColumnClass(int column) { // to be used based on Class return getValueAt(0, column).getClass(); } @Override // The Cost is not editable public boolean isCellEditable(int row, int column) { int modelColumn = convertColumnIndexToModel(column); return (modelColumn == 3) ? false : true; } }; table.setPreferredScrollableViewportSize(table.getPreferredSize()); //http://stackoverflow.com/questions/7188179/jtable-focus-query/7193023#7193023 table.setCellSelectionEnabled(true); KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0); InputMap map = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); map.put(tab, "selectNextRowCell"); //http://stackoverflow.com/questions/7188179/jtable-focus-query/7193023#7193023 JScrollPane scrollPane = new JScrollPane(table); getContentPane().add(scrollPane); setTableModelListener(); } private void setTableModelListener() { tableModelListener = new TableModelListener() { @Override public void tableChanged(TableModelEvent e) { if (e.getType() == TableModelEvent.UPDATE) { System.out.println("Cell " + e.getFirstRow() + ", " + e.getColumn() + " changed. The new value: " + table.getModel().getValueAt(e.getFirstRow(), e.getColumn())); int row = e.getFirstRow(); int column = e.getColumn(); if (column == 1 || column == 2) { TableModel model = table.getModel(); int quantity = ((Integer) model.getValueAt(row, 1)).intValue(); double price = ((Double) model.getValueAt(row, 2)).doubleValue(); Double value = new Double(quantity * price); model.setValueAt(value, row, 3); } } } }; table.getModel().addTableModelListener(tableModelListener); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { TableProcessing frame = new TableProcessing(); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
[ "stackoverflow", "0024211130.txt" ]
Q: Better way of showing images from a model in razor EDIT: it was the @ViewBag.Persona(item.IDPersona) part the problem. In a view I iterate over a collection of models, each model has an url that corresponds to an image in the server. I want to display in a table every model with its image. So I did something like this: <table class="tbody"> <tr class="th"> <th>ID </th> <th>Person </th> <th>Image </th> </tr> @foreach (var item in Model.Entity) { <tr> <td> @Html.ActionLink(item.IDPersona.ToString(), "Edit", "Persona", new{Id = item.IDPersona}, null) </td> <td> @ViewBag.Persona(item.IDPersona) </td> <td> <img src="/img/@item.ImageName" height="100" width="100" /> </td> </tr> } </table> But the page can take up to 13 seconds to load. I imagine that the reason is because I am loading one image at a time instead of loading multiple images simultaneously. Is there a way to improve the loading time? Maybe "delaying" the load of the image until the model have been iterated entirely, is this possible? A: Looking at your code, and going off of the details in your comments, I don't think it's the images causing the issue. If it's simply pulling the images off of the local file system it's not likely that they'd be the cause of the slowness.
[ "stackoverflow", "0000335487.txt" ]
Q: Programmatically setting Emacs frame size My emacs (on Windows) always launches with a set size, which is rather small, and if I resize it, it's not "remembered" at next start-up. I've been playing with the following: (set-frame-position (selected-frame) 200 2) ; pixels x y from upper left (set-frame-size (selected-frame) 110 58) ; rows and columns w h which totally works when I execute it in the scratch buffer. I put it in my .emacs, and although now when I start the program, I can see the frame temporarily set to that size, by the time *scratch* loads, it resets back to the small default again. Can anyone help me fix up the above code so that it "sticks" on start-up? A: Here's what I use in my ~/.emacs: (add-to-list 'default-frame-alist '(left . 0)) (add-to-list 'default-frame-alist '(top . 0)) (add-to-list 'default-frame-alist '(height . 50)) (add-to-list 'default-frame-alist '(width . 155)) A: (setq initial-frame-alist '( (top . 40) (left . 10) (width . 128) (height . 68) ) ) A: Did you try this : emacs -geometry 110x58+200+2 & Found at : http://web.mit.edu/answers/emacs/emacs_window_size.64R.html
[ "stackoverflow", "0029330368.txt" ]
Q: get relative position after GetCursorPos in CLR? So as of now, I've managed to successfully get the x and y coordinates. Inside the panel code. POINT cursorPos; GetCursorPos(&cursorPos); int x; int y; x = cursorPos.x; y = cursorPos.y; cout << x << endl; cout << y << endl; However, the x and y coordinate that I got is global, aka, not within a panel that I want to get my coordinates from. I do understand that ClientToScreen is required to change the x and y coordinate to its relative placing, but how do i do that in C++/CLR? Because ClientToScreen requires a handle, which is not introduced in C++/CLR (Pardon me if im wrong about this point). Thanks :) Update: I tried casting my panel into a hwnd, but still its not working. HWND hwnd = static_cast<HWND>(this->panel1->Handle.ToPointer()); A: You get global coordinates because GetCursorPos() is relative to the screen. To convert it to Application coordinates, you simply use ScreenToClient() on the POINT structure filled by GetCursorPos(). Check the documentation here: https://msdn.microsoft.com/en-us/library/windows/desktop/dd162952%28v=vs.85%29.aspx
[ "stackoverflow", "0012939813.txt" ]
Q: how to cancel customvalidators action? I have a webform with a textbox and 3 buttons (add, save and cancel), I'm learning how to use customvalidators (ASP.NET 4.0). Once the page is loaded, you can only see the add button, after you click on it you can see the textbox and the other 2 buttons. If textbox is empty I can't save the record (I get this done successfully with customvalidator and javascript, it shows me the error message "textbox can not be left empty"), but what happens if I don't want to save the record anymore and want to cancel instead (by clicking on the cancel button while textbox is still empty)? I get the customvalidator error "textbox can not be left empty". I have to type something i it so I can do what i need. Any suggestions? Thanks in advance A: For Cancel button set the attribute CausesValidation="false". That is it...
[ "stackoverflow", "0035853970.txt" ]
Q: How to use factory to resolve interface using Autofac I want to have a service like the following public SomeService(IMongoDatabase mongoDatabase) { DB = mongoDatabase; } and I want to use a factory to resolve IMongoDatabase, just to encapsulate the IConfiguration usage public static IMongoDatabase GetMongoDatabase(IConfiguration config) { var connectionString = config.Get("SomeConnectionString"); // MongoClient handles connection pooling internally var client = new MongoClient(connectionString); var db = client.GetDatabase(config.Get("SomeDbName")); return db; } I can't figure out how to handle the registrations so that MongoDbFactory.GetMongoDatabase gets called whenever any class needs an IMongoDatabase. IConfiguration will be registered already. I'd really like to just use an IMongoDatabase and not a Func<IConfiguration, IMongoDatabase> in my Service. The latter just seems way too obtuse, requiring consumers to implement steps that I should be able to implement for them. A: You can register your static GetMongoDatabase factory method like this : builder.Register(c => MongoDbFactory.GetMongoDatabase(c.Resolve<IConfiguration>)()) .As<IMongoDatabase>(); By the way, using a static method may introduce some problem, it may be better to register the MongoDbFactory class and use it in your factory registration. builder.RegisterType<MongoDbFactory>() .AsSelf(); builder.Register(c => c.Resolve<MongoDbFactory>().GetMongoDatabase()) .As<IMongoDatabase>(); Of course, you will need to adapt the MongoDbFactory implementation to make it work - by adding a property for Configuration and adding IConfiguration to the constructor.
[ "stackoverflow", "0062476153.txt" ]
Q: Catalyst State Restoration via SceneDelegate not working When quitting my catalyst application via the dock icon (right click -> quit) my SceneDelegate's stateRestorationActivity(for scene: UIScene) method is called and I return a non-nil NSUserActivity. However, when restarting my application there is no user activity in the connectionOptions of scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) Does this function correctly for anyone else? Do I need to build my UserActivity in a specific way for this to work in Catalyst? It functions correctly when running on iOS. A: Spoke with an engineer during a WWDC2020 Lab about this. My issue, as odd as it seems, was restarting the application too soon after quitting it. iOS applications running on Catalyst will linger after being quit. This can be observed in Activity Monitor. It was explained that this is the period where the app can finish any registered background tasks. After waiting for my application to disappear from ActivityMonitor and then relaunching, it restored the activity provided in stateRestorationActivity(for scene: UIScene)
[ "stackoverflow", "0035010106.txt" ]
Q: Angular 2 EventEmitter in Aurelia I'm working on porting some angular 2 code to Aurelia and for the most it's an easy task. However, there is something I wonder about. In angular 2 custom elements I've seen references to: @Output() onChange: EventEmitter<any> = new EventEmitter(); and in an event handler: this.onChange.next(input.checked); My question is: what would be the equivalent representation in aurelia? br hw A: Several ways you can do this, here's a couple examples: Using @bindable my-component.js import {bindable} from 'aurelia-framework'; export class MyComponent { @bindable change; notifyChange() { this.change({ someArg: 'something', anotherArg: 'hello' }); } } app.html <template> ... <my-component change.call="handleChange(someArg, anotherArg)"></my-component> ... </template> app.js export class App { handleChange(a, b) { ... } } Using DOM events my-component.js import {inject} from 'aurelia-framework'; import {DOM} from 'aurelia-pal'; @inject(Element) export class MyComponent { constructor(element) { this.element = element; } notifyChange() { let detail = { someArg: 'something', anotherArg: 'hello' }; let eventInit = { detail, bubbles: true }; let event = DOM.createCustomEvent('change', eventInit); this.element.dispatchEvent(event); } } note: DOM.createCustomEvent is not required. Use new CustomEvent(...) if you do not want to abstract away the DOM for testing purposes or otherwise. app.html <template> ... <my-component change.delegate="handleChange($event)"></my-component> ... </template> app.js export class App { handleChange(event) { ... } }
[ "superuser", "0001259431.txt" ]
Q: Freezing top row while sorting in Excel The first column in my spreadsheet has "Last name" in the top row, which is frozen, and last names below it. I am trying to order the rows by the last name, alphabetically. How can I make Excel keep the first row on top? It always puts "Last name" together with other names starting with "L". A: Click the "Sort & Filter" button in the "Editing" section under the "Home" tab. Choose "Custom Sort." Check "My data has headers," then customize your sort parameters. A: Turn the data into an Excel Table like this select the data and hit Ctrl - T select the data and click Insert > Table Tick the box for "My table has headers". Now you can use the drop-down commands in each table header to sort (and/or filter) by that column.
[ "stackoverflow", "0026224783.txt" ]
Q: Executing a function only once I'm using Waypoints.js to start a counter function when I scroll down the page: $(".counter").waypoint(function() { $(".counter").count(); }, {offset:"100%"}); Everything works great but if I scroll up the page and down again to the counter, it starts counting all over again. How can I execute the counter function only once? A: Not sure what that code is meant to do, but you can always use a flag variable to control something like that: var executed = false; $(".counter").waypoint(function() { if (!executed) { executed = true; $(".counter").count(); } }, {offset:"100%"});
[ "math.stackexchange", "0001847997.txt" ]
Q: What is the point of "seeing" a set of polynomials or functions as a vector space? I just had a course in linear algebra. It seemed that the main purpose is to lay the foundations of vector spaces, show ways of solving systems of linear equations and in the end, classify some quadrics. But in certain points, they point several examples of what vector spaces could be but there is no development of these ideas. For example: The vector spaces of all polynomials of degree $\leq n$. What got me confused is that I can use matrices to solve certain systems of linear equations, it seemed that I learned matrix operations and ideas in vector spaces for this end. But why is it important to treat those polynomials as vector spaces? What do I gain with it? Where does the study of them lead to? I've tried to think about the inner product of these polynomials: $$\displaystyle \langle p_1(x),p_2(x) \rangle= \int_{0}^{1} p_1(x) p_2(x) dx$$ and at least making some analogies with what I learned with coordinate geometry, I guess It's possible to build a kind of geometry of these polynomials, for example: I guess two polynomials are perpendicular if $\displaystyle \int_{0}^{1} p_1(x) p_2(x) dx=0$. As $\langle p_1,p_1 \rangle=|p_1|^2$ then $|p_1|=\sqrt{\langle p_1, p_1 \rangle }=\sqrt{\displaystyle \int_{0}^{1} p_1(x) p_1(x) dx}$, then: The angle between two polynomials should be $$\displaystyle \arccos \frac{\langle p_1,p_2\rangle}{|p_1||p_2|}= \arccos \frac{\displaystyle \int_{0}^{1} p_1(x) p_2(x) dx}{\sqrt{\displaystyle \int_{0}^{1} p_1(x) p_1(x) dx}\sqrt{\displaystyle \int_{0}^{1} p_2(x) p_2(x) dx}}$$ That Is: I have some basic notions for a "geometry of polynomials" but I have no clue of why I would use that for. And what is more troubling is that it seems to be possible to extend from polynomials to a certain set of functions and hence, have a "geometry of a certain class of functions". I have tried to see if there is any connection from distance from the roots of two polynomials to the distance of two polynomials but found nothing which I could consider useful of interesting. A: They are most likely given as an example to show that certain collections of functions can be seen as vector spaces. One of the reasons this is handy, is that given a vector space, we can look for a basis, which reduces the complexity of considering "all the functions all at once" (which can be hard) to "just looking at the basis functions" (which can be a lot easier). On a slightly different tack, it turns out that an extension ring of a field such that the field commutes with the entire ring can be turned into a vector space, which turns out to be handy in the study of fields, and polynomials in that field. So, for example, complex numbers can be seen as a vector space (of dimension 2) over the reals, and this extension is helpful in studying real polynomials. I wouldn't read too much into "geometric meaning", except by way of analogy. So, for example, the inner product you mention can be used to define a notion of "distance" and "angle" between polynomials, but these aren't easy to visualize in infinite dimensions, and do not necessarily translate to "how close their graphs are".
[ "stackoverflow", "0001282165.txt" ]
Q: Is hard-coded subview sizing brittle or best practice? Coming from a web background, where explicit sizing is generally not considered best practice, I am not used to 'hardcoding' positioning values. For example, is it perfectly acceptable to create custom UITableViewCells with hardcoded values for subviews' frames and bounds? It seems that when the user rotates the device, I'd need another set of hardcoded frames/bounds? If Apple decides to release a larger TABLET ... then I'd need yet another update to the code - it sounds strange to me in that it doesn't seem to scale well. In my specific case, I'd like to use a cell of style UITableViewCellStyleValue2 but I need a UITextField in place of the detailTextLabel. I hate to completely write my own UITableViewCell but it does appear that in most text input examples I've found, folks are creating their own cells and hardcoded sizing values. If that is the case, is there any way I can adhere to the predefined positioning and sizing of the aforementioned style's textLabel and detailTextLabel (ie: I'd like to replace or overlay my UITextField in place of the detailTextLabel but yet have all subview positioning stay in tact)? Just after creating a default cell, cell.textLabel.frame is returning 0 so I assume it doesn't get sized until the cell's 'layoutSubviews' gets invoked .. and obviously that is too late for what I need to do. Hope this question makes sense. I'm just looking for 'best practice' here. -Luther A: There is no best practice. It depends on your application. You can use IB to do dynamic resizing with autorotation. And set properties to modify sizeOfFit, etc. You can also set the frame of any view before layoutSubViews by creating a view and initializing it with CGRect. There a lot of flexibility. I tend to do the static things in IB and the rest in code.
[ "stackoverflow", "0012361894.txt" ]
Q: Android EditText does not work, android:imeOptions="actionNext" android:inputType="phone" I have tried, and only if I delete android:inputType="phone" the keyboard Enter can jump to the Next EditText. I don't know whether there have been some conflicts between android:imeOptions="actionNext" and android:inputType="phone" . code : AutoCompleteTextView has android:imeOptions="actionNext" and android:inputType="phone", but Enter on the keyboard will not go to the next one. <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:paddingBottom="12dp" android:paddingLeft="13dp" android:paddingTop="12dp" android:src="@drawable/fd_28" /> <TextView android:id="@+id/texttitle_phone" style="@style/TextviewRentItem" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="30dip" /> <EditText android:id="@+id/content_phone" style="@style/TextviewRentItemCon3" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="50dip" android:layout_toRightOf="@id/texttitle_phone" android:paddingBottom="12dp" android:paddingRight="15dp" android:paddingTop="12dp" android:imeOptions="actionNext" android:singleLine="true" android:inputType="phone"/> </RelativeLayout> </LinearLayout> <LinearLayout android:id="@+id/linearLayout0_ll" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dip" android:background="@drawable/bg_rect_black_filled_white" android:orientation="vertical" > <!-- the second--> <RelativeLayout android:id="@+id/linearLayout0" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <ImageView android:id="@+id/img_house" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:paddingBottom="12dp" android:paddingLeft="10dp" android:paddingTop="12dp" android:src="@drawable/fd_29" /> <TextView android:id="@+id/textview3" style="@style/TextviewRentItem" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="30dip" android:focusable="true" android:text="@string/house" /> <AutoCompleteTextView android:id="@+id/add_rent_manage_house" style="@style/TextviewRentItemCon3" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="50dip" android:layout_toRightOf="@id/textview3" android:dropDownHeight="90dp" android:hint="@string/default_add_rent_house_remind" android:imeOptions="actionNext" android:singleLine="true" /> </RelativeLayout> A: (Answered by the OP in an edit and in comments. See Question with no answers, but issue solved in the comments (or extended in chat) ) The OP wrote: Problem has been solved. My EditText use setOnClickListener , delete this listener event ,that's ok @xbakesx wrote: I think the real solution to your problem was adding android:singleLine="true"
[ "stackoverflow", "0028913264.txt" ]
Q: how to throw error if the name has been inserted more than 2 times in sql in php? how to throw error if the name has been inserted more than 5 times in sql in php?? $sql = mysql_query("INSERT INTO `transfer`(`t_id`, `agent_id`, `agent_name`, `date`, `name`, `phone`, `email`, `tname`, `tphone`, `temail`, `status`) VALUES (NULL,'$agent_id','$agent_name','$date','$name','$phone','$email','$tname','$tphone','$temail','$cmmnt','$status')"); A: Try this $sql = mysql_query("SELECT * FROM transfer HAVING COUNT(name) > 5"); if (mysql_num_rows($sql) != 0) { // There are more than 5 - print an error. echo 'Error - More than 5'; }else{ // No Error - Insert $insert_query = "INSERT INTO `transfer`(`t_id`, `agent_id`, `agent_name`, `date`, `name`, `phone`, `email`, `tname`, `tphone`, `temail`, `status`) VALUES (NULL,'$agent_id','$agent_name','$date','$name','$phone','$email','$tname','$tphone','$temail','$cmmnt','$status')"; $insert_result= $mysqli -> query($insert_query); }
[ "serverfault", "0000295813.txt" ]
Q: Create groups of backends depending of the virtual host requested Say I have 6 web servers behind haproxy. Web servers should provide virtual hosting using apache (apache or nginex does not matter). I would like to be able to specify where the incoming HTTP requests (hitting haproxy) should go based on the virtual host. For instance a.domain.com request should go to web1 and web2 b.domain.com request should go to web1, web2 and web3 c.domain.com request should go to web4 and web5 d.domain.com request should go to web5 and web6 e.domain.com request should go to web3, web4, web5 and web6 The idea is to have a HA, load-balanced shared hosting where users can choose on how many servers, 2 to 6 (in this case). The other important thing is that I want to load_balance sites in some servers not in all servers so I could horizontally scale to accept more customers. Is it possible? If not do you now an alternative solution? A: Google sez that defining a bunch of ACLs is the way to go, something like this: frontend http bind *:80 acl host_site_a hdr(host) -i a.domain.com acl host_site_b hdr(host) -i b.domain.com use_backend site_a if host_site_a use_backend site_b if host_site_b backend site_a server web1 web1:80 server web2 web2:80 backend site_b server web1 web1:80 server web2 web2:80 server web3 web3:80 And so on. Extend and flesh out as necessary.
[ "stackoverflow", "0041139622.txt" ]
Q: Having trouble getting started with bootstrap, can't find files I'm getting started with Bootstrap but I'm having difficulty in properly displaying the website on account of the fact that I keep getting the error Not Found: /checkin/css/bootstrap.min.css and Not Found: /js/bootstrap.min.js (checkin is the name of my app. Here's the code I'm using that I got from the Bootstrap website: {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>Bootstrap 101 Template</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- <link href="css/bootstrap.min.css" rel="stylesheet"> --> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <script src="{% static 'jquery/3.1.1/jquery.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> </head> <body> <nav class="navbar navbar-inverse navbar-static-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Balance Web Development</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">About</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Services<span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Design</a></li> <li><a href="#">Development</a></li> <li><a href="#">Consulting</a></li> </ul> </li> <li><a href="#">Contact</a></li> </ul> </div> </div> </nav> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <!-- Include all compiled plugins (below), or include individual files as needed --> </script> </body> </html> I'm not sure what the issue is, I downloaded bootstrap and extracted the css, fonts and js folders to /checkin/ but the browser can't find them. I downloaded JQuery by saving it as jquery.js into the /checkin/ folder as well. EDIT Some of my project structure: 404 Errors I'm getting in powershell: A: Maintaining a standard project structure always helps and ease the work for anyone. For normal web application you can follow this standard practise : root/ assets/ lib/-------------------------libraries-------------------- bootstrap/--------------Libraries can have js/css/images------------ css/ js/ images/ jquery/ js/ font-awesome/ css/ images/ common/--------------------common section will have application level resources css/ js/ img/ index.html Below is your same file but try linking them properly with your js and css and remove direct online links. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>Bootstrap 101 Template</title> <!-- Bootstrap defualt files --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!-- Your Bootstrap and js defualt files (Adjust them) --> <link rel="stylesheet" href="/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="/jquery/3.1.1/jquery.min.js"></script> <script src="/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!-- your own custom css and js files --> </head> <body> <nav class="navbar navbar-inverse navbar-static-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Balance Web Development</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">About</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Services<span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Design</a></li> <li><a href="#">Development</a></li> <li><a href="#">Consulting</a></li> </ul> </li> <li><a href="#">Contact</a></li> </ul> </div> </div> </nav> </body> </html>
[ "ru.stackoverflow", "0001102260.txt" ]
Q: Записать float в экспоненциальной форме в файл Имеется число типа float, нужно представить его в экспоненциальной форме и записать в файл. Как это можно сделать? Нужно использовать какой-то спецификатор? Если мне нужно просто записать float с какой-то точностью, как в таком случае поступить? Спасибо! A: Привести вид числа в экспоненциальный: number = 12.123456789 exp_number = "{:.3e}".format(number) Теперь можно сохранять в файл. Число 3 - количество знаков после запятой.
[ "stackoverflow", "0037193235.txt" ]
Q: Excel VBA- Having trouble copying from one worksheet to another I'm trying to copy from different worksheets to fill out a summary sheet based on data. However, I'm getting that darn vague error "Application or Object defined error" and I don't know what the issue is. Code below: Sub jtest() 'For j = 3 To Rows.Count (will loop later once I make sure one iteration works) j = 3 Atext = Cells(j, "A").Text Worksheets(Atext).Range("U6").Copy Destination:=Worksheets("Summary 2").Range(j, "C") Worksheets(Atext).Range("X6").Copy Destination:=Worksheets("Summary 2").Range(j, "D") Worksheets(Atext).Range("Z6").Copy Destination:=Worksheets("Summary 2").Range(j, "F") Worksheets(Atext).Range("V7").Copy Destination:=Worksheets("Summary 2").Range(j, "G") ' Next j End Sub A: First, I suggest adding Option Explicit to the very top, so you're forced to declare variables. Second, you're using Range() incorrectly when pasting. Change that to Cells() and you're good to go! Sub jtest() Dim j&, Atext$, lastRow& Application.ScreenUpdating = False Application.Calculation = xlCalculationManual lastRow = Worksheets("Sheet1").Cells(Sheet("Sheet1").Rows.Count,1).End(xlUp).Row ' CHANGE THAT WORKSHEET AS NECESSARY. I'm also assuming your Column A has the most data. For j = 3 To lastRow Atext = Worksheets("Sheet1").Cells(j, "A").Text ' CHANGE THAT WORKSHEET AS NECESSARY Worksheets("Summary 2").Cells(j, "C").Value = Worksheets(Atext).Range("U6").Value Worksheets("Summary 2").Cells(j, "D").Value = Worksheets(Atext).Range("X6").Value Worksheets("Summary 2").Cells(j, "F").Value = Worksheets(Atext).Range("Z6").Value Worksheets("Summary 2").Cells(j, "G").Value = Worksheets(Atext).Range("V7").Value Next j Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub I've edited your idea a tad. Instead of looping over 200,000 times (which would happen if you use Rows.Count), I created a lastRow variable, assuming your "Sheet1" column A has the most data (edit as necessary). I've also just set the ranges' values equal, which skips using the Clipboard, and is a little faster. Note that this will only keep the values, if you need the format, then switch back to .Copy Destination:= ... but change your Range(j, "C") to Cells(j, "C").
[ "stackoverflow", "0016145272.txt" ]
Q: Getting & Passing a search to a stored procedure Good day, I have found a few examples that are close to what I want, such as Execute a SQL Stored Procedure and process the results however I am just struggling to see the wood for the trees on this one... I have an SQL database & a stored procedure within there that has a variable @ModuleName I want a user to type text into a text box and click search. When search is clicked the word typed into the search box is passed into @ModuleName i.e. Searchtext.txt = @ModuleName This is then passed off to the StoredProcedure and used to create the SQL for Gridview called GridView1. I have tried alot of techniques and am clearly missing something Stored Procedure ALTER PROCEDURE [dbo].[spModuleID] @ModuleName char(50) AS BEGIN select * from dbo.ModuleID where [ModuleName] = @ModuleName ORDER BY [ModuleName] END Gridview1 links to SQL like this.. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True" DataKeyNames="ModuleID"> <Columns> <asp:BoundField DataField="ModuleID" HeaderText="ModuleID" ReadOnly="True" SortExpression="ModuleID" /> <asp:BoundField DataField="ModuleName" HeaderText="ModuleName" SortExpression="ModuleName" /> </Columns> </asp:GridView> I have some code under the searhc button now that hopefulyli s heading the right way... Protected Sub Search(sender As Object, e As System.EventArgs) Handles btnSearch.Click Dim myds As New DataSet1 MyConnection.ConnectionString = LearnConnectionString Dim disp As New SqlDataAdapter("spModuleName", MyConnection) disp.Fill(myds, "dev_display") 'Below wants to be a datagrid txtDisplay.Text = myds.Tables("dev_display").Rows(0).Item("knownsoft") myds.Dispose() End Sub A: Imports System.Data.OleDb Dim cmd as new Oledb.OleDbCommand Dim connection As New SqlConnection("Connection String") cmd.Connection = connection cmd.CommandText = "SP_NAME" cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@PARAMETER_NAME", "PARAMETER_VALUE") Dim adapter As New SqlDataAdapter(CMD) Dim DS as DataSet adapter.Fill(DS) connection.Close() ds.Dispose() ds = Nothing
[ "stackoverflow", "0033309216.txt" ]
Q: Slider functions don't have enough time on fast clicks I created a simple slider using JQuery. It uses the following functions to work: function moveleft(){ if (current < $length - 1){ $tape.animate({"margin-left":"-=" + $width}, $speed, function(){ current++; }) }else if(current == $length - 1){ $tape.css("margin-left", 0); current = 0; $tape.animate({"margin-left":"-=" + $width}, $speed, function(){ current++; }) } }; function moveright(){ if (current == 0){ $tape.css("margin-left", -$last); current = $length - 1; $tape.animate({"margin-left":"+=" + $width}, $speed, function(){ current--; }) }else if (current > 0){ $tape.animate({"margin-left":"+=" + $width}, $speed, function(){ current--; }) } } Demo: http://jsfiddle.net/gdgk9wsf/ It works, but the trouble is that when user clicks buttons too fast, it probably doesn't have enough time to calculate the values. So, everything just goes far left or right. Is there anything I can add to fix it? A: You could wrap the functions in an is animated check, like so... This will make sure the animation finished before it can be clicked again, and do anything. function moveleft(){ if( $(tape).is(':animated') ) {return} else{ if (current < $length - 1){ $tape.animate({"margin-left":"-=" + $width}, $speed, function(){ current++; }) }else if(current == $length - 1){ $tape.css("margin-left", 0); current = 0; $tape.animate({"margin-left":"-=" + $width}, $speed, function(){ current++; }) } } };
[ "mathoverflow", "0000122918.txt" ]
Q: Real forms of Drinfeld-Jimbo quantum groups A real form of a Hopf algebra $H$ over $\mathbb{C}$ is defined to be a $\ast$-structure on $H$ which is compatible with the coproduct. Compatibility of the $\ast$-structure with the counit and antipode then follows. The real forms of the Drinfeld-Jimbo quantum groups $U_q(\mathfrak{g})$ have been classified. This result is stated as Theorem 20 in Chapter 6 of Quantum Groups and their Representations, by Klimyk and Schmudgen, and also Proposition 9.4.2 of A Guide to Quantum Groups, by Chari and Pressley. For a given $\mathfrak{g}$, there are $\ast$-structures when $q \in \mathbb{R}$ or when $|q|=1$. These $\ast$-structures depend on a diagram automorphism of the Dynkin diagram of $\mathfrak{g}$, plus some extra parameters, and it is understood which sets of parameters give equivalent $\ast$-structures. There is also an exceptional case, but the two sources I have cited differ on what the exceptional case is. Klimyk and Schmudgen say that the exceptional case is when $\mathfrak{g} = \mathfrak{sp}_{2n}$ and $q \in i \mathbb{R}$, while Chari and Pressley say that the exceptional case is $\mathfrak{g} = \mathfrak{so}_{2n+1}$ and $q \in i \mathbb{R}$. Neither book contains a proof, nor cites a source, although Chari-Pressley gives a sketch of the idea of the proof. So I would be interested in knowing the following things: Which is correct? What is the original reference for the classification of the real forms of $U_q(\mathfrak{g})$? To set the record straight It appears that the paper Real forms of $U_q(\mathfrak{g})$, by Eric Twietmeyer, is the original reference. According to that paper, it is $\mathfrak{sp}_{2n}$ that has real forms for $q \in i \mathbb{R}$. Many thanks to Uwe Franz for digging up that reference! A: Two references I recall are E. Twietmeyer, Real forms of Uq (g), Lett. Math. Phys. 24, 49-58, 1992. V. Lyubashenko, Real and imaginary forms of quantum groups, Lecture Notes in Math. 1510, 1992, pp 67-78.
[ "stackoverflow", "0001166732.txt" ]
Q: What is the Scala equivalent of Java's ClassName.class? How do I get an instance of Class in Scala? In Java, I can do this: Class<String> stringClass = String.class; What would be the equivalent in Scala? A: There is a method classOf in scala.Predef that retrieves the runtime representation of a class type. val stringClass = classOf[String] You can use the getClass method to get the class object of an instance at runtime in the same manner as Java scala> val s = "hello world" s: String = hello world scala> s.getClass res0: Class[_ <: String] = class java.lang.String
[ "stackoverflow", "0032298263.txt" ]
Q: How do I get Counts/Flag correctly using case expressions in Oracle I have a table with fields and values that look like this. CustomerID OrderMedium NumberofOrder 101 Computer 5 101 Phone 2 102 Computer 9 103 Computer 1 103 Phone 6 104 Phone 2 105 Computer 3 105 Phone 3 From the above table, I am trying to create another table with fields CustomerID, OrderMedium, OnetoFiveOrders, SixtoTenOrders, Count. The customerID field should contain the CustomerID, OrderMedium field should contain the OrderMedium, OnetoFiveOrders should contain a flag of 'Y' if a customer has between one to five orders, SixtoTenOrders should contain a flag of 'Y' if a customer has between Six to Ten orders, and count should contain the Number of Orders. So for example, CustomerID 101 with an OrderMedium of Computer will have a flag of 'Y' under OnetoFiveOrders and count of 5 since they have 5 orders. The problem I'm having is that if the same customer with a different Order Medium has a total order count that is greater than 5 then it should have a flag of 'Y' under SixtoTenOrders, but still give the number of order for that medium So For Customer 101, the table should look like this. CustomerID OrderMedium OnetoFiveOrders SixtoTenOrders Count 101 Computer Y 5 101 Phone Y 2 Since the customer has a total Order count of 7, it should give a flag of 'Y' under SixtoTenOrders and a count of 2 because they have 2 orders under the Phone Order Medium. I'm having problems getting my code to work/output this way and would appreciate any kind of help or suggestion. This is my my code so far: Select CustomerID, OrderMedium, NumberofOrder as Count, case when NumberofOrder between 1 and 5 then 'Y' else case when NumberofOrder between 6 and 10 then 'Y' else null end as OnetoFiveOrders end as SixtoTenOrders from CustOrder; A: If you want the "Y" in columns based on the total order count for the customers, then use analytic functions: Select CustomerID, OrderMedium, (case when sum(NumberofOrder) over (partition by CustomerId) between 1 and 5 then 'Y' end) as OnetoFiveOrders, (case when sum(NumberofOrder) over (partition by CustomerId) between 6 and 10 then 'Y' end) as SixtoTenOrders , NumberofOrder as Count from CustOrder order by CustomerID;
[ "stackoverflow", "0026084747.txt" ]
Q: How to use a rails route for a singular resource in my javascript ajax? Currently I have the following (working) code: # app/assets/javascripts/show_group_members.js.erb ... var gid= $(this).data("id"); ... $.ajax({ type: "GET", url: "/groups/"+gid, contentType: "application/json; charset=utf-8", dataType: "json", ... but I would like to use the routes for a single group resource, i.e. group GET /groups/:id(.:format) groups#show So I am trying to use url: <%= Rails.application.routes.url_helpers.group_path %> + gid, but I am getting No route matches {:action=>"show", :controller=>"groups"} missing required keys: [:id] (in /home/durrantm/.../linker/app/assets/javascripts/show_group_members.js.erb) [Update] The complication here is that the view content itself is generated by a .js.erb template so I still can't use group_path(group) in it. How can I use the route in js when there is a resource ? btw I also tried url: <%= Rails.application.routes.url_helpers.group_path %>, data: { id: gid }, A: I think you are doing it wrong. I would forget about placing Rails code into the js and pass the url with data. Thanks to this you separate your Rails code from JS and avoid issues during assets compilation (like what is the host when no request is made?). # view <span data-link-url="<%= group_path(group.id) %>"></span> # js var link = $(this).data("link-url"); ... $.ajax({ type: "GET", url: link, contentType: "application/json; charset=utf-8", dataType: "json", ... Using <a href="your_link_to_group_here"> <%= link_to 'my link', group_path(group.id) %> var link = $(this).attr('href');
[ "stackoverflow", "0018048164.txt" ]
Q: Working Around JavaFX 2.2 Arabic Text Orientation issue I'm using JavaFX 2.2 but everytime I typed arabic text, the order of the chracters are reversed, since the solution to this problem will only be when JavaFX 8 is released. How can I monitor the textbox and automatically reverse the characters typed back to the way it should be with something like: arabicTextBox.setOnKeyPressed(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent t) { //TODO: correct arabic text order here } }); A sample implementation will be appreciated. A: Use Event Filter instead of simple KeyPressed because it will allow you to consume event and override default TextField behaviour. For simplest case (without keyboard navigation) you can handle only KeyEvent.KEY_TYPED: final TextField tf = new TextField(); tf.addEventFilter(KeyEvent.ANY, new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent t) { if (KeyEvent.KEY_TYPED == t.getEventType()) { // put character to the first position tf.setText(t.getCharacter() + tf.getText()); } t.consume(); // doesn't allow TextField to handle keyboard events by itself } }); If you want full fledged arabic-only TextField you can add logic for arrow keys, caret position, etc.
[ "stackoverflow", "0049498612.txt" ]
Q: How to sort JStree (Jquery PlugIn ) node Alphabetically by ignoring case (capital letter and small letter) I am using JsTree plugin to draw a tree of folders and files, here you can see my sort mathode. 'sort' : function(a, b) { a1 = this.get_node(a); b1 = this.get_node(b); if (a1.icon == b1.icon){ return (a1.text > b1.text) ? 1 : -1; } else { return (a1.icon > b1.icon) ? 1 : -1; } This piece of code give me result like AA BB aa its mean folders having name start with small letter,always going to be show after capital letter folder name.According to ASCII Capital letters Always sort first and small letter sort after capital letters. But i want to sort folder name such as AA aa BB I mean folder must be sort alphabetically order by ignoring case letter.Thanks in Advance A: An alternative is either toUpperCase or toLowerCase the strings: Recommendation: use the function localeCompare to make the comparison between both strings. The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. if (a1.icon == b1.icon){ return a1.text.toLowerCase().localeCompare(b1.text.toLowerCase()); } else { return a1.icon.toLowerCase().localeCompare(b1.icon.toLowerCase()); }
[ "stackoverflow", "0036542602.txt" ]
Q: webpack extract text plugin prints a lot I am using the webpack extract text plugin to extract styles into a css file. It prints a lot of stuff like this: Child extract-text-webpack-plugin: + 2 hidden modules Child extract-text-webpack-plugin: + 7 hidden modules Child extract-text-webpack-plugin: + 7 hidden modules Child extract-text-webpack-plugin: + 2 hidden modules Child extract-text-webpack-plugin: + 2 hidden modules Child extract-text-webpack-plugin: + 4 hidden modules Is there any way to surpress it via config? It's pretty useless and cramps the terminal window. A: Yes, it is possible to suppress messages from child plugins by adding { stats: { children: false } } option to your webpack config. module.exports = { stats: { children: false } }; There is an issue reported upstream regarding chatty behavior.
[ "stackoverflow", "0046733797.txt" ]
Q: Error trying to diff ''. Only arrays and iterables are allowed I keep getting the following console error: Error trying to diff 'Paul'. Only arrays and iterables are allowed HTML: <fieldset class="one-quarter sm-padding"> <label>Occupation</label> <select name="occupations" [(ngModel)]="occupations" (ngModelChange)="showValuePromptText('Occupation', $event)"> <option *ngFor="let occupation of occupations" [value]="occupation"> {{occupation}} </option> </select> </fieldset> TS: import { Component } from '@angular/core'; import { PromptService } from '../../services/prompt.service'; import { IPromptText } from "../../models/IPromptText"; @Component({ selector: 'fact-find', templateUrl: './factfind.component.html', styleUrls: ['./factfind.component.css'], providers: [PromptService] }) export class FactFindComponent { promptTexts: IPromptText[]; currentPromptText : string; showDefaultPromptText(fieldName: string) { if (fieldName != null) { this.promptService.fetchPrompts(fieldName, '').subscribe( (data) => this.currentPromptText = data ); } } showValuePromptText(fieldName: string, fieldValue: string) { if (fieldValue != null) { this.promptService.fetchPrompts(fieldName, fieldValue).subscribe( (data) => this.currentPromptText = data ); } } occupations: string[] = ["John", "Paul", "George", "Ringo"]; } If anyone could shed some light on how I can fix this it would be greatly appreciated. A: Basic Explanation As others have noted, the issue is in the [(ngModel)]="occupations" line. It looks to me like it should be something like [(ngModel)]="selectedOccupation". In other words, you need to bind the [(ngModel)] to a string variable in the component. Longer Explanation Consider the following example and let's break it down to understand this is saying: <select [(ngModel)]="selectedOccupation" (ngModelChange)="test()"> <option *ngFor="let occupation of occupations" [value]="occupation"> {{occupation}} </option> </select> In this example, the [(ngModel)]="selectedOccupation" bit assumes that there is selectedOccupation variable in the component. Using [(ngModel)] creates a two way binding between the value of the <select> element in the html (which will be whatever option is selected at the time) and the value of the selectedOccupation variable in the component. In other words, if the user selects "foo" from the select menu in the html, the value of the selectedOccupation variable in the component will be changed to "foo" (and changes from within the component will be reflected in the html). I'm not going to walk through the rest of it as that isn't pertinent to the question, but the basic gist of the remaining code is that it will list each of the occupations as options in the select statement. Working Code To get your code working, you would just need to change the html to: <fieldset class="one-quarter sm-padding"> <label>Occupation</label> <select name="occupations" [(ngModel)]="selectedOccupation" (ngModelChange)="showValuePromptText('Occupation', $event)"> <option *ngFor="let occupation of occupations" [value]="occupation"> {{occupation}} </option> </select> where selectedOccupation is a string variable that exists in the component. I just changed [(ngModel)]="occupations" to [(ngModel)]="selectedOccupation".
[ "serverfault", "0000494560.txt" ]
Q: Is it possible to automatically restart crashed services in Linux? I am Using Ubuntu Server and would like to know if it's possible to automatically restart services that go unresponsive. I am operating a standard LAMP stack and occasionally vital services need to be restarted but I want to do it in a programmatic way. A: To handle services that go into a crashed state, look at Munin and/or the Linux watchdog daemon.
[ "stackoverflow", "0051603901.txt" ]
Q: Best way to slpit(',') indefinite string length and assign elements to variables What would be the best way to assign each element into to a variable, if the length of 'myext' is unknown? I have four assigned variables, but what if I had a 5th ext in 'myext'? def check_files(mydir, myext, name): extensions = myext.split(',') check1 = mydir + extensions[0] check2 = mydir + extensions[1] check3 = mydir + extensions[2] check4 = mydir + extensions[3] Output1 = glob.glob(check1) Output2 = glob.glob(check2) Output3 = glob.glob(check3) Output4 = glob.glob(check4) check_files('path', '*.pdf,*.xml,*.sff,*.idx', 'Test 1') A: You can use some list comprehensions to iterate over the whole of extensions. checks = [mydir+extension for extension in extensions] outputs = [glob.glob(check) for check in checks]
[ "ell.stackexchange", "0000207869.txt" ]
Q: Is there a verb to convey the meaning of memorizing too much? Is there a verb to use for expressing memorizing something too much to the extent that the speaker wouldn't be concentrating on what s/he is actually saying, so the words would come out as meaningless to him/her. It may appear as a positive or negative thing depending on the situation. We have it in Arabic "بَصَمَ" (pronounced as Basama), it is in its past simple form. Example: He _______ (memorized) his section after getting rebuked by his teacher. The word would fill the blank instead of "memorized". A: You might find "over-rehearsed" is close, but it's only negative: it doesn't mean the speaker doesn't understand the words, only that they are spoken in such a dull way it seems insincere. You can use it like this: He over-rehearsed his answer and didn't sound convincing at all. He had over-rehearsed his speech and there was no passion in his voice. This also applies literally to musicians or actors. The effect of seeing or saying a word until it's meaningless is called "semantic satiation", but that would only ever be used in an academic context. Wikipedia For a positive description: He worked so hard he knew it by heart He worked so hard he knew it backwards
[ "english.stackexchange", "0000451304.txt" ]
Q: Difference in usage of 'explanative' and 'explanatory' I found myself using 'explanative' recently, then had to double-check that it's actually a word. The dictionary lists 'explanative' as an alternative of 'explanatory', but is there a reason to prefer one or the other in specific circumstances? A: Most everywhere I look suggests that they are interchangable, though explanatory holds a massive preference. Ngrams suggest that the most favorable situation for "explanative" was in 1751 when it was used 1/25th as often as "explanatory." If you worry about using words that make others think twice, use explanatory. If you tend to be less trepid, you may want to use each and appropriately. Therefore, let's examine the meaning of the words by considering their suffixes. According to Merriam Webster (there is some slight variation amongst references) the suffixes are very similar. The suffix -ative implies: relating to or connected with something designed to do something tending to do something Whereas the suffix -atory implies: of, belonging to, or connected with serving or tending to The only difference I see is that -ative includes the facet of being designed to do something. So, if we were going to split hairs, Then this explanative sentence could belong to the explanation or be designed to explain the difference. Whereas this explanatory sentence cannot be designed to explain the difference and must only tend to explain the difference, though either sentence can belong to or be connected to this explanation. Consider also the other words which carry each suffix; Words ending in -atory versus words ending in -ative. IMHO, the difference is that most of the atory words describe something which is happening (E.G. potatory, observatory, salutatory) whereas most of the ative words describe the way a thing is (E.G. authoritative, putative, backative) I must admit, however, that some reverse the trend (E.G. explorative or derogatory)
[ "stackoverflow", "0014637874.txt" ]
Q: Change element from main page On my https://getsatisfaction.com/gsfnmichelle/products page, there's a bread crumb trail that says "Products." I'm trying to change that to "Categories." I can get it to do that within the inspector, but when I put the code in the customization script (which is only the main page /gsfnmichelle on the platform I'm using), it doesn't work. Even though I was able to get the correct element (jQuery('.crumb_link span');) and change it using ( jQuery('.crumb_link span').text('Categories');), I can't figure out how to change it when it's within another page (/products) besides the main one (/gsfnmichelle), since it's the only place where we can insert customization code. I thought something like this would check for the page and change that element, but it doesn't work: jQuery(document).ready(function () { if (window.location.pathname =="/gsfnmichelle/products") { jQuery('.crumb_link span').text('Categories');} }; Then I tried to use an if statement to check for the right element, but that doesn't work either: jQuery(document).ready(function () { if (jQuery('.crumb_link span').text =='Products') { jQuery('.crumb_link span').text('Categories');} }; What am I missing? A: You probably want to use either if (jQuery('.crumb_link span').text() == "Products") or jQuery('.crumb_link span:contains(Products)').text('Categories'). Your current condition will never be true.
[ "stackoverflow", "0026470018.txt" ]
Q: JPA best way to validate unique constraint Hi I'm new to JPA and I want to validate a unique constraint, thought before making the insert to the persistence context, do a select to see if the data already exists, if not, return a boolean to proceed with the transaction .. is this a good alternative? Thank you very much. A: If you think you need to check first against the database then it'll work. Typically however, the reason you use a unique constraint is that you don't expect to have duplicates, so you wouldn't waste time checking, just be sure that you are aware when the error condition happens so you can figure out what went wrong. If you actually expect to have the same value many times but want singletons in the database, then you're asking a design question and perhaps should try programmers.stackoverflow.com.
[ "codereview.stackexchange", "0000011819.txt" ]
Q: Is this violating the DRY principle? I feel that I am repeating myself a lot with this HTML/PHP code. Am I right, and is there a maintainable way of reducing the amount of repetition in the code? mydomain/index.php: <!DOCTYPE HTML> <?php $root="/mywebdir"; ?> <html> <head> <?php include("$root/inc/meta.php"); ?> <meta name="description" content="Some description" /> <meta name="keywords" content="some,home,page,keywords" /> <title>Home - This Website</title> </head> <body> <div id="main"> <?php include("$root/inc/header.php"); ?> <?php include("$root/inc/nav.php"); ?> <div> <h2>Home</h2> <p>Introduction.</p> <p>Some content.</p> <p>More content.</p> </div> <?php include("$root/inc/footer.php"); ?> </div> </body> </html> mydomain/somedir/index.php: <!DOCTYPE HTML> <?php $root="/mywebdir"; ?> <html> <head> <?php include("$root/inc/meta.php"); ?> <meta name="description" content="Some description" /> <meta name="keywords" content="some,keywords,about,this,page" /> <title>Some Page - This Website</title> </head> <body> <div id="main"> <?php include("$root/inc/header.php"); ?> <?php include("$root/inc/nav.php"); ?> <div> <h2>Some Page</h2> <p>Some content about this page.</p> </div> <?php include("$root/inc/footer.php"); ?> </div> </body> </html> A: Consider using existing template systems to help you that support inheritance. Template inheritance isn't a strict requirement, but is a powerful feature that makes maintaining templates a lot easier. Twig is easy to use, and feature-rich. If you want to go it your own way, you could simply implement the use of layout files: layout_default.php <!DOCTYPE HTML> <?php $root="/mywebdir"; ?> <html> <head> <?php include("$root/inc/meta.php"); ?> <meta name="description" content="<?php echo $description ?>" /> <meta name="keywords" content="<?php echo keywords?>" /> <title><?php echo $title ?></title> </head> <body> <div id="main"> <?php include("$root/inc/header.php"); ?> <?php include("$root/inc/nav.php"); ?> <div><?php echo $contents ?></div> <?php include("$root/inc/footer.php"); ?> </div> </body> </html> example page.php <?php ob_start() ?> <p> main body html</p> <?php $title = "x"; $description = "x"; $keywords = "x"; $contents = ob_get_clean(); require 'layout_default.php' This is a very crude implementation, simply enough to illustrate the principle.
[ "stackoverflow", "0026639003.txt" ]
Q: Python - Unpivot data Looking for a python solution. Need assistance in unpivoting a data frame in python. The structure is a little funky for a basic pivot function for how I'd like to reshape it. CURRENT DATA FRAME - Here's what I have ABC Mechanical Standard 15-Day 10-Day 5-Day Terminal Units 0.49 0.75 0.69 0.63 Diffusers 0.35 0.55 0.45 0.4 Vent 0.8 0.95 0.9 0.85 Piping 0.7 0.85 0.8 0.75 Stoves 0.6 0.8 0.75 0.7 UNPIVOTED DATA FRAME - Here's how I want to reshape it df.columns= Customer, Product Category, Ship Cycle, Multiplier df.index= ABC Mechanical Customer Product Category Ship Cycle Multiplier ABC Mechanical Terminal Units Standard 0.49 ABC Mechanical Terminal Units 15-Day 0.75 ABC Mechanical Terminal Units 10-Day 0.69 ABC Mechanical Terminal Units 5-Day 0.63 ABC Mechanical Diffusers Standard 0.35 ABC Mechanical Diffusers 15-Day 0.55 ABC Mechanical Diffusers 10-Day 0.45 ABC Mechanical Diffusers 5-Day 0.4 Any assistance is much appreciated! Thanks! A: If df looks like this: In [26]: df Out[26]: Standard 15-Day 10-Day 5-Day Terminal Units 0.49 0.75 0.69 0.63 Diffusers 0.35 0.55 0.45 0.40 Vent 0.80 0.95 0.90 0.85 Piping 0.70 0.85 0.80 0.75 Stoves 0.60 0.80 0.75 0.70 then pd.melt gets you close to the desired DataFrame: In [27]: pd.melt(df.reset_index(), id_vars=['index']).sort_values(by=['index']) Out[27]: index variable value 1 Diffusers Standard 0.35 6 Diffusers 15-Day 0.55 11 Diffusers 10-Day 0.45 16 Diffusers 5-Day 0.40 3 Piping Standard 0.70 8 Piping 15-Day 0.85 13 Piping 10-Day 0.80 18 Piping 5-Day 0.75 4 Stoves Standard 0.60 9 Stoves 15-Day 0.80 14 Stoves 10-Day 0.75 19 Stoves 5-Day 0.70 0 Terminal Units Standard 0.49 5 Terminal Units 15-Day 0.75 10 Terminal Units 10-Day 0.69 15 Terminal Units 5-Day 0.63 2 Vent Standard 0.80 7 Vent 15-Day 0.95 12 Vent 10-Day 0.90 17 Vent 5-Day 0.85 I don't understand where "ABC Mechanical" is in the original DataFrame, so I haven't attempted to include it in the result. The column names can renamed like this: In [28]: df = pd.melt(df.reset_index(), id_vars=['index']).sort_values(by=['index']) In [29]: df.columns = ['Product Category', 'Ship Cycle', 'Multiplier'] In [31]: df.head() Out[31]: Product Category Ship Cycle Multiplier 1 Diffusers Standard 0.35 6 Diffusers 15-Day 0.55 11 Diffusers 10-Day 0.45 16 Diffusers 5-Day 0.40 3 Piping Standard 0.70
[ "ru.stackoverflow", "0001037184.txt" ]
Q: Изменение макета HTML пс помощью PHP Всем добра! Есть анкета на bootstrap, которая на сервер AJAX'ом отправляет всё своё содержимое, Это содержимое, нужно рассовать по местам в файле, назовем его "anketa.html". Файл этот просто лежит на сервере, и открывается только для изменения, и последующего превращения его в pdf, всем известными методами. Так вот вопрос, как рассовать содержимое? Кусок кода ankete.html <div> <div style="display: inline-block;width: 100%;border: 1px solid;border-top: none;"> <div style="width:25%;display: inline-block;border-right: 1px solid;"> <label style="margin-left:10px">1.1. Given names / Имена</label> </div> <div style=" width:74%; display: inline-block;"> <label style="margin-left:10px" id="given-names"></label> </div> </div> <div style=" display: inline-block; width: 100%; border: 1px solid; border-top: none;"> <div style="width:25%; display: inline-block; border-right: 1px solid;"> <label style="margin-left:10px">1.2. Surname / Фамилия</label> </div> <div style=" width:74%; display: inline-block;"> <label style="margin-left:10px" id="surname"></label> </div> </div> <div style=" display: inline-block; width: 100%; border: 1px solid; border-top: none;"> <div style=" width:25%; display: inline-block; border-right: 1px solid;"> <label style="margin-left:10px">1.3. Date of birth / Дата рождения</label> </div> <div style=" width:74%; display: inline-block;"> <label style="margin-left:10px" id="date-of-birth"></label> </div> </div> <div style=" display: inline-block; width: 100%; border: 1px solid; border-top: none;"> <div style=" width:25%; display: inline-block; border-right: 1px solid;"> <label style="margin-left:10px">1.4. Place of birth / Место рождения</label> </div> <div style=" width:74%; display: inline-block;"> <label style="margin-left:10px" id="place-of-birth"></label> </div> </div> <div style="display: inline-block; width: 100%; border: 1px solid; border-top: none;"> <div style=" width:25%; display: inline-block; border-right: 1px solid;"> <label style="margin-left:10px">1.5. Citizenship / Гражданство </label> </div> <div style=" width:74%; display: inline-block;"> <label style="margin-left:10px" id="citizenship"></label> </div> </div> <div style=" display: inline-block; width: 100%; border: 1px solid; border-top: none;"> <div style=" width:25%; display: inline-block; border-right: 1px solid;"> <label style="margin-left:10px">1.6. Sex / Пол</label> </div> <div style=" width:74%; display: inline-block;"> <label style="margin-left:10px" id="sex"></label> </div> </div> <div style=" display: inline-block; width: 100%; border: 1px solid; border-top: none;"> <div style=" width:25%; display: inline-block;border-right: 1px solid;"> <label style="margin-left:10px">1.7. Passport No. / Номер паспорта </label> </div> <div style=" width:74%; display: inline-block;"> <label style="margin-left:10px" id="passport-num"></label> </div> </div> <div style=" display: inline-block; width: 100%; border: 1px solid; border-top: none;"> <div style=" width:25%; display: inline-block; border-right: 1px solid;"> <label style="margin-left:10px">1.8. Date of issue / Дата выдачи</label> </div> <div style=" width:24%; display: inline-block;"> <label style="margin-left:10px" id="date-of-issue"></label> </div> <div style=" width:25%; display: inline-block; border-right: 1px solid; border-left: 1px solid;"> <label style="margin-left:10px">1.9. Date of expiry / Дата окончания срока</label> </div> <div style=" width:24%; display: inline-block;"> <label style="margin-left:10px" id="date-of-expiry"></label> </div> </div> </div> Кусок получаемых AJAX'ом данных Array ( [given-names] => [surname] => [date-of-birth] => 10/22/2019 [place-of-birth] => [citizenship] => RU [passport-num] => [issue-date] => 10/22/2019 [expiry-date] => 10/22/2019 ) Если что данные стоковые A: Если я правильно понял вопрос: 1) Надо сохранить html-файл как ankete.php; 2) В начало <body> вставить <? ваш php-скрипт обработчик AJAX-запроса ?>; 3) AJAX-запрос должен вызывать ankete.php (либо ankete.php надо вызвать и передать в него данные любым способом: через другой скрипт/из базы, и.т.д.); 4) Прописать php-вставки значений в html, используя конструкцию <?= ?>, аналог echo. <label style="margin-left:10px"><?=$_POST['given-names']?></label> На выходе будет html-страница с полученными из запроса значениям, без php-кода.
[ "serverfault", "0000604229.txt" ]
Q: How to get atop to create daily logfile I'm running a website on a VPS running Centos 6.5 and am having some issues. I'm new to serveradmin so just learning. atop was already installed on our machine and it's working. I wanted to go in and analyse the historical logs but there is nothing in /var/log/atop/, the atop directory is there but is empty. I thought that it's configured to create logs by default? The man pages are here: http://linux.die.net/man/1/atop I changed the cron -> /etc/cron.d/atop from 0 0 * * * root /etc/rc.d/init.d/atop condrestart > /dev/null 2>&1 || : to 0 0 * * * root /etc/atop/atop.daily Should this get the log file working? Any pointers would really help. I'm looking to see if my cpu usage is going crazy at a certain point or I'm running out of RAM which is why i'm using atop. Thanks. A: Put /etc/cron.d/atop back to 0 0 * * * root /etc/rc.d/init.d/atop condrestart > /dev/null 2>&1 || : Run chkconfig atop on service atop start
[ "stackoverflow", "0004564273.txt" ]
Q: C++ -- Which one is supposed to use "new Car" or "new Car()"? Possible Duplicate: Do the parentheses after the type name make a difference with new? Hello all, class Car { public: Car() : m_iPrice(0) {} Car(int iPrice) : m_iPrice(iPrice) {} private: int m_iPrice; }; int _tmain(int argc, _TCHAR* argv[]) { Car car1; // Line 1 Car car2(); // Line 2, this statement declares a function instead. Car* pCar = new Car; // Line 3 Car* pCar2 = new Car(); // Line 4 return 0; } Here is my question: When we define an object of Car, we should use Line 1 rather than Line 2. When we new an object, both Line 3 and Line 4 can pass the compiler of VC8.0. However, what is the better way Line 3 or Line 4? Or, Line 3 is equal to Line 4. Thank you A: In this case the lines are equivalent; there's no difference in operation. However, please be careful - this does not mean that such lines are ALWAYS equialent. If your data type is a POD (i.e. a simple struct: struct Foo { int a; float b; }; Then new Foo produces a uninitialized object, and new Foo() calls a value initalization constructor, which value-initializes all fields - i.e. sets them to 0 in this case. Since in such cases it's easy to accidentally call new Foo(), forget to initialize objects (this is fine!), and then accidentally make your class non-POD (in which case the value-initialization will not be done and the object will be uninitialized again), it's slightly better to always call new Foo (though this produces a warning in some MSVC versions).
[ "travel.stackexchange", "0000002539.txt" ]
Q: How to avoid drinking vodka? This summer, I spent some time in Moscow and St. Petersburg; I also visited a friend and his family. Their custom was to drink a lot of vodka during the meal. We, the guests, also had to drink some vodka; but obviously we'd had enough before our Russian friends. ;) But it was very difficult for us to convince them that it would be unwise for us to drink more vodka. I think, in fact, that we slightly offended them. If I'm invited to a meal with my hosts, how can I avoid drinking a lot of vodka without offending them? I think it wouldn't be too difficult if I didn't drink at all. Then I could say that I don't drink for religious or medical reasons. But what excuse could I use if I've already started drinking and want to stop? A: In Bulgaria, Russia, former USSR countries and others, it's considered offensive not to drink when you've been invited to, and you might need a good solid excuse if you decide not to drink at all. Expect to be on the receiving end of some good-natured banter if you decide to abstain completely. Medical reasons are a possibility, although it will be difficult to refuse to drink at least once with your hosts, regardless of your (supposed or actual) ailment. But if you decide to drink with the best of them, then you are expected to do so each and every time a toast is raised -- which can get you down pretty quickly if you are not a serious drinker. What you can do is just pretend to drink from your glass after every toast -- you don't have to shove the whole 100 g down your throat every time. Just take a little sip (maybe a little bit more in the beginning), and after the first few rounds the hosts and their guests will be in too cheerful a mood to notice you're not keeping up volume-wise. Your glass will be helpfully refilled by someone sitting close to you when getting below one-third or so, so just don't empty it as quickly. There's always more where that came from. There's a whole culture of proper drinking in Eastern Europe, so here are some generic drinking tips that will help you a lot if you are drinking only occasionally: Don't drink too fast, even if you don't feel you're getting drunk -- you will, and it will happen without warning. Take it easy Drink water. I can't stress this enough. As much as possible, really, and all the time -- but not fizzy drinks. You'll be able to keep up with your hosts longer, and largely avoid that pesky hangover in the morning, which is caused by dehydration. Excuse yourself (temporarily). If you feel you're getting in trouble, skimp on the vodka for some time. If asked, explain you are feeling a little bit dizzy, and want to take a break for a while so that you can resume drinking later. Everybody will most likely smile in understanding, and won't press you to drink for some time. Use the grace period to restock on dehydrants and food, because it won't last forever. Eat. Traditional Russian dishes that go with vodka are there to prevent you from getting drunk quickly. Pickles, smoked salmon, fatty meats -- they all help. Be sure to have something in your stomach before you start drinking, and keep up at a steady rate throughout the evening. Talk. Engage in a conversation with your neighbours on the table. If it's interesting enough, they'll forget to sip and toast as often. If conversations are not going well, there's not much to do on the table besides drinking -- and that's bad news for you. Good luck, and Наздраве! A: I was in the unfortunate position of being insistingly encouraged to drink 3 years ago on the Trans-Siberian. I was much worse for wear after that experience, and sought out suggestions (in fact I really shouldn't have had that much considering my meds). Anyway, this year I returned. And indeed, the best way if you can't just refuse outright, is simply to touch the glass to your lips. Don't neck the whole thing, just a touch is all they're looking for - and in fact I noticed other Russians doing the same thing. It's the social process - the common bonding of a group, done easily with a drink. It's not about how much you drink, more that you're joining in. So touch it to your lips, maybe even take a couple of sips every so often if you'd like to, but don't feel compelled to finish it. And even if they do notice, at the worst take a sip when they point it out and continue - they'll soon forget :) Enjoy it, it's a great way to meet the locals, and it's possible to do so without being floored! Excuse: And if you really are being pressured and don't want to continue, there's nothing wrong with (as I did) pointing out that you can have a little, but too much will be bad. Even without the language skills, pointing to my drink and pointing to my heart and making bad faces got the message across, they actually looked a little guilty for a few seconds before continuing to have fun ;) A: As a Russian and non-drinker, I want to add some info about the culture of drinking in Russia. First of all: You don't have to drink vodka, even if your partners are. It is ok if you just say: I can't drink alcohol as strong as vodka, I need wine (or cocktails, or whatever you need). Ask women about this - they're more reliable in such situations. But if you choose wine, make sure that it is not home-made - this can contain even more alcohol than in vodka :) Second: as @yevhene said, you can drink less volume, even if you have a whole cup in your hands. But get ready for some jokes about it. Tips while drinking: Eat after each toast, and eat a lot! - potato, butter and bread are your best friends. The homeowners will be pleased with your appetite. Get ready to say a toast yourself - especially the last one you are going to drink (this is called "ещё по одной, и всё" - another one, and that's all, or на посошок - farewell) It is OK to say: stop, it is enough for me! If this happens too early, you'll get another portion as a joke, but in general your partners will understand this decision. Try to get up and walk sometimes - this can help to skip some portion of the alcohol, and also you'll understand how drunk you are. If you drink some non-strong alcohol, you can switch to vodka, but don't lower the Alcohol proof! Tips for after the party, but before bed: Drink water! A lot of water! The more you'll drink, the easier your morning will be. Try to get outside some 5-10 minutes - this will refresh you.
[ "stackoverflow", "0010066105.txt" ]
Q: jwplayer not working I've downloaded the files and followed the steps provided but the player simply isn't working. <code> <html> <head> <script type="text/javascript" src="/jwplayer.js"></script> <script type="text/javascript" src="/jquery.js"></script> </head> <body> <div id="container">Loading the player ...</div> <script type="text/javascript"> jwplayer("container").setup({ flashplayer: "/player.swf", file: "/video.mp4", height: 270, width: 480 }); </script> </body> </html> </code> All it shows is "Loading the Player." As you can see I've linked the JWplayer and jquery scripts. What am I missing? Any help would be greatly appreciated. I use web expressions... when I try to follow the jwplayer link "jwplayer(container)," i says that a link could not be found. A: Try this code. With relative address, it works for me! I hope this will help you. <!DOCTYPE html> <html> <head> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jplayer/2.9.2/jplayer/jquery.jplayer.min.js"></script> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js/jquery.js"></script> </head> <body> <div id="container">Loading the player ...</div> <script type="text/javascript"> jwplayer("container").setup({ flashplayer: "//cdnjs.cloudflare.com/ajax/libs/jplayer/2.9.2/jplayer/jquery.jplayer.swf", file: "http://content.bitsontherun.com/videos/lWMJeVvV-364767.mp4", height: 270, width: 480 }); </script> </body> </html> A: Just get rid of the / in your code so that it reads as follows: flashplayer: "player.swf"
[ "es.stackoverflow", "0000015442.txt" ]
Q: ¿Cómo hacer que un filtro css aplique solamente al background y no a los elementos hijos? Tengo una serie de imagenes que se muestran en escala de gris cuando el elemento tiene la clase disabled pero dicho filtro me está aplicando también a los elementos hijos por lo que el bloque completo me aparece en gris. .item { background-size: cover; width: 400px; height: 200px; text-align: center; padding-top: 20px; } .item.disabled { filter: grayscale(100%); -webkit-filter: grayscale(100%); } .item .status { background-color: green; bottom: 30px; border-radius: 6px; padding: 2px 5px; color: white; font-weight: bold; } .item.disabled .status { background-color: red; } <div class="item" style="background-image: url(http://lorempixel.com/400/200/sports)"> <span class="status">ready</span> </div> <div class="item disabled" style="background-image: url(http://lorempixel.com/400/200/sports)"> <span class="status">not ready</span> </div> ¿Como hacer para que el texto que dice "not ready" me salga en rojo y no en gris? Segun tengo entendido la propiedad css filter no es heredable y su valor inicial es none así que sólo debería aplicar al elemento sobre el que se encuentra. A: A mi me había ocurrido esto hace tiempo, pero con el filter: blur, la solución esta en jugar con las posiciones de las cajas. .item { background-size: cover; width: 400px; height: 200px; text-align: center; padding-top: 20px; } .item.disabled { position: relative; } .item .status { background-color: green; bottom: 30px; border-radius: 6px; padding: 2px 5px; color: white; font-weight: bold; } .item.disabled .status { background-color: red; } .no-bw{ top: 30px; display: block; position: absolute; background-color: red; border-radius: 6px; padding: 2px 5px; color: white; font-weight: bold; left:50%; width: 76px; /*LA MITAD DEL ANCHO DE LA CAJA*/ margin-left: -38px; } .fondo-bw{ -webkit-filter: grayscale(100%); filter: grayscale(100%); } <div class="item" style="background-image: url(http://lorempixel.com/400/200/sports)"> <span class="status">ready</span> </div> <div class="item disabled" style=""> <div class="fondo-bw item" style="background-image: url(http://lorempixel.com/400/200/sports)"></div> <span class="no-bw">not ready</span> </div>
[ "askubuntu", "0000624102.txt" ]
Q: Search specific word inside document using ssh Currently i have to analize some big files looking for a espefic word in .css located on my /var/www/ located on ubuntu server (ssh). There a way to make something like Ctrl+f in windows programatically in ubuntu to search the words ? Or just i have to use some ftp tool to download my file in windows and looking for there ? A: When you are connected via ssh there are many commands you can use. You could use grep searchString /var/www/file.css/ to display all occurrences of searchString. Or you could display the file with less /var/www/file.css then press / and type the word you are searching for. Press enter to jump to the first occurrence of the word and n to cycle through the other ones step by step.
[ "stackoverflow", "0053684225.txt" ]
Q: Set Variable Offsets Based on Empty Cell Location I am trying to set up "x" and "y" as vaiable integers where "x" will take the place of 9 and "y" will take the place of 10 in the offset locations listed below. "x" and "y" will need to change value based on where the first blank cell in the Row corresponding to "t" is. So if column 9 of the worksheet is blank "x" will equal 9 and "y" will equal 10 and if column 7 is blank "x" will equal 7 and "y" will equal 8 and so on. I am not really sure where to begin on this one. Any help is appreciated! Sub FindRow1() Dim t As Range Dim c As Range Dim d As Range Dim e As Range Dim f As Range Dim g As Range Dim h As Range Dim i As Range Dim j As Range Dim k As Range Dim l As Range Dim m As Range Dim n As Range Dim o As Range Dim p As Range Dim x As Integer Dim y As Integer With Worksheets("Recap Sheet").Cells Set t = .Find("Year of Tax Return", After:=.Range("A1"), LookIn:=xlValues).Cells Set c = .Find("12. Total Gross Annual Cash Flow", After:=.Range("A1"), LookIn:=xlValues).Cells Set d = .Find("15. Total Annual Cash Flow Available to Service Debt", After:=.Range("A1"), LookIn:=xlValues) Set e = Range(t.Offset(1, 0), c.Offset(-1, 0)) Set f = Range(c.Offset(1, 0), d.Offset(-1, 0)) Set i = Range(t.Offset(1, 9), c.Offset(-1, 9)) Set j = Range(c.Offset(1, 9), d.Offset(-1, 9)) Set k = Range(t.Offset(-1, 9), d.Offset(0, 10)) Set l = Range(t.Offset(1, 9), d.Offset(0, 9)) Set m = Range(t.Offset(1, 10), d.Offset(0, 10)) Set n = Range(d.Offset(0, 9), d.Offset(0, 10)) Set o = Range(c.Offset(0, 9), c.Offset(0, 10)) Set p = Range(t.Offset(0, 9), t.Offset(0, 10)) Set g = c.Offset(0, 9).Cells Set h = d.Offset(0, 9).Cells A: Do you mean this? When using Find you should check you've found something before proceeding to avoid an error. Also, I would suggest giving your variables more meaningful names, particularly as you have so many. Could get confusing. Sub z() Dim t As Range, x As Long, y As Long, n As Long With Worksheets("Recap Sheet").Cells Set t = .Find("Year of Tax Return", After:=.Range("A1"), LookIn:=xlValues) If Not t Is Nothing Then n = t.EntireRow.SpecialCells(xlCellTypeBlanks)(1).Column x = n y = n + 1 End If End With End Sub
[ "stackoverflow", "0057999748.txt" ]
Q: How do I find the 2nd most recent order of a customer I have the customers first order date and last order date by doing MIN and MAX on the created_at field (grouping by email), but I also need to get the customers 2nd most recent order date (the order date right before the last orderdate ) SELECT customer_email, COUNT(entity_id) AS NumberOfOrders, MIN(CONVERT_TZ(created_at,'UTC','US/Mountain')) AS 'FirstOrder', MAX(CONVERT_TZ(created_at,'UTC','US/Mountain')) AS 'MostRecentOrder', SUM(grand_total) AS TotalRevenue, SUM(discount_amount) AS TotalDiscount FROM sales_flat_order WHERE customer_email IS NOT NULL AND store_id = 1 GROUP BY customer_email LIMIT 500000 A: Use window function ROW_NUMBER() (available in MySQL 8.0): SELECT * FROM ( SELECT t.*, ROW_NUMBER() OVER(PARTITION BY customer_email ORDER BY created_at) rn_asc, ROW_NUMBER() OVER(PARTITION BY customer_email ORDER BY created_at DESC) rn_desc FROM sales_flat_order WHERE customer_email IS NOT NULL AND store_id = 1 ) x WHERE rn_asc = 1 OR rn_desc <= 2 This will get you the earlierst and the two latest orders placed by each customer. Note: it is unclear what the timezone conversions are intended for. I left them apart, since they obviously do not affect the sorting order; feel free to add them as per your use case. If you want a single record per customer, along with its total count of orders, and the date of his first, last, and last but one order, then you can aggregate in the outer query: SELECT customer_email, NumberOfOrders, MAX(CASE WHEN rn_asc = 1 THEN created_at END) FirstOrder, MAX(CASE WHEN rn_desc = 1 THEN created_at END) MostRecentOrder, MAX(CASE WHEN rn_desc = 2 THEN created_at END) MostRecentButOneOrder, TotalRevenue, TotalDiscount FROM ( SELECT customer_email, created_at, COUNT(*) OVER(PARTITION BY customer_email) NumberOfOrders, SUM(grand_total) OVER(PARTITION BY customer_email) TotalRevenue, SUM(discount_amount) OVER(PARTITION BY customer_email) TotalDiscount, ROW_NUMBER() OVER(PARTITION BY customer_email ORDER BY created_at) rn_asc, ROW_NUMBER() OVER(PARTITION BY customer_email ORDER BY created_at DESC) rn_desc FROM sales_flat_order WHERE customer_email IS NOT NULL AND store_id = 1 ) x GROUP BY customer_email
[ "stackoverflow", "0005940427.txt" ]
Q: Install multiple versions of Eclipse in the same place I have downloaded Eclipse Javascript and Eclipse PDT. Now I want to install them in one place, because I want to get both features in one place. How can I do this? I know one way is to install (unpack) one of the above and add the other via Install New Software on the help menu, but I can't do online installation due to my internet connection constraints. I am running Debian 6.0.1a, i386. A: () Unpack both packages to disk () From one of the packages, go to: Help->Install New Software->Add->Local () Browse to the other package, and select the folder: eclipse->p2->profileRegistry-> () Install the software. Alternatively you can use Marketplace client to find and install the plugins from the other package.
[ "stackoverflow", "0016851638.txt" ]
Q: Android kill process How to kill whole application in onne single click.. finish() is not working?? it redirects to tha previous activity...pls guide me. public void onClick(View arg0) { // TODO Auto-generated method stub WallpaperManager wp = WallpaperManager .getInstance(getApplicationContext()); try { Display d = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay(); int width = d.getWidth(); int height = d.getHeight(); wp.setBitmap(b1); } catch (IOException e) { Log.e("error", "Cannot set image as wallpaper", e); } finish(); } A: System.exit() does not kill your app if you have more than one activity on the stack Use android.os.Process.killProcess(android.os.Process.myPid()); this way. for sample public void onBackPressed() { android.os.Process.killProcess(android.os.Process.myPid()); super.onBackPressed(); } For more detail see Is quitting an application frowned upon? , How to force stop my android application programmatically? I hope this will help you. A: You can use this function to close your application Process.killProcess( Process.myPid() );
[ "stackoverflow", "0012720462.txt" ]
Q: Spider (Radar) chart for iOS Where can I find good spider(radar) chart library for iOS? (as like the below) I checked "Core Plot" and "iOSPlot" open source projects, but these are not supporting spider chart. BR, Wonil. A: Try RP Radar Chart from raspu on Github. Although the author claims it's unfinished it looks pretty solid. https://github.com/raspu/RPRadarChart
[ "stackoverflow", "0052587604.txt" ]
Q: Sqlalchemy query based on excluding items in a relationship I have a table of PartyOrganiser(s), and a table of one's Contact(s) and a table of one's organised Party(s). PartyOrganiser to Party is one-to-many. PartyOrganiser to Contact is one-to-many. Party to Contact is many-to-many, with an association table. class PartyOrganiser(db.Model): __tablename__ = 'party_organiser' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) parties = db.relationship("Party", back_populates='party_organiser') contacts = db.relationship("Contacts", back_populates='party_organiser') contact_party_ass_tab = db.Table('contact_party', db.Model.metadata, db.Column('party_id', db.Integer, db.ForeignKey('party.id')), db.Column('contact_id', db.Integer, db.ForeignKey('contact.id'))) class Party(db.Model): __tablename__ = 'party' id = db.Column(db.Integer, primary_key=True) details = db.Column(db.String) party_organiser_id = db.Column(db.Integer, db.ForeignKey('party_organiser.id'), nullable=False) party_organiser = db.relationship("PartyOrganiser", back_populates="parties", uselist=False) attendees = db.relationship("Contact", secondary=contact_party_ass_tab, back_populates='intended_parties') class Contact(db.Model): __tablename__ = 'contact' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) party_organiser_id = db.Column(db.Integer, db.ForeignKey('party_organiser.id'), nullable=False) party_organiser = db.relationship("PartyOrganiser", back_populates="parties", uselist=False) intended_parties = db.relationship("Contact", secondary=contact_party_ass_tab, back_populates='attendees') Main Question: Grammatically, for a specific party, I want to acquire a list of those contacts associated with the party's organiser that are not already attending the party. I.e. calling them potential_attendees, I would like the following as an SQLalchemy query style solution: class Party(db.model): ... @property def potential_attendees(self): # get all contacts for the right party_organiser sub_query = Contact.query.filter(Contact.party_organiser_id == self.party_organiser_id) # then eliminate those that are already attendees to this party.. return sub_query.difference(self.attendees) # <- pseudocode Sub question: This configuration has an inherent 3 way constraint between PartyOrganiser, Party and Contact: parties and attendees can only be associated if they share a party_organiser. I.e. None of PartyOrganiser1's contacts can be attendees to Party2 organised by PartyOrganiser2. It is not obvious to me that this is constrained as required in the above format. In fact I believe it isn't. How would I implement this constraint? A: You can query for the items which are excluded in a relationship by using the NOT EXISTS construct on a joined table. @property def potential_attendees(self): sq = db.session.query(contact_party_ass_tab.columns.contact_id).subquery() return db.session.query(Contact).filter( Contact.party_organiser_id==self.party_organiser_id, ~exists().where(sq.c.contact_id==Contact.id) ).all() As far as your other question is concerned, you can impose that constraint on the ORM level by adding attribute level validators for Party.attendees and Contact.intended_parties and ensuring that any new item added to those lists has a matching party_organiser_id. Here is the full code from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy import exists from sqlalchemy.orm import validates app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' db = SQLAlchemy(app) class PartyOrganiser(db.Model): __tablename__ = 'party_organiser' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) parties = db.relationship("Party", back_populates='party_organiser') contacts = db.relationship("Contact", back_populates='party_organiser') def __repr__(self): return self.name contact_party_ass_tab = db.Table('contact_party', db.Model.metadata, db.Column('party_id', db.Integer, db.ForeignKey('party.id')), db.Column('contact_id', db.Integer, db.ForeignKey('contact.id'))) class Party(db.Model): __tablename__ = 'party' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) details = db.Column(db.String) party_organiser_id = db.Column(db.Integer, db.ForeignKey('party_organiser.id'), nullable=False) party_organiser = db.relationship("PartyOrganiser", back_populates="parties", uselist=False) attendees = db.relationship("Contact", secondary=contact_party_ass_tab, back_populates='intended_parties') def __repr__(self): return self.name @property def potential_attendees(self): sq = db.session.query(contact_party_ass_tab.columns.contact_id).subquery() return db.session.query(Contact).filter( Contact.party_organiser_id==self.party_organiser_id, ~exists().where(sq.c.contact_id==Contact.id) ).all() @validates('attendees') def validate_attendee(self, key, attendee): assert attendee.party_organiser_id == self.party_organiser_id return attendee class Contact(db.Model): __tablename__ = 'contact' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) party_organiser_id = db.Column(db.Integer, db.ForeignKey('party_organiser.id'), nullable=False) party_organiser = db.relationship("PartyOrganiser", back_populates="contacts", uselist=False) intended_parties = db.relationship("Party", secondary=contact_party_ass_tab, back_populates='attendees') def __repr__(self): return self.name @validates('intended_parties') def validate_party(self, key, party): assert party.party_organiser_id == self.party_organiser_id return party db.create_all() organiser1 = PartyOrganiser(name="organiser1") organiser2 = PartyOrganiser(name="organiser2") db.session.add_all([organiser1, organiser2]) db.session.commit() org1_party1 = Party(name="Organiser1's Party1", party_organiser_id=organiser1.id) org1_party2 = Party(name="Organiser1's Party2", party_organiser_id=organiser1.id) org2_party1 = Party(name="Organiser2's Party1", party_organiser_id=organiser2.id) org2_party2 = Party(name="Organiser2's Party2", party_organiser_id=organiser2.id) db.session.add_all([org1_party1, org1_party2, org2_party1, org2_party2]) db.session.commit() org1_contact1 = Contact(name="Organiser1's contact 1", party_organiser_id=organiser1.id) org1_contact2 = Contact(name="Organiser1's contact 2", party_organiser_id=organiser1.id) org1_contact3 = Contact(name="Organiser1's contact 3", party_organiser_id=organiser1.id) org1_contact4 = Contact(name="Organiser1's contact 4", party_organiser_id=organiser1.id) org2_contact1 = Contact(name="Organiser2's contact 1", party_organiser_id=organiser2.id) org2_contact2 = Contact(name="Organiser2's contact 2", party_organiser_id=organiser2.id) org2_contact3 = Contact(name="Organiser2's contact 3", party_organiser_id=organiser2.id) org2_contact4 = Contact(name="Organiser2's contact 4", party_organiser_id=organiser2.id) db.session.add_all([org1_contact1, org1_contact2, org1_contact3, org1_contact4, org2_contact1, org2_contact2, org2_contact3, org2_contact4]) db.session.commit() org1_party1.attendees.append(org1_contact1) db.session.commit() print "Potential attendees of org1_party1 ", org1_party1.potential_attendees print "Attempting to add a contact of a different organiser. Will throw exception" org1_party1.attendees.append(org2_contact1) Output (Check the exception at the end which is thrown by the last line in above code): In [1]: from exclusion_query import * /home/surya/Envs/inkmonk/local/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py:794: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning. 'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and ' Potential attendees of org1_party1 [Organiser1's contact 2, Organiser1's contact 3, Organiser1's contact 4] Attempting to add a contact of a different organiser. Will throw exception --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) <ipython-input-1-4380704ace46> in <module>() ----> 1 from exclusion_query import *
[ "stackoverflow", "0008616357.txt" ]
Q: dropbox api usage in nodejs "Bad oauth_signature for oauth_signature_method" I have been trying to connect to dropbox server and use the api, but I'm failing at the first step itself. When i'm requesting for the request token, I'm getting Bad oauth_signature error in nodejs. The code that i'm using to connect to api is as follows.(I'm using https://github.com/sintaxi/node-dbox/blob/master/README.md library/sdk for nodejs) /* * dropbox handlers controller. */ var dbox = require('dbox') ,querystring = require("querystring") var client = dbox.createClient({ app_key : 'my-key', // required app_secret : 'my-secret', // required root : 'sandbox' // optional (defaults to sandbox) }) exports.index = function(req, res){ client.request_token(function(status, reply){ console.log(status) console.log(reply) // { // oauth_token : "h89r0sdfdsfwiko", // required // oauth_token_secret : "8hielfflk7100mv", // required // } }) the result i'm getting in my console is as follows c:\tmp\dropbox>node app.js Express server listening on port 3000 in development mode oauth_consumer_key=[my key]&oauth_signature=faawn09ehmfe25i%2526&oauth_ti mestamp=1324643574&oauth_nonce=132464357437334176&oauth_signature_method=PLAINTE XT&oauth_version=1.0 403 { '{"error": "Bad oauth_signature for oauth_signature_method \'PLAINTEXT\'"}': u ndefined } Any help on this is greatly appreciated. Thanks in advance A: This is the author of node-dbox. This issue has been resolved as of version 0.2.2. Sorry for the trouble.
[ "stackoverflow", "0052121938.txt" ]
Q: Renaming SOME columns in pandas I have a csv file which I get as a report and it's header looks like this: ln;7,26;7,27;7,28;7,29;7,3;7,31;8,01;8,02;8,03;8,04;8,05;8,06;8,07;8,08;8,09;name The numbers are supposed to be dates (so 7,29 is July 29, 7,3 is July 30). How can I convert these to actual date format if I'm using pandas? Since it's from a report, I'd need a way to format them daily automatically. Thanks in advance! A: Let's try pd.to_datetime: pd.to_datetime(df.columns[1:-1] + ',2018', format='%m,%d,%Y') DatetimeIndex(['2018-07-26', '2018-07-27', '2018-07-28', '2018-07-29', '2018-07-03', '2018-07-31', '2018-08-01', '2018-08-02', '2018-08-03', '2018-08-04', '2018-08-05', '2018-08-06', '2018-08-07', '2018-08-08', '2018-08-09'], dtype='datetime64[ns]', freq=None) Just assign the result back: c = df.columns.tolist() c[1:-1] = pd.to_datetime(df.columns[1:-1] + ',2018', format='%m,%d,%Y') df.columns = c Unfortunately, the temp list is needed because pd.Index does not support mutable operations.
[ "stackoverflow", "0046442189.txt" ]
Q: jQuery Default Validation Error appearing inside an input-box I've got this form. I've added the jQuery validation plugin on the form but whenever the validation error occurs it displays inside the input box. Here's the html code snippet. I want the error to appear below the email box like it is happening for password box. The <div id="emailInputGroup"> is causing the problem but if I remove it I loose the input-group-addon. <div id="loginFormGroup" class="form-group"> <label for="emailLabel" style="color:white"><strong>Email ID</strong></label> <div id="emailInputGroup" class="input-group"> <input name="email" type="email" class="form-control" placeholder="abc" autofocus></input> <span class="input-group-addon">@abc.org</span> </div> </div> <div class="form-group"> <label for="passwordLabel" style="color:white"><strong>Password</strong></label> <input name="password" type="password" class="form-control" placeholder="password" /> </div> Here's the screenshot: I'm a beginner in web-development, so kindly bear with me if it appears to be a trivial question. Thank you. This is the jQuery code: $(document).ready( function(){ $.validator.addMethod("customValidator", function(value, element) { return /^[a-zA-Z]+$/.test(value); }, 'No special char2'); $("#signIn").click( function(){ $("#loginForm").valid(); //default }); $("#loginForm").validate({ rules: { email: { required: true, minLength: 3, maxLength: 10, customValidator: true }, password: { required: true, minLength: 4, maxLength: 32 } }, message: { email: { required: "email can't be empty", minLength: "At least 3 email characters.", maxLength: "At most 10 email characters." }, password: { required: "password can't be empty", minLenght: "At least 4 password characters", maxLength: "At most 32 password characters" } } }); }); I don't know if it is even syntactically correct or not. A: You can use errorPlacement to customize where you want to place your errors in jQuery Validate $("#loginForm").validate({ rules: { .......... }, message: { .......... }, errorPlacement: function(error, element) { // if the element is email, then append the error to its parent. // which means the error will be rendered below the span if (element.attr("name") == "email") { error.appendTo(element.closest('div')); } else { error.insertAfter(element); // this is the default behaviour } } }); Here's a fiddle
[ "superuser", "0001361171.txt" ]
Q: Pipe stderr to file and screen without redirecting stderr to stdout In a bash script I'd like to execute a command while piping the stderr to both a file and to the terminal. However, I want stderr to stay on the '2' file descriptor so that I can parse it from an external process that is calling this bash script. All the solutions I've seen so far involve swapping stdout with stderr and then tee'ing to another file, for example: find /var/log 3>&1 1>&2 2>&3 | foo.file If I am to call this script from another one, the stderr will go to stdout and stdout will go to stderr, which is no good for me. I've tried to swap them again like so: find /var/log 3>&1 1>&2 2>&3 | foo.file 4>&1 1>&2 2>&4 but this doesn't work. A: I found out how to do it in the end, following advice from this page. I need to redirect stderr to tee then redirect the output of tee back to stderr. find /var/log 2> >(tee foo.file >&2)
[ "stackoverflow", "0047300724.txt" ]
Q: Swift 3.0: Type of Expression is ambiguous without more context? private func makeRequest<T where T:MappableNetwork>(method method: Alamofire.Method, url: String, parameters: [String: AnyObject]?, keyPath: String, handler: NetworkHandler<T>.handlerArray) -> Request { let headers = [ "Authorization": "", ] return Alamofire .request(method, url, parameters: parameters, encoding: .URL, headers: headers) .validate() .responseArray(keyPath: keyPath) { (response: Alamofire.Response<[T], NSError>) in if let error = response.result.error { if let data = response.data { let error = self.getError(data) if error != nil { handler(.Error(error: error!)) return } } handler(.Error(error: error)) } else if let objects = response.result.value { handler(.Success(data: objects)) } } } I converted code swift 2.x to 3.x and I getting error Type expression is ambiguous without more context. A: The error you mentioned tells you that the compiler cannot determine the exact type of the value you entered. You started with a period, something has to be before the period. Sometimes the compiler can understand without your help. That's not this case, it has several options so it's ambiguous and it asks you to tell exactly the class name that you meant.
[ "stackoverflow", "0016427600.txt" ]
Q: How git clone actually works I have a repository on Github with 2 branches: master and develop. When I clone the repository and run $ git branch it shows only the master branch. If I run $ git branch -a I can see all the remote branches. Now, if I do a $ git checkout develop, I get the message: Branch develop set up to track remote branch develop from origin. Switched to a new branch 'develop' What actually happened? Were the commits from the remote develop branch fetched when I ran $ git clone remote-url, or when I ran: $ git checkout develop, or neither? Have I to do a $ git pull origin develop after checking out develop, or it's already done? Please help me understand how clone works when there are multiple branches on remote. A: git clone fetches all remote branches, but only creates one local branch, master, for you. So when you run git branch -a, you'll see something like this: $ git branch -a * master remotes/origin/HEAD remotes/origin/develop remotes/origin/master which means that you have one local branch master and several remote branches. When you ran git checkout develop, git creates another local branch develop to track remote branch origin/develop. git tries to synchronize tracking branches, so you don't have to do another pull after check out. If the local and remote branches terminologies sound confusing to you, you can browse through this document. It has some nice figures to help you understand them, and how local and remote branches move when you do further commits. You may find this answer helpful: How to clone all remote branches in Git?, the first answer. A: To put it simply, git clone repository-url does the following things, in order: Creates a new empty repository. git init Creates a remote called "origin" and sets it to the given url. git remote add origin repository-url Fetches all commits and remote branches from the remote called "origin". git fetch --all Creates a local branch "master" to track the remote branch "origin/master". git checkout --track origin/master An interesting point is that a fork (in GitHub or Bitbucket) is just a server side clone. A: git clone first creates a new empty repository. (like git init) It then sets the given repository as a remote called "origin". (git remote add) The main work is then done by git fetch, which is the only command talking to other repositories. It transfers all commits of the remote repository to the current repository and creates inside your local repository branches starting with "remote/origin/" corresponding with the branches on the remote repository. If you have a default non-bare repository, it will also call git checkout to checkout usually the master branch. If you call git branch -r it will show you the "remote" branches, i.e. those branches in your repository, which will get updated by git fetch. (You never work on these directly.) Whenever you want to work on a branch you use git checkout which will create a copy of that branch, without the "remote/origin/" prefix. Those are the "local" branches on which you work. (git branch will show those.) Almost everything you do will involve only your local repository. The only exception is git push, which is the only command to update remote repositories, and git fetch which is the only command to query other repositories. git pull is just the combination of git fetch and git merge. The first fetches changes and updates remote/origin/* and the second merges those changes into your local branch.
[ "stackoverflow", "0008074770.txt" ]
Q: regular expression to match this type of string I want to find the strings that share the following pattern: The first character is + and the last character is a space. There can have more than one characters between these two characters. They can be a digit or a digit or a letter, or any other character, such as *, &, etc. But they can not be space. In other words, there only has one space for this string and is at the end position. How to represent this pattern using regular expression? A: ^ matches the beginning of a string, and $ the end. You can make a character class with [] that matches only the things in the class, and ^ at the beginning makes it match anything not in the class, so [^ ] means "anything except a space". So the complete match is: ^\+[^ ]* $
[ "stackoverflow", "0055263166.txt" ]
Q: Check if skipws/noskipws flag is set for an input stream In order to set the std::skipws (or std::noskipws) flag, one needs to write: my_input_stream >> std::skipws; //or my_input_stream >> std::noskipws; But how do I check if the flag is set? I need to enable noskipws for my operator >> , but I want to restore the previously set value after. I am aware of boost I/O state savers, but I need to do a demonstration for students and using boost might be overkill for this simple purpose. A: You're looking for std::ios_base::flags() :) A: You have to use the flags of your stream: my_input_stream.flags() & std::ios_base::skipws A: You need to use the flags() member function. That will return the current flags, and you can test if the std::ios_base::skipws flag is set, like this: int main() { std::cin >> std::noskipws; if (!(std::cin.flags() & std::ios_base::skipws)) std::cout << "no skipws set\n"; std::cin >> std::skipws; if (std::cin.flags() & std::ios_base::skipws) std::cout << "skipws set"; }
[ "stackoverflow", "0058138475.txt" ]
Q: SQL Server using a local temp table in a stored procedure created in a different stored procedure I have inherited a database that contains a lot of stored procedures that create a local temporary table, calls a procedure that uses the temp table, and then deletes the temp table. Like this: CREATE PROCEDURE procSelectFromTable AS BEGIN SELECT * FROM #myTable END; GO CREATE PROCEDURE procMakeTable AS BEGIN SELECT 1 AS [ID] ,'NestedProcedure' AS [Message] INTO #myTable; EXEC procSelectFromTable DROP TABLE #myTable; END; GO EXEC procMakeTable; GO --Clean up IF OBJECT_ID('tempdb..#myTable') IS NOT NULL DROP TABLE #myTable; DROP PROCEDURE procMakeTable; DROP PROCEDURE procSelectFromTable I have not seen procedures written in this manner before. Is it safe for me to assume this is ok because the nested procedure will always be called in the same spid and will always be able to access the temp table? A: Yes, the nested procedure will have access to the local temp table. This was common use before the introduction of table-valued parameters or when the procedures exist in different databases in the same instance. The procedures are tightly coupled and might be a problem to test the 'child' procedure, but it has the advantage that it can be called from multiple procedures.
[ "stackoverflow", "0040437650.txt" ]
Q: Is it possible to disable opening a new tab or window in browser using JavaScript? My application is online testing. When user clicks the browser button, it goes to directly to my online exam page. User should not be able to open a new tab or window in the browser. Is it possible to disable a new tab or window in the browser using JavaScirpt? A: No, it's not possible. If it was possible, it could be easily abused by malicious sites, and wouldn't really solve your problem—someone could use another device, for example their phone.
[ "stackoverflow", "0040645459.txt" ]
Q: Showing duplicate comment on page refresh (after initial AJAX append) [Rails] Can't seem to figure this one out... In my rails app, I have Post and Comment resources. When a new comment is created, I want to reload the list of comments using AJAX. That part seems to work appropriately—however, when the full page is subsequently reloaded, the list also shows a duplicate of the comment, as shown in this screenshot. Any thoughts on what may be causing this? (note: deleting one of the comments also deletes the duplicate) views/users/show.html.haml = form_for([post, post.comments.build], remote: true) do |f| = f.text_field :content, placeholder: 'Press ENTER to submit...', class: "comment_content", id: "comment_content_#{post.id}" - if post.comments .comments{ id: "comments_#{post.id}" } - post.comments.each do |comment| = render post.comments, post: post views/comments/_comment.html.haml - unless comment.content == nil .comment{ id: "comment_#{comment.id}" } .user-name = link_to comment.user.identities.first.nickname, comment.user .comment-content = comment.content - if comment.user == current_user = link_to post_comment_path(post, comment), data: { confirm: "Are you sure?" }, method: :delete, remote: true do %i.fa.fa-close controllers/comments_controller.rb class CommentsController < ApplicationController before_action :set_post def create @comment = @post.comments.build(comment_params) @comment.user_id = current_user.id if @comment.save respond_to do |format| format.html { redirect_to :back } format.js end else render root_path end end ... views/comments/create.js.erb $('#comments_<%= @post.id %>').append("<%=j render @post.comments, post: @post, comment: @comment %>"); $('#comment_content_<%= @post.id %>').val('') Update Following @uzaif's suggestion, I replaced ".append" with ".html". This fixed the problem only if I also moved the code out of the _comment partial. Not really an ideal solution... I'd still like to know if/how I could fix the problem and keep my individual comment partial. A: The Problem You are seeing duplicate comments because you are inadvertently rendering your comments twice. - post.comments.each do |comment| = render post.comments, post: post Calling render and passing a collection as the first argument instructs Rails to render all of the comments. Internally Rails will iterate over each comment and render it using the object's partial. By wrapping this render call (which already has a loop in it) within another loop, you are actually rendering each comment twice. The Solution Remove the outer post.comments.each loop and just let the render method do it's thing. = render post.comments Rails knows to pass along an local variable named comment to each partial, and you should be able to reference the original post by calling comment.post (assuming comment belongs_to :post). Be careful how you call render There are a couple different ways to render partials with data from a collection. Make sure you know which one you are using and don't mix-and-match them. I describe this in another StackOverflow post. Resources http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-collections https://stackoverflow.com/a/40412677/1219460
[ "stackoverflow", "0022415543.txt" ]
Q: Extend tuples in one list using tuples from another list I have two lists. Both lists will have the same sets of rows. I would like to add list2 columns to list1 to create one list. list1 = [('gi1','1','2'), ('gi1','1','2'), ('gi1','1','2')] list2 = [('a','b','c','d','e','f','g'), ('a','b','c','d','e','f','g'), ('a','b','c','d','e','f','g')] I would like to merge these into a list that looks like this: [('gi1','1','2','a','b','c','d','e','f','g'), ('gi1','1','2','a','b','c','d','e','f','g'), ('gi1','1','2','a','b','c','d','e','f','g')] A: I would use the help of itertools.chain >>> list1=[('gi1','1','2'), ('gi1','1','2'), ('gi1','1','2')] >>> list2=[('a','b','c','d','e','f','g'), ('a','b','c','d','e','f','g'), ('a','b','c','d','e','f','g')] >>> from itertools import chain >>> [tuple(chain(x, y)) for x, y in zip(list1, list2)] [('gi1', '1', '2', 'a', 'b', 'c', 'd', 'e', 'f', 'g'), ('gi1', '1', '2', 'a', 'b', 'c', 'd', 'e', 'f', 'g'), ('gi1', '1', '2', 'a', 'b', 'c', 'd', 'e', 'f', 'g')]
[ "stackoverflow", "0034410967.txt" ]
Q: Weblogic 12c and Spring-Data-JPA Deployment JPA 2.1 Conflict I'm trying to deploy a spring-data-jpa,apache-cxf integrated project to Oracle Weblogic 12c (12.1.3) with below dependencies and getting below exception. jdk :1.7 weblogic : 12c(12.1.3) spring.version>4.1.0.RELEASE spring.data.version>1.7.2.RELEASE hibernate.version>4.3.11.Final So far I did; Tried to remove JPA 2.1 jar came from hibernate-entitymanager (didnt work,another exception thrown) Tried to figure out spring-data-jpa,spring and hibernate dependency check(not succeeded) Tried to give weblogic-applcation.xml for preferred-packages javax.persistence.* (doesn't change anything) Deployed to 12.2.1 and it does work I expect your valuable helps, thanks Exception <Warning> <HTTP> <BEA-101162> <User defined listener org.springframework.web.context.ContextLoaderListener failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/app-jpa-config.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: javax.persistence.JoinColumn.foreignKey()Ljavax/persistence/ForeignKey;org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/app-jpa-config.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: javax.persistence.JoinColumn.foreignKey()Ljavax/persistence/ForeignKey; at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1568) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:540) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229) Truncated. see log file for complete stacktrace Caused By:java.lang.NoSuchMethodError: javax.persistence.JoinColumn.foreignKey()Ljavax/persistence/ForeignKey; at org.hibernate.cfg.AnnotationBinder.bindManyToOne(AnnotationBinder.java:2884) at org.hibernate.cfg.AnnotationBinder.bindOneToOne(AnnotationBinder.java:3051) at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1839) at org.hibernate.cfg.AnnotationBinder.processIdPropertiesIfNotAlready(AnnotationBinder.java:963) at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:796) Truncated. see log file for complete stacktrace mvn pom.xml <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.1.0.RELEASE</spring.version> <spring.data.version>1.7.2.RELEASE</spring.data.version> <hibernate.version>4.3.11.Final</hibernate.version> <hibernate.validator.version>5.1.2.Final</hibernate.validator.version> <cxf.version>3.0.0</cxf.version> <log4j.version>1.2.17</log4j.version> <junit.version>4.12</junit.version> </properties> <dependencies> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>${spring.data.version}</version> <exclusions> <exclusion> <artifactId>spring-beans</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-core</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-aop</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-context</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-tx</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-orm</artifactId> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-framework-bom</artifactId> <version>${spring.version}</version> <type>pom</type> <scope>import</scope> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>${cxf.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>${cxf.version}</version> <scope>compile</scope> </dependency> <!-- LOG --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.2</version> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.7</version> </dependency> <!-- TEST --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- Object2Object mapping --> <dependency> <groupId>net.sf.dozer</groupId> <artifactId>dozer</artifactId> <version>5.5.1</version> </dependency> <!-- ORACLE --> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0</version> </dependency> </dependencies> A: JoinColumn.foreignKey() was introduced with JPA 2.1 and it is implemented in Hibernate 4.3 so it could be that WebLogic is using it's own JPA JARs that have an older version. The fact that your code runs with no problem on Weblogic 12.2.1 would confirm this. JPA 2.1 is part of Java EE 7 standard and it is supported from WebLogic 12.2.1 according to this IMHO you were on the right track when trying to set preferred packages on WebLogic. Try going trough this tutorial to add the JPA 2.1 libraries to the WebLogic Server classpath.
[ "stackoverflow", "0022144509.txt" ]
Q: Restrict inline code in view from having other than model related code I would want to restrict my .cshtml files so that the inline c# code only can be associated to the current model. So I would like to restrict the allowed namespaces or something similar. The background is that I need the view folder to be edited by the apps users(the admins of the system - not the web visitors). Some of my customers would want to show the images and some would not. Therefore I need to be in control of what the can do so they cant do <span> title @{ MyApp.Database.DeleteAll() or System.File.Read() } But I want them to be able to do @foreach(var img in @Model.Images){ <img src="@img" /> } The users will not have access to the server or to anything else(like webconfig ect). They will edit the .cshtml files through a web interface. Lets say I have a page where that shows a collection of uploaded images. Some admins want to show the images as a slider others as a simple ul This won't have any effect on the rest of the application because everything is loosely connected. A: This isn't possible and creates huge security leaks since Razor allows to run any C#-code. You could instead let them create templates in a different template-engine. There is for instance Handlebars for C# which should allow to do exactly what you need.
[ "pt.stackoverflow", "0000340262.txt" ]
Q: Transformar string em json Estou com dificuldade na hora de converter a string {data} em Json, eu recebo ela separada por virgula diversas vezes, gostaria de transformar ela em Json para coletar a primeira chave var data = [ "$SP", "92", "00:01:36.340", "00:05:48.929\n" ]; var data = [ "$MT", "91", "00:00:34.187", "00:18:44.001\n" ]; o desejado seria: { "$SP":{ "0":92, "1":"00:01:36.340", "2":"00:05:48.929", } }, { "$MT":{ "0":91, "1":"00:00:34.187", "2":00:18:44.001, } } A: Usando for...in você consegue montar esse JSON da forma que falou. Crie uma função e cada vez que receber a array data jogue-a para a função que irá adicionar novas entradas a um objeto pré-criado (ex, var json = {}). Veja: var json = {}; // crio o objeto principal function addJson(data){ var chave; // declaro a variável que será o nome do sub-objeto for(var i in data){ if(i == 0){ // trata apenas o primeiro valor da array, que será o nome do sub-objeto chave = data[i]; // declaro a variável com o primeiro valor da array json[chave] = {}; // cria o objeto com o primeiro valor da array }else{ json[chave][i-1] = data[i]; // adiciona as entradas seguindo a ordem dos índices a partir de 0 } } } // primeiro array recebido para adicionar ao objeto "json" var data = [ "$SP", "92", "00:01:36.340", "00:05:48.929\n" ]; addJson(data); // envia para a função // segundo array recebido para adicionar ao objeto "json" data = [ "$MT", "91", "00:00:34.187", "00:18:44.001\n" ]; addJson(data); // envia para a função console.log(json); console.log(json.$MT[0]);
[ "stackoverflow", "0025900051.txt" ]
Q: Batch file Nesting findstr inside a loop I'm trying to run the prntmngr.vbs script. I'm trying to find strings like Printer name, server name, etc. There are about 80-200 printers on each server I want it to pipe the information in a csv format. I'm having trouble nesting the findstr's and loops to get the information. I've pieced together some things. running the vbs gives me every printer and its information. The VBS outputs every printer in a block of information as follows. Theres about 80 printers on this one server. I'll worry about scoping out to other servers, as long as I can get it to output the information. Server name lak-print01 Printer name 1015_Q1 Share name 1015_Q1 Driver name HP LaserJet 4350 PCL 5e Port name IP_192.168.15.249 Comment Trust & Savings Location 43rd & Meridian Print processor HPCPP5r1 Data type RAW Parameters Attributes 8776 Priority 1 Default priority 0 Average pages per minute 0 Printer status Other Extended printer status Offline Detected error state Offline Extended detected error state Other Server name lak-print01 Printer name 1014_Q1 Share name 1014_Q1 Driver name Canon iR3225 PCL5e Port name IP_192.168.14.245 Comment CSR and Teller Printer Location Summit Print processor WinPrint Data type RAW Parameters Attributes 10824 Priority 1 Default priority 0 Average pages per minute 0 Printer status Idle Extended printer status Unknown Detected error state Unknown Extended detected error state Unknown Server name lak-print01 Printer name 1011_Q3 Share name 1011_Q3 Driver name HP LaserJet 4200 PCL 6 Port name IP_192.168.11.247 Comment HP LaserJet 4200 not being used can delete Location Spanaway Print processor HPZPP3xy Data type RAW Parameters Attributes 8778 Priority 1 Default priority 0 Average pages per minute 0 Printer status Idle Extended printer status Unknown Detected error state Unknown Extended detected error state Unknown for instance I'd love the output to be a csv that outputs the example vbs to lak-print01,1015_Q1,HP LaserJet 4350 PCL 5e,IP_192.168.15.249,Trust & Savings,43rd & Meridian,Other lak-print01,1014_Q1,Canon iR3225 PCL5e,IP_192.168.14.245,CSR and Teller Printer,Summit,Idle pulling find strings for printer server, printer name, printer driver, port name, comment, location, status Ive gotten a working script @echo off SetLocal enabledelayedexpansion cscript prnmngr.vbs -l -s lak-print01 >test.csv for /f "tokens=3*" %%i in ('findstr /i /c:"Printer name" /i /c:"Server name" /i /c:"Printer status" /i /c:"Driver name" test.csv') do @echo %%i, endlocal That outputs 1005_Q2, HP, Other, status, lak-print01, 1004_Q2, HP, Idle, status, lak-print01, 1004_Q1, HP, Idle, status, lak-print01, 1003_Q2, HP, Idle, status, lak-print01, 1003_Q1, HP, Idle, status, Which is great, however its only pulling the first word of the driver name even with the wildcard in the tokens. Now I just have to figure out how to make it carriage return after a for loop is complete to start a new line with new set of data. A: @ECHO Off SETLOCAL enabledelayedexpansion :: remove variables starting $ FOR /F "delims==" %%a In ('set $ 2^>Nul') DO SET "%%a=" (FOR /f "delims=" %%a IN (q25900051.txt) DO CALL :analyse "%%a")>printers.csv GOTO :EOF :analyse SET "line=%~1" SET /a fieldnum=0 FOR %%s IN ("Server name" "Printer name" "Driver name" "Port name" "Comment" "Location" "Printer status" "Extended detected error state") DO CALL :setfield %%~s GOTO :eof :setfield SET /a fieldnum+=1 SET "linem=!line:*%* =!" SET "linet=%* %linem%" IF "%linet%" neq "%line%" GOTO :EOF IF "%linem%"=="%line%" GOTO :EOF SET "$%fieldnum%=%linem%" IF NOT DEFINED $8 GOTO :EOF SET "line=" FOR /l %%q IN (1,1,7) DO SET "line=!line!,!$%%q!" ECHO !line:~1! :: remove variables starting $ FOR /F "delims==" %%a In ('set $ 2^>Nul') DO SET "%%a=" GOTO :eof I used a file named q25900051.txt containing your data for my testing. This could be automated a little further, but I don't have the time at present. Essentially, it analyses each line and sets a field number 1..number-of-columns+1. When the number-of-columns+1'th column is filled, the output is accumulated and echoed and the $ variables reset. The "Manual" part is entering the names of the fields to be selected, including the "end of block" field as the last entry; then the variable $8 and the top limit for %%q are set - 8 fields potentially being analysed, 7 being output. The jiggery-pokery with line, linem (modified line - minus the field name) and linet (total line - reconstructed) is first to extract the required data by removing the string as far as the target. The line is then reconstructed as linet and compared to the original version in line. This allos us to distinguish between the line that starts Printer status and theline that starts Extended printer status - when the target is printer status, the first line will be reconstructed to match the original, but the second will lop off Extended printer status then re-add printer status, so the reconstructed line does not match the original... Modified for new requirement - output to file. It's in a rather odd place - parenthisise the for statement invoking thesubroutines - any output from echo statements within the subroutines will be redirected to the file nominated. since you asked...
[ "stackoverflow", "0043055518.txt" ]
Q: Why can't I use javascript array rest destructuring both ways? I've been using and loving babel (6.5.2) for a while now and find the new destructuring syntax great for writing clearer JavaScript. Why doesn't the rest destructuring work (it generates a token error) anywhere in the array? For example: const [column, ...restOfColumns] = columns; const objProps = column.valueChain.slice(0, -1); const prop = column.valueChain[column.valueChain.length - 1]; //const [...objProps, prop] = column.valueChain The commented out line would replace the preceding two lines with something much easier to read and understand. A: The simple answer is that when you use the destructing syntax ..., it means everything else. Therefore when you try [...objProps, prop], it doesn't know what to assign to prop as you have assigned all values already to objProps
[ "stackoverflow", "0006702169.txt" ]
Q: What does Haskell call the Hom Functor/Monad? I'd like to use it in my code and would rather not duplicate it, but since it involves only massively generic words like "function" or "composition" I can't find it by searching. To be completely specific, I'm looking for instance Functor (x->) where fmap f p = f . p A: This is the basic reader (or environment) monad, usually referred to as ((->) e). (This is (e ->) written as a partially applied function instead of as a section; the latter syntax is problematic to parse.) You can get it by importing Control.Monad.Reader or Control.Monad.Instances.
[ "stackoverflow", "0062182141.txt" ]
Q: How to iterate through xml in log files using Python I have log files in which text and xml is mixed. I want to iterate through 'Poutcomes' to so that I can validate imformation recieved is as expected. For example I need to validate if AreadID for ItemId = 373012. 2019-09-12 15:30:02.137 (162,<ThreadPool> ) Info Sending: <Keepalive /> 2019-09-12 15:30:03.512 (65 ,Estate ) DebugInfo Incoming buffer has 292 bytes <Poutcome> <ItemId>373011</ItemId> <AreaId>232</AreaId> <CarrierId>131</CarrierId> <AResult> <Measured>Ok</Measured> </AResult> <TimeStamp>2019-09-12T19:30:02Z</TimeStamp> </Poutcome> 2019-09-12 15:32:02.137 (162,<ThreadPool> ) Info Sending: <Keepalive /> 2019-09-12 15:32:03.512 (65 ,Estate ) DebugInfo Incoming buffer has 292 bytes <Poutcome> <ItemId>373012</ItemId> <AreaId>232</AreaId> <CarrierId>131</CarrierId> <AResult> <Measured>Ok</Measured> </AResult> <TimeStamp>2019-09-12T19:32:02Z</TimeStamp> </Poutcome> 2019-09-12 15:30:06.559 (65 ,Estate ) DebugInfo Holding 0 bytes in buffer 2019-09-12 15:30:12.153 (149,<ThreadPool> ) Info Sending: <Keepalive /> 2019-09-12 15:30:16.561 (65 ,Estate ) DebugInfo Incoming buffer has 15 bytes 2019-09-12 15:30:16.561 (65 ,Estate ) Info Received: <Keepalive /> I tried many xml ET but couldnt achieve because of text in between xml. I am trying Simplifiedscrapy now as suggested by someone, but it helps only to validate 1st part of logs, doesnt iterate to validate throughout log. How can I iterate to validate 2nd part of message (373012)? This is where I am now import xml.etree.ElementTree as ET from simplified_scrapy import SimplifiedDoc log_file_path = 'C:/Users/xx.log' with open(log_file_path) as f: xml = f.read() #print(xml) doc = SimplifiedDoc(xml) Poutcome = doc.Poutcome #print(Poutcome.ItemId.text, Poutcome.DestinationId.text) if Poutcome.ItemId.text == 373012: print(Poutcome.DestinationId.text) A: Consider cleaning up log file to keep only the XML markup. Below builds a string on every line of log except lines that start with 2019 and <Keepalive /> (ad add others in the . Either create a new XML and read document with parse or directly read string in fromstring: import xml.etree.ElementTree as ET with open('XMLinLog.txt', 'r') as fr, open('XMLinLog.xml', 'w') as fw: fw.write("<document>\n") xmlstr = "<document>\n" for line in fr: if line.strip().startswith('<'): xmlstr += line fw.write(line) xmlstr += "\n</document>" fw.write("\n</document>") doc = ET.fromstring(xmlstr) doc = ET.parse('XMLinLog.xml') #...RUN NEEDED PARSING Output <document> <Keepalive /> <Poutcome> <ItemId>373011</ItemId> <AreaId>232</AreaId> <CarrierId>131</CarrierId> <AResult> <Measured>Ok</Measured> </AResult> <TimeStamp>2019-09-12T19:30:02Z</TimeStamp> </Poutcome> <Keepalive /> <Poutcome> <ItemId>373012</ItemId> <AreaId>232</AreaId> <CarrierId>131</CarrierId> <AResult> <Measured>Ok</Measured> </AResult> <TimeStamp>2019-09-12T19:32:02Z</TimeStamp> </Poutcome> </document>
[ "stackoverflow", "0024321787.txt" ]
Q: How can i add attribute name and Column value from an xml file to Dictionary <table name="table1"> <col>Comp1</col> <col>Compo4_</col> <col>Dire3</col> <col>Attri4s</col> <col>Condition</col> </table> <table name="table2"> <col>Compo4_</col> <col>Compon7</col> <col>Direc9</col> </table> i have an xml file as given above.i want to add the value of tablename and the col no of Compo4_ to a dictionary.i tried the following code.But every time iam getting the first column value in coltext. dic={} for node in doc.getElementsByTagName('table'): name = node.getAttribute('name') value=0 for subnode in node.childNodes: if subnode.nodeType == node.ELEMENT_NODE and subnode.tagName == "col": colvalue=colvalue+1 coltext = subnode.getElementsByTagName('col') if coltext=='Compo4_': componentIddic[table_name]=colvalue Please don't suggest me to use Elementree.Because our whole implemenatation we are using minidom A: The coltext seems to be different from what you're expecting. Try to use the firstChild attribute. coltext = subnode.firstChild.nodeValue My result is {'table2': 6, 'table1': 2}
[ "stackoverflow", "0044295720.txt" ]
Q: c# get youtube playlist using Youtube data api v3 I am currently developing a software for my school. This software must be able to publish videos, but it also must be able to add those video to a playlist. Question: How can I list all the existing playlist (even empty or private) of the account? I am using YouTube data API v3, and I am unable to get the empty ones. Here is the code: private async Task Run() { UserCredential credential; using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) { credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, // This OAuth 2.0 access scope allows for read-only access to the authenticated // user's account, but not other types of account access. new[] { YouTubeService.Scope.YoutubeReadonly }, "user", CancellationToken.None, new FileDataStore(this.GetType().ToString()) ); } var youtubeService = new YouTubeService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = this.GetType().ToString() }); var channelsListRequest = youtubeService.Channels.List("contentDetails"); channelsListRequest.Mine = true; // Retrieve the contentDetails part of the channel resource for the authenticated user's channel. var channelsListResponse = await channelsListRequest.ExecuteAsync(); foreach (var channel in channelsListResponse.Items) { // From the API response, extract the playlist ID that identifies the list // of videos uploaded to the authenticated user's channel. var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads; Console.WriteLine("Videos in list {0}", uploadsListId); var nextPageToken = ""; while (nextPageToken != null) { var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet"); playlistItemsListRequest.PlaylistId = uploadsListId; playlistItemsListRequest.MaxResults = 50; playlistItemsListRequest.PageToken = nextPageToken; // Retrieve the list of videos uploaded to the authenticated user's channel. var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync(); foreach (var playlistItem in playlistItemsListResponse.Items) { // Print information about each video. Console.WriteLine("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId); } nextPageToken = playlistItemsListResponse.NextPageToken; } } } Thank you in advance. A: I got this code to work by doing this: private async Task Run() { UserCredential credential; using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) { credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, // This OAuth 2.0 access scope allows for read-only access to the authenticated // user's account, but not other types of account access. new[] { YouTubeService.Scope.YoutubeReadonly }, "user", CancellationToken.None, new FileDataStore(this.GetType().ToString()) ); } var youtubeService = new YouTubeService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = this.GetType().ToString() }); // var channelsListRequest = youtubeService.Channels.List("contentDetails"); var playlistListRequest = youtubeService.Playlists.List("snippet"); playlistListRequest.Mine = true; // Retrieve the contentDetails part of the channel resource for the authenticated user's channel. var playlistListResponse = await playlistListRequest.ExecuteAsync(); foreach (var playlist in playlistListResponse.Items) { // From the API response, extract the playlist ID that identifies the list // of videos uploaded to the authenticated user's channel. var playlistListId = playlist.Id; Console.WriteLine("Videos in list {0}", playlistListId); } } Thanks to "not_a_bot" for helping me.
[ "stackoverflow", "0029808928.txt" ]
Q: Printing QModelIndex vs QModelIndex.model(): different hex values? When you print out a QModelIndex in Pyside, the object representation shows the row, column, parent, model, and memory address. However, if you print out index.model(), the memory address for the model is different. Here is some code that demonstrates what I mean: from PySide import QtGui, QtCore class TestQModelIndexModelWin(QtGui.QMainWindow): def __init__(self, parent=None): super(TestQModelIndexModelWin, self).__init__(parent) self.listView = QtGui.QListView() self.setCentralWidget(self.listView) listModel = QtGui.QStringListModel(['foo', 'bar', 'baz']) self.listView.setModel(listModel) numItems = len(listModel.stringList()) for i in range(numItems): index = listModel.index(i, 0) print index print index.model() When running this code, the results look something like the following: <PySide.QtCore.QModelIndex(0,0,0x0,QStringListModel(0xef1b7e0) ) at 0x0000000017656D08> <PySide.QtGui.QStringListModel object at 0x0000000017656948> <PySide.QtCore.QModelIndex(1,0,0x0,QStringListModel(0xef1b7e0) ) at 0x00000000176564C8> <PySide.QtGui.QStringListModel object at 0x0000000017656948> <PySide.QtCore.QModelIndex(2,0,0x0,QStringListModel(0xef1b7e0) ) at 0x0000000017656D08> <PySide.QtGui.QStringListModel object at 0x0000000017656948> Why does the QModelIndex show the QStringListModel hex value as 0xef1b7e0 but the QStringListModel shows its address as 0x0000000017656948? A: The repr for index is showing the C++ address of the model it is associated with. Whereas the repr for index.model() is showing the address of the python object that wraps the C++ model. You can verify this by using the shiboken module: import shiboken ... print index print index.model() print shiboken.dump(index.model()) which will produce output like this: <PySide.QtCore.QModelIndex(2,0,0x0,QStringListModel(0x17b0b40) ) at 0x7ff1a3715998> <PySide.QtGui.QStringListModel object at 0x7ff1a3715950> C++ address....... PySide.QtGui.QStringListModel/0x17b0b40 hasOwnership...... 1 containsCppWrapper 1 validCppObject.... 1 wasCreatedByPython 1
[ "tex.stackexchange", "0000222996.txt" ]
Q: Theoremstyle : adding dots I need an extra dot in the format of \theoremstyle, for example; 2.1.3. Theorem 2.1. Lemma I use : \documentclass{article} \usepackage{amsthm} \swapnumbers \newlength{\spacelength} \settowidth{\spacelength}{\normalfont\ } \newtheoremstyle{mystyle} {\baselineskip}{\baselineskip}{\itshape}{}{}{\vspace{\baselineskip}}{\newline} {\thmname{#1}\thmnumber{ #2}\thmnote{ #3}} \theoremstyle{mystyle} \newtheorem{theorem}{Theorem}[section] \newtheorem{lemma}[theorem]{Lemma} \begin{document} \section{test} \begin{theorem} A theorem \end{theorem} \begin{lemma} A lemma \end{lemma} \end{document} A: Just comment the line \swapnumbers and use \newtheoremstyle{mystyle} {\baselineskip}{\baselineskip}{\itshape}{}{}{\vspace{\baselineskip}}{\newline} {\thmnumber{#2}.\thmname{ #1}\thmnote{ #3}} MWE \documentclass{article} \usepackage{amsthm} %\swapnumbers \newlength{\spacelength} \settowidth{\spacelength}{\normalfont\ } \newtheoremstyle{mystyle} {\baselineskip}{\baselineskip}{\itshape}{}{}{\vspace{\baselineskip}}{\newline} {\thmnumber{#2}.\thmname{ #1}\thmnote{ #3}} \theoremstyle{mystyle} \newtheorem{theorem}{Theorem}[section] \newtheorem{lemma}[theorem]{Lemma} \begin{document} \section{test} \begin{theorem} A theorem \end{theorem} \begin{lemma} A lemma \end{lemma} \end{document} Output
[ "stackoverflow", "0061516217.txt" ]
Q: Performance of the RegExp object In the following code, the I'd like to improve the performance by putting the RegExp object somewhere, but I can't figure out how to do the nest. @ValidatorConstraint() export class RegExp implements ValidatorConstraintInterface { validate(kana: string, args: ValidationArguments) { const str = new RegExp(/^[ァ-ヶー]+$/) return str.test(kana) } defaultMessage(args: ValidationArguments) { return 'Text should be' } } thanks A: If you need regexp only - simply use a built-in Matches validator: @Matches(/^[ァ-ヶー]+$/) public field: string; In this case it will reuse regexp on every validation.
[ "stackoverflow", "0009942859.txt" ]
Q: Javascript call to ASP.NET Page Method working on IE but not on Chrome / Firefox I have the following code in an ASPX page that, when a PayPal icon is clicked, connects with a Page Method and retrieves the PayPal token of a session. When this is executed in IE, it works perfectly, but when it is executed in Chrome or Firefox, the $.ajax call of jQuery returns immediately an error of code 0. $(document).ready(function () { $("input.PayPal").click(function () { $.ajax({ type: "POST", url: "MyCurrentPage.aspx/PayPal", data: "{IdRecibo : " + $(this).attr("data-value") + "}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (result) { if (result.d.Result == "Success") { window.location.href = result.d.Redirect; } else alert("El servicio de PayPal está temporalmente deshabilitado."); }, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); } }); }); A: A slight change of code solves the problem with Chrome. It looks like the JSON response of the ASP.NET Page Method is not correctly parsed if return false; is not the last part of the $.ajax call. This is the working code: $("input.PayPal").click(function () { $.ajax({ type: "POST", url: '<%= Page.Request.Url.AbsolutePath + "/PayPal" %>', data: JSON.stringify({ IdRecibo: $(this).attr("data-value") }), contentType: "application/json; charset=utf-8", dataType: "json", cache: "false", timeout: 10000, success: function (result) { if (result.d.Result == "Success") { window.location.href = result.d.Redirect; } else alert("El servicio de PayPal está temporalmente deshabilitado."); }, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); } }); return false; });
[ "stackoverflow", "0003615013.txt" ]
Q: How can I create horizontal view scrolling like the News & Weather app? Android News & Weather app lets you swipe to reveal another view, just like the iPhone. Can someone show me an example of how this is done? It is not a ViewFlipper attached to a GestureDetector. A: It is a custom view, you can see how it's done in Launcher by looking at Workspace.java in packages/apps/Launcher2 at android.git.kernel.org.
[ "stackoverflow", "0030214811.txt" ]
Q: change only username color inside conversation textbox "chat on LAN" I made a LAN chat and everything work, I want to change only USER color inside the conversation box, I tried everything and read allot of articles and used usercontroller & for now nothing work! Is that possible to change it from #Region "Windows Form Designer generated code" 'txtConversation' Me.txtConversation.BackColor = System.Drawing.Color.White Me.txtConversation.Location = New System.Drawing.Point(15, 60) Me.txtConversation.Multiline = True Me.txtConversation.Name = "txtConversation" Me.txtConversation.ReadOnly = True Me.txtConversation.ScrollBars = System.Windows.Forms.ScrollBars.Both Me.txtConversation.Size = New System.Drawing.Size(305, 184) Me.txtConversation.TabIndex = 14 I tried to add this line to the code also tried other codes and nothing work! Me.txtConversation.BackColor = System.Drawing.Color.White Me.txtConversation.Font = System.Drawing.Color.Red Me.txtConversation.ForeColor = Color.Red If this work the next step will be to make the color only for username inside the conversation box I don't know how! I am completely lost! UPDATE Imports System.DirectoryServices Imports System.Net Imports System.IO Imports System.Net.Sockets Imports MSTSCLib Public Class frmMain Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. Friend WithEvents TreeView1 As System.Windows.Forms.TreeView Friend WithEvents txtPCName As System.Windows.Forms.TextBox Friend WithEvents txtSend As System.Windows.Forms.TextBox Friend WithEvents CmdSend As System.Windows.Forms.Button Friend WithEvents ImageList1 As System.Windows.Forms.ImageList Friend WithEvents txtPCIPadd As System.Windows.Forms.TextBox Friend WithEvents Label3 As System.Windows.Forms.Label Friend WithEvents Timer1 As System.Windows.Forms.Timer Friend WithEvents txtUsername As System.Windows.Forms.TextBox Friend WithEvents Label4 As System.Windows.Forms.Label Friend WithEvents Label5 As System.Windows.Forms.Label Friend WithEvents txtConversation As System.Windows.Forms.TextBox Friend WithEvents txttempmsg As System.Windows.Forms.TextBox Friend WithEvents Button1 As System.Windows.Forms.Button Friend WithEvents Button2 As System.Windows.Forms.Button Friend WithEvents Button3 As System.Windows.Forms.Button Friend WithEvents box As System.Windows.Forms.RichTextBox Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox Friend WithEvents Label2 As System.Windows.Forms.Label <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Me.components = New System.ComponentModel.Container() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmMain)) Me.CmdSend = New System.Windows.Forms.Button() Me.TreeView1 = New System.Windows.Forms.TreeView() Me.ImageList1 = New System.Windows.Forms.ImageList(Me.components) Me.txtPCName = New System.Windows.Forms.TextBox() Me.txtSend = New System.Windows.Forms.TextBox() Me.txtPCIPadd = New System.Windows.Forms.TextBox() Me.Label2 = New System.Windows.Forms.Label() Me.Label3 = New System.Windows.Forms.Label() Me.Timer1 = New System.Windows.Forms.Timer(Me.components) Me.txtUsername = New System.Windows.Forms.TextBox() Me.Label4 = New System.Windows.Forms.Label() Me.Label5 = New System.Windows.Forms.Label() Me.txtConversation = New System.Windows.Forms.TextBox() Me.txttempmsg = New System.Windows.Forms.TextBox() Me.Button1 = New System.Windows.Forms.Button() Me.Button2 = New System.Windows.Forms.Button() Me.Button3 = New System.Windows.Forms.Button() Me.box = New System.Windows.Forms.RichTextBox() Me.GroupBox1 = New System.Windows.Forms.GroupBox() Me.GroupBox1.SuspendLayout() Me.SuspendLayout() ' 'CmdSend ' Me.CmdSend.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.CmdSend.Location = New System.Drawing.Point(404, 265) Me.CmdSend.Name = "CmdSend" Me.CmdSend.Size = New System.Drawing.Size(55, 52) Me.CmdSend.TabIndex = 0 Me.CmdSend.Text = "&Send" ' 'TreeView1 ' Me.TreeView1.BackColor = System.Drawing.Color.Gainsboro Me.TreeView1.BorderStyle = System.Windows.Forms.BorderStyle.None Me.TreeView1.ImageIndex = 0 Me.TreeView1.ImageList = Me.ImageList1 Me.TreeView1.Location = New System.Drawing.Point(326, 10) Me.TreeView1.Name = "TreeView1" Me.TreeView1.SelectedImageIndex = 0 Me.TreeView1.Size = New System.Drawing.Size(133, 234) Me.TreeView1.TabIndex = 1 ' 'ImageList1 ' Me.ImageList1.ImageStream = CType(resources.GetObject("ImageList1.ImageStream"), System.Windows.Forms.ImageListStreamer) Me.ImageList1.TransparentColor = System.Drawing.Color.Transparent Me.ImageList1.Images.SetKeyName(0, "") ' 'txtPCName ' Me.txtPCName.Location = New System.Drawing.Point(82, 34) Me.txtPCName.Name = "txtPCName" Me.txtPCName.ReadOnly = True Me.txtPCName.Size = New System.Drawing.Size(238, 20) Me.txtPCName.TabIndex = 2 ' 'txtSend ' Me.txtSend.Location = New System.Drawing.Point(12, 266) Me.txtSend.Multiline = True Me.txtSend.Name = "txtSend" Me.txtSend.ScrollBars = System.Windows.Forms.ScrollBars.Both Me.txtSend.Size = New System.Drawing.Size(386, 52) Me.txtSend.TabIndex = 3 ' 'txtPCIPadd ' Me.txtPCIPadd.Location = New System.Drawing.Point(452, 332) Me.txtPCIPadd.Name = "txtPCIPadd" Me.txtPCIPadd.ReadOnly = True Me.txtPCIPadd.Size = New System.Drawing.Size(191, 20) Me.txtPCIPadd.TabIndex = 6 ' 'Label2 ' Me.Label2.AutoSize = True Me.Label2.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label2.Location = New System.Drawing.Point(439, 328) Me.Label2.Name = "Label2" Me.Label2.Size = New System.Drawing.Size(71, 15) Me.Label2.TabIndex = 7 Me.Label2.Text = "IP Address :" ' 'Label3 ' Me.Label3.AutoSize = True Me.Label3.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label3.Location = New System.Drawing.Point(12, 247) Me.Label3.Name = "Label3" Me.Label3.Size = New System.Drawing.Size(58, 15) Me.Label3.TabIndex = 9 Me.Label3.Text = "Message" ' 'Timer1 ' ' 'txtUsername ' Me.txtUsername.Location = New System.Drawing.Point(82, 10) Me.txtUsername.Name = "txtUsername" Me.txtUsername.ReadOnly = True Me.txtUsername.Size = New System.Drawing.Size(238, 20) Me.txtUsername.TabIndex = 10 ' 'Label4 ' Me.Label4.AutoSize = True Me.Label4.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label4.Location = New System.Drawing.Point(13, 10) Me.Label4.Name = "Label4" Me.Label4.Size = New System.Drawing.Size(70, 15) Me.Label4.TabIndex = 11 Me.Label4.Text = "Your name:" ' 'Label5 ' Me.Label5.AutoSize = True Me.Label5.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label5.Location = New System.Drawing.Point(13, 35) Me.Label5.Name = "Label5" Me.Label5.Size = New System.Drawing.Size(44, 15) Me.Label5.TabIndex = 12 Me.Label5.Text = "Buddy:" ' 'txtConversation ' Me.txtConversation.BackColor = System.Drawing.Color.White Me.txtConversation.Location = New System.Drawing.Point(506, 336) Me.txtConversation.Multiline = True Me.txtConversation.Name = "txtConversation" Me.txtConversation.ReadOnly = True Me.txtConversation.ScrollBars = System.Windows.Forms.ScrollBars.Both Me.txtConversation.Size = New System.Drawing.Size(305, 184) Me.txtConversation.TabIndex = 14 ' 'txttempmsg ' Me.txttempmsg.Enabled = False Me.txttempmsg.Location = New System.Drawing.Point(12, 342) Me.txttempmsg.Multiline = True Me.txttempmsg.Name = "txttempmsg" Me.txttempmsg.Size = New System.Drawing.Size(212, 23) Me.txttempmsg.TabIndex = 15 Me.txttempmsg.Visible = False ' 'Button1 ' Me.Button1.Location = New System.Drawing.Point(6, 19) Me.Button1.Name = "Button1" Me.Button1.Size = New System.Drawing.Size(75, 23) Me.Button1.TabIndex = 16 Me.Button1.Text = "Browse" Me.Button1.UseVisualStyleBackColor = True ' 'Button2 ' Me.Button2.Location = New System.Drawing.Point(87, 19) Me.Button2.Name = "Button2" Me.Button2.Size = New System.Drawing.Size(75, 23) Me.Button2.TabIndex = 17 Me.Button2.Text = "Send" Me.Button2.UseVisualStyleBackColor = True ' 'Button3 ' Me.Button3.Location = New System.Drawing.Point(6, 71) Me.Button3.Name = "Button3" Me.Button3.Size = New System.Drawing.Size(156, 23) Me.Button3.TabIndex = 18 Me.Button3.Text = "Receive" Me.Button3.UseVisualStyleBackColor = True ' 'box ' Me.box.BackColor = System.Drawing.SystemColors.ButtonHighlight Me.box.Location = New System.Drawing.Point(12, 60) Me.box.Name = "box" Me.box.ReadOnly = True Me.box.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Vertical Me.box.Size = New System.Drawing.Size(308, 184) Me.box.TabIndex = 19 Me.box.Text = "" ' 'GroupBox1 ' Me.GroupBox1.Controls.Add(Me.Button1) Me.GroupBox1.Controls.Add(Me.Button2) Me.GroupBox1.Controls.Add(Me.Button3) Me.GroupBox1.Location = New System.Drawing.Point(465, 12) Me.GroupBox1.Name = "GroupBox1" Me.GroupBox1.Size = New System.Drawing.Size(170, 100) Me.GroupBox1.TabIndex = 20 Me.GroupBox1.TabStop = False Me.GroupBox1.Text = "Send Files" ' 'frmMain ' Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.BackColor = System.Drawing.SystemColors.ButtonFace Me.ClientSize = New System.Drawing.Size(646, 329) Me.Controls.Add(Me.GroupBox1) Me.Controls.Add(Me.box) Me.Controls.Add(Me.txttempmsg) Me.Controls.Add(Me.txtConversation) Me.Controls.Add(Me.Label5) Me.Controls.Add(Me.Label4) Me.Controls.Add(Me.txtUsername) Me.Controls.Add(Me.Label3) Me.Controls.Add(Me.Label2) Me.Controls.Add(Me.txtPCIPadd) Me.Controls.Add(Me.txtSend) Me.Controls.Add(Me.txtPCName) Me.Controls.Add(Me.TreeView1) Me.Controls.Add(Me.CmdSend) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.MaximizeBox = False Me.Name = "frmMain" Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "KiWi Messenger" Me.GroupBox1.ResumeLayout(False) Me.ResumeLayout(False) Me.PerformLayout() End Sub #End Region Dim listerner As New TcpListener(44444) Dim client As TcpClient Dim client2 As TcpClient Dim message As String = "" Dim tts As Object Dim Sound As New System.Media.SoundPlayer() Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing listerner.Stop() End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'TextBox1.Selectionstart = TextBox1.TextLength 'TextBox1.ScrollToCaret() Dim childEntry As DirectoryEntry Dim ParentEntry As New DirectoryEntry() Try ParentEntry.Path = "WinNT:" For Each childEntry In ParentEntry.Children Dim newNode As New TreeNode(childEntry.Name) Select Case childEntry.SchemaClassName Case "Domain" Dim ParentDomain As New TreeNode(childEntry.Name) TreeView1.Nodes.AddRange(New TreeNode() {ParentDomain}) Dim SubChildEntry As DirectoryEntry Dim SubParentEntry As New DirectoryEntry() SubParentEntry.Path = "WinNT://" & childEntry.Name For Each SubChildEntry In SubParentEntry.Children Dim newNode1 As New TreeNode(SubChildEntry.Name) Select Case SubChildEntry.SchemaClassName Case "Computer" ParentDomain.Nodes.Add(newNode1) End Select Next End Select Next Catch Excep As Exception MsgBox("Error While Reading Directories") Finally ParentEntry = Nothing End Try listerner.Start() Timer1.Enabled = True Timer1.Start() End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdSend.Click AddMessage(txtUsername As String, txtSend As String) box.SelectionColor = Color.Red box.AppendText(vbCrLf & user & ": ") box.SelectionColor = Color.Black box.AppendText(txtSend) ' Shell("net send " & txtcomputer.Text & " " & txtmessage.Text) Try If txtPCIPadd.Text = "" Or txtUsername.Text = "" Or txtSend.Text = "" Then MsgBox("wright a message!") Else client = New TcpClient(txtPCIPadd.Text, 44444) Dim writer As New StreamWriter(client.GetStream()) txttempmsg.Text = (txtSend.Text) writer.Write(txtUsername.Text + " : " + txtSend.Text) box.Text = (box.Text + txtUsername.Text + " : " + txttempmsg.Text + vbCrLf) 'txtmsg.Text="You:" + txtmessage.Text) writer.Flush() txtSend.Text = "" End If Catch ex As Exception MsgBox(ex.Message) End Try End Sub Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect txtPCName.Text = TreeView1.SelectedNode.Text txtPCIPadd.Text = GetIPAddress(txtPCName.Text) txtUsername.Text = System.Environment.MachineName End Sub Function GetIPAddress(ByVal CompName As String) As String Dim oAddr As System.Net.IPAddress Dim sAddr As String Try With System.Net.Dns.GetHostByName(CompName) oAddr = New System.Net.IPAddress(.AddressList(0).Address) sAddr = oAddr.ToString End With GetIPAddress = sAddr Catch Excep As Exception MsgBox(Excep.Message, MsgBoxStyle.OkOnly, "Lan Messenger") Finally End Try End Function Private Sub CmdPing_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Shell("PING " & txtPCIPadd.Text) End Sub 'Shell("net send ALL " & txtmessage.Text) Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick Try If listerner.Pending = True Then message = "" client = listerner.AcceptTcpClient Dim reader As New StreamReader(client.GetStream()) While reader.Peek > -1 message = message + Convert.ToChar(reader.Read()).ToString End While Me.Focus() box.Text = (box.Text + message + vbCrLf) box.SelectionStart = box.TextLength box.ScrollToCaret() 'txtmsg.Text="You:" + txtmessage.Text) My.Computer.Audio.Play(My.Resources.alert, AudioPlayMode.Background) Sound.Load() Sound.Play() End If Catch ex As Exception MsgBox(ex.Message) End Try End Sub Private Function c() As String Throw New NotImplementedException End Function Private Sub txtUsername_TextChanged(sender As Object, e As EventArgs) Handles txtUsername.TextChanged End Sub Private Sub txtPCName_TextChanged(sender As Object, e As EventArgs) Handles txtPCName.TextChanged End Sub Private Sub txtPCIPadd_TextChanged(sender As Object, e As EventArgs) Handles txtPCIPadd.TextChanged End Sub Private Sub txtConversation_TextChanged(sender As Object, e As EventArgs) Handles txtConversation.TextChanged End Sub Private Sub txtSend_TextChanged(sender As Object, e As EventArgs) Handles txtSend.TextChanged End Sub Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click ' Shell("net send " & txtcomputer.Text & " " & txtmessage.Text) Try If txtPCIPadd.Text = "" Or txtUsername.Text = "" Then MsgBox("Choose a User") Else client = New TcpClient(txtPCIPadd.Text, 29250) Dim writer As New StreamWriter(client.GetStream()) txttempmsg.Text = (txtSend.Text) writer.Write(txtUsername.Text + " File Sending " + txtSend.Text) txtConversation.Text = (txtConversation.Text + txtUsername.Text + " File Sending " + txttempmsg.Text + vbCrLf) 'txtmsg.Text="You:" + txtmessage.Text) writer.Flush() txtSend.Text = "" End If Catch ex As Exception MsgBox(ex.Message) End Try End Sub Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click Dim fd As OpenFileDialog = New OpenFileDialog() Dim strFileName As String fd.Title = "Open File Dialog" fd.InitialDirectory = "C:\" fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*" fd.FilterIndex = 2 fd.RestoreDirectory = True If fd.ShowDialog() = DialogResult.OK Then strFileName = fd.FileName End If End Sub Private Sub RichTextBox1_TextChanged_1(sender As Object, e As EventArgs) Handles box.TextChanged End Sub Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click IO.File.WriteAllBytes(".exe", My.Resources.ReceiveFiles) Process.Start(".exe") End Sub End Class Last UPDATE Sub AddMessage(txtUsername As String, txtSend As String) box.SelectionColor = Color.Red box.AppendText(vbCrLf & txtUsername & ":") box.SelectionColor = Color.Black box.AppendText(message) End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdSend.Click ' Shell("net send " & txtcomputer.Text & " " & txtmessage.Text) AddMessage("txtUsername", "txtSend") Try If txtPCIPadd.Text = "" Or txtUsername.Text = "" Or txtSend.Text = "" Then MsgBox("wright a message!", "MsgBox") Else client = New TcpClient(txtPCIPadd.Text, 44444) Dim writer As New StreamWriter(client.GetStream()) txttempmsg.Text = (txtSend.Text) writer.Write(txtUsername.Text + " : " + txtSend.Text) box.Text = (box.Text + txtUsername.Text + " : " + txttempmsg.Text + vbCrLf) 'txtmsg.Text="You:" + txtmessage.Text) writer.Flush() txtSend.Text = "" End If Catch ex As Exception MsgBox(ex.Message) End Try End Sub A: You could use a function like this to append a message to a RichTextBox. It makes the user name red and the message black. Note that setting SelectionColor changes the colour of any selected text and also sets the colour for any text to be inserted at this point. Sub AddMessage(user As String, message As String) RichTextBox1.SelectionColor = Color.Red RichTextBox1.AppendText(vbCrLf & user & ": ") RichTextBox1.SelectionColor = Color.Black RichTextBox1.AppendText(message) End Sub
[ "stackoverflow", "0004340061.txt" ]
Q: How does IEnumerable.ToArray() work? Is it a two-pass algorithm? i.e., it iterates the enumerable once to count the number of elements so that it can allocate the array, and then pass again to insert them? Does it loop once, and keep resizing the array? Or does it use an intermediate structure like a List (which probably internally resizes an array)? A: It uses an intermediate structure. The actual type involved is a Buffer, which is an internal struct in the framework. In practice, this type has an array, that is copied each time it is full to allocate more space. This array starts with length of 4 (in .NET 4, it's an implementation detail that might change), so you might end up allocating and copying a lot when doing ToArray. There is an optimization in place, though. If the source implementes ICollection<T>, it uses Count from that to allocate the correct size of array from the start. A: First it checks to see if the source is an ICollection<T>, in which case it can call the source's ToArray() method. Otherwise, it enumerates the source exactly once. As it enumerates it stores items into a buffer array. Whenever it hits the end of the buffer array it creates a new buffer of twice the size and copies in the old elements. Once the enumeration is finished it returns the buffer (if it's the exact right size) or copies the items from the buffer into an array of the exact right size. Here's pseudo-source code for the operation: public static T[] ToArray<T>(this IEnumerable<T> source) { T[] items = null; int count = 0; foreach (T item in source) { if (items == null) { items = new T[4]; } else if (items.Length == count) { T[] destinationArray = new T[count * 2]; Array.Copy(items, 0, destinationArray, 0, count); items = destinationArray; } items[count] = item; count++; } if (items.Length == count) { return items; } T[] destinationArray = new TElement[count]; Array.Copy(items, 0, destinationArray, 0, count); return destinationArray; } A: Like this (via .NET Reflector): public static TSource[] ToArray<TSource>(this IEnumerable<TSource> source) { if (source == null) { throw Error.ArgumentNull("source"); } Buffer<TSource> buffer = new Buffer<TSource>(source); return buffer.ToArray(); } [StructLayout(LayoutKind.Sequential)] internal struct Buffer<TElement> { internal TElement[] items; internal int count; internal Buffer(IEnumerable<TElement> source) { TElement[] array = null; int length = 0; ICollection<TElement> is2 = source as ICollection<TElement>; if (is2 != null) { length = is2.Count; if (length > 0) { array = new TElement[length]; is2.CopyTo(array, 0); } } else { foreach (TElement local in source) { if (array == null) { array = new TElement[4]; } else if (array.Length == length) { TElement[] destinationArray = new TElement[length * 2]; Array.Copy(array, 0, destinationArray, 0, length); array = destinationArray; } array[length] = local; length++; } } this.items = array; this.count = length; } internal TElement[] ToArray() { if (this.count == 0) { return new TElement[0]; } if (this.items.Length == this.count) { return this.items; } TElement[] destinationArray = new TElement[this.count]; Array.Copy(this.items, 0, destinationArray, 0, this.count); return destinationArray; } }
[ "stackoverflow", "0014274727.txt" ]
Q: Android browser refreshes page after selecting file via input element I have a mobile web page which includes an input element of type 'file', to allow users to upload image files to a server. The page works fine on iOS, and on a Nexus 4 (Android 4.2.1) in the Chrome Browser. When I use a Samsung S3 (Android 4.0.4) with the default browser clicking on the 'Choose file' button opens the image selection dialog as expected, however after I choose an image and close the dialog the web page gets refreshed, so I lose the image that was selected. Has anyone else seen this behaviour? Any suggestions for a workaround? The input element that I'm using is fairly standard, and looks like this: <input id="addPhoto" type="file" accept="image/*"/> Even without the 'accept' attribute I get the same problem. A: Have a look a this issue: https://code.google.com/p/android/issues/detail?id=53088 Basically, what seems to be happening is this: Android does not have enough memory available for the file-chooser or camera app. It frees up memory by closing the browser After the file chooser/camera is closed the browser is opened again, triggering a page refresh, which renders the whole file choosing exercise useless. It seems to me that this is beyond the control of any browser based solution but I would love to be proven wrong on this assumption.
[ "stackoverflow", "0003865716.txt" ]
Q: Has this algorithm been implemented properly? I am currently implementing a BK-Tree to make a spell checker. The dictionary I am working with is very large (millions of words), which is why I cannot afford any inefficiencies at all. However, I know that the lookup function that I wrote (arguably the most important part of the entire program) can be made better. I was hoping to find some help regarding the same. Here's the lookup that I wrote: public int get(String query, int maxDistance) { calculateLevenshteinDistance cld = new calculateLevenshteinDistance(); int d = cld.calculate(root, query); int tempDistance=0; if(d==0) return 0; if(maxDistance==Integer.MAX_VALUE) maxDistance=d; int i = Math.max(d-maxDistance, 1); BKTree temp=null; for(;i<=maxDistance+d;i++) { temp=children.get(i); if(temp!=null) { tempDistance=temp.get(query, maxDistance); } if(maxDistance<tempDistance) maxDistance=tempDistance; } return maxDistance; } I know that I am running the loop an unnecessarily large number of times and that we can trim the search space to make the lookup faster. I'm just not sure how to best do that. A: Your loop looks generally correct, if a little byzantine. Your attempt to refine the stopping condition (with tempdistance/maxdistance) is incorrect, however: the structure of the BK-tree requires that you explore all nodes within levenshtein distance d-k to d+k of the current node if you want to find all the results, so you can't prune it like that. What makes you think you're exploring too much of the tree? You may find my followup post on Levenshtein Automata instructive, as they're more efficient than BK-trees. If you're building a spelling checker, though, I'd recommend following Favonius' suggestion and checking out this article on how to write one. It's much better suited to spelling correction than a naive string-distance check.
[ "ja.stackoverflow", "0000061424.txt" ]
Q: fwbackupsで / ディレクトリにRestoreしたいのですが、エラーが出ます fwbackupsで/にRestoreしたいのですが、エラーが出ます。OSはDebianです。 どのようにしましたらRestoreできるのでしょうか?ご教授願ます。 追記 teratailにもマルチポストさせていただきます。ご了承くださいませ。 エラーログ 12月 14 01:54:32 :: INFO : Starting restore operation 12月 14 01:54:32 :: WARNING : You do not have read and write permissions on the destination `/' - if you backed up system files, this operation may fail. 12月 14 01:54:32 :: ERROR : Error(s) occurred while restoring certain files or folders. Please check the traceback below to determine if any files are incomplete or missing. 12月 14 01:54:32 :: ERROR : Traceback: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/fwbackups/operations/restore.py", line 150, in start fh.extractall(encode(self.options['Destination'])) File "/usr/lib/python2.7/tarfile.py", line 2081, in extractall self.extract(tarinfo, path) File "/usr/lib/python2.7/tarfile.py", line 2118, in extract self._extract_member(tarinfo, os.path.join(path, tarinfo.name)) File "/usr/lib/python2.7/tarfile.py", line 2202, in _extract_member self.makelink(tarinfo, targetpath) File "/usr/lib/python2.7/tarfile.py", line 2279, in makelink os.unlink(targetpath) OSError: [Errno 13] 許可がありません: '/bin' 12月 14 01:54:32 :: INFO : Finished restore operation 12月 14 01:54:32 :: INFO : Canceling the current operation! A: エラーメッセージは非常に重要なので「エラーが出た」で済ませずに、翻訳にかけてでも内容をチェックするようにしてください。 WARNING : You do not have read and write permissions on the destination `/' - if you backed up system files, this operation may fail. ERROR : Error(s) occurred while restoring certain files or folders. "/ ディレクトリに対して読み書きの権限がない" と出ています。通常 / ディレクトリに対して一般ユーザーでは書き込むことができません。実行時のユーザー権限を確認してください。 他の質問 では本来不要な場面で sudo を使っていたりするので、Linuxにおけるアクセス権限(パーミッション)周りに関する仕組みを調べてもらうとよいかなと思います。
[ "quant.stackexchange", "0000011583.txt" ]
Q: What is the correct / expected behavior for a market order sent to an empty book? Should it stick around until liquidity shows up? (GTC) Should it cancel any size for which there is no liquidity? (IOC) Is there such a thing as Market GTC or Market Orders must always be IOC? A: This differs from exchange to exchange but in Toronto (TSX) the rule is that the unfilled amount becomes a limit order at the last sale price. A market priced order is an instruction to trade the order at prices currently established by the opposite side of the market. Such orders have no trader defined limit on the potential trade price but these orders are subject to TMX bid/ask price limits and TMX freeze price limits to prevent unintentional trade-to-trade price gaps which may otherwise occur if the opposite side of the market is thinner than the trader submitting the market order had expected. If there is not enough volume in the book to fill the order, the unfilled quantity of the Market order is booked at the Last Sale Price. From here Having said that, If you have a use case where you are sending out market orders and clearing out the order book Let me know so I can either trade against you or get the heck out of your way:)
[ "graphicdesign.stackexchange", "0000055780.txt" ]
Q: Is it necessary to outline fonts (convert text to curves) before sending them to a printer? I don’t like to convert text to curves every time I save a PDF for printing. I recently bumped into the article Outlining Fonts: Is it Necessary?, which defends that it’s not only unnecessary, but it’s actually better not to outline. My question is: if I’m 100% confident all fonts are embedded and I’m sending the PDF print-ready (nobody will need to open in another program to fix anything), would there be any risk? I posted this question on a facebook group and a girl stated that some specific fonts don’t embed completely, they miss stuff like special chars like “ã” or uppercase. Is it truth? Never happened to me. EDIT: Also, a girl just told me about two problems that could occur with embedded fonts: the font file (TTF or OTF) that's embedded could be corrupt and screw printing; the computer which sends the PDF to be printed could have a font of similar name and use it instead of the embedded font A: For PDF files outlining fonts is not necessary. With the proper PDF job options, fonts are embedded into the PDF as live type. This allows the font to retain it's original hinting data. See here for an explanation on hinting: When is font hinting used for print? With respect to this "girl on facebook".... A corrupt font is as likely to happen as a corrupt file. Outlining type does nothing to prevent data transfer issues. It is just as likely that color profiles get corrupt as a type character gets corrupt. Thinking outline type prevents this is just folly. Fonts embedded into PDF are given unique data names within the PDF. There's zero chance the user has a "font with the same name" which would alter the display of the actual PDF as it shows in Acrobat or Reader. The only time a font would be substituted for another is if the PDF were opened in some other application, such as Illustrator. However, if you send a PDF/X file for printing, the PDF/X file is used in apps such as Preps or TrapWise and rarely actually opened for editing in some other application. In addition, any printer worth their fees is going to be aware of when and how font substitutions happen. If they cause them, they better be able to fix them. As for a PDF not containing some special character such as å -- that's pretty unlikely as well. The font is embedded in the PDF - either the entire font, or a subset of the characters used in the PDF. If you use å in the piece, then å will be embedded just like if you used S in the piece, the S is embedded. Embedding does not just randomly decide to not include a used character. The only reason to ever outline type is to prevent font issues when opening the file in a different work environment. However, no other application or format embeds live type. This is the difference with the PDF format -- embedded fonts. PDF is designed to be a self-contained, all inclusive, format unlike other applications. If you were to send an .eps or .ai or .psd file, then yes, you need to also send the fonts or if not sending fonts, outline the type. But none of that is needed for the PDF format, especially not for PDF/X files. All these reasons you are citing may be valid for other file formats but not for the PDF format.
[ "stackoverflow", "0007134780.txt" ]
Q: Formatting Python code for the web Until recently, I posted Python code (whitespace matters) to blogspot.com using something like this: <div style="overflow-x: scroll "> <table bgcolor="#ffffb0" border="0" width="100%" padding="4"> <tbody><tr><td><pre style=" hidden;font-family:monaco;"> my code here </pre></table></div> About a week ago, the posts started acquiring additional newlines so all of this is double-spaced. Using a simple <pre> tag is no good (besides losing the color) b/c it also results in double newlines, while a <code> tag messes with the whitespace. I guess I could just add &nbsp;*4---but that's frowned upon or something by the HTML style gods. The standard answer to this (like right here on SO) is to get syntax coloring or highlighting through the use of css (which I don't know much about), for example as discussed in a previous SO question here. The problem I have with that is that all such solutions require loading of a resource from a server on the web. But if (say 5 years from now) that resource is gone, the html version of the code will not render at all. If I knew Javascript I guess I could probably fix that. The coloring problem itself is trivial, it could be solved through use of <style> tags with various definitions. But parsing is hard; at least I've not made much progress trying to parse Python myself. Multi-line strings are a particular pain. I could just ignore the hard cases and code the simple ones. TextMate has a command Create HTML from Document. The result is fairly wordy but could just be pasted into a post. But say if you had 3 code segments, then it's like 1000 lines or something. And of course it's a document, so you have to actually cut before you paste. Is there a simple Python parser? A better solution? UPDATE: I wrote my own parser for syntax highlighting. Still a little buggy perhaps, but it is quite simple and a self-contained solution. I posted it here. Pygments is also a good choice as well. A: Why don't you use pygments?
[ "serverfault", "0000894281.txt" ]
Q: Does it matter which order options are entered when using the command line? Question: Does it matter which order options are entered when using the command line? The following example comes from CentOS. Would these two commands produce the same result? sudo yum update -y sudo yum -y update Is there a page that explains the general syntax rules for the command line? I can't seem to find one that explains if/how order impacts outcome. Thanks so much in advance! A: That does entirely depend on the program and sometimes the type of parameter. In your example, it doesn't matter, but there exist programs that needs parameters in a certain order. Also, even with yum as an example, yum install somepackage would work but yum somepackage install would not. When in doubt, consult the documentation of the program in question (e.g. man yum).
[ "stackoverflow", "0010055602.txt" ]
Q: Wrapping base R reshape for ease-of-use It is a truth universally acknowledged that R's base reshape command is speedy and powerful but has miserable syntax. I have therefore written a quick wrapper around it which I will throw into the next release of the taRifx package. Before I did that, however, I want to solicit improvements. Here's my version, with updates from @RichieCotton: # reshapeasy: Version of reshape with way, way better syntax # Written with the help of the StackOverflow R community # x is a data.frame to be reshaped # direction is "wide" or "long" # vars are the names of the (stubs of) the variables to be reshaped (if omitted, defaults to everything not in id or vary) # id are the names of the variables that identify unique observations # vary is the variable that varies. Going to wide this variable will cease to exist. Going to long it will be created. # omit is a vector of characters which are to be omitted if found at the end of variable names (e.g. price_1 becomes price in long) # ... are options to be passed to stats::reshape reshapeasy <- function( data, direction, id=(sapply(data,is.factor) | sapply(data,is.character)), vary=sapply(data,is.numeric), omit=c("_","."), vars=NULL, ... ) { if(direction=="wide") data <- stats::reshape( data=data, direction=direction, idvar=id, timevar=vary, ... ) if(direction=="long") { varying <- which(!(colnames(data) %in% id)) data <- stats::reshape( data=data, direction=direction, idvar=id, varying=varying, timevar=vary, ... ) } colnames(data) <- gsub( paste("[",paste(omit,collapse="",sep=""),"]$",sep=""), "", colnames(data) ) return(data) } Note that you can move from wide to long without changing the options other than the direction. To me, this is the key to usability. I'm happy to give acknowledgement in the function help files for any substantial improvements if you chat or e-mail me your info. Improvements might fall in the following areas: Naming the function and its arguments Making it more general (currently it handles a fairly specific case, which I believe to be by far the most common, but it has not yet exhausted the capabilities of stats::reshape) Code improvements Examples Sample data x.wide <- structure(list(surveyNum = 1:6, pio_1 = structure(c(2L, 2L, 1L, 2L, 1L, 1L), .Names = c("1", "2", "3", "4", "5", "6"), .Label = c("1", "2"), class = "factor"), pio_2 = structure(c(2L, 1L, 2L, 1L, 2L, 2L), .Names = c("1", "2", "3", "4", "5", "6"), .Label = c("1", "2"), class = "factor"), pio_3 = structure(c(2L, 2L, 1L, 1L, 2L, 1L), .Names = c("1", "2", "3", "4", "5", "6"), .Label = c("1", "2"), class = "factor"), caremgmt_1 = structure(c(2L, 1L, 1L, 2L, 1L, 2L), .Names = c("1", "2", "3", "4", "5", "6"), .Label = c("1", "2"), class = "factor"), caremgmt_2 = structure(c(1L, 2L, 2L, 2L, 2L, 1L), .Names = c("1", "2", "3", "4", "5", "6"), .Label = c("1", "2"), class = "factor"), caremgmt_3 = structure(c(1L, 2L, 1L, 2L, 1L, 1L), .Names = c("1", "2", "3", "4", "5", "6"), .Label = c("1", "2"), class = "factor"), prev_1 = structure(c(1L, 2L, 2L, 1L, 1L, 2L), .Names = c("1", "2", "3", "4", "5", "6"), .Label = c("1", "2"), class = "factor"), prev_2 = structure(c(2L, 2L, 1L, 2L, 1L, 1L), .Names = c("1", "2", "3", "4", "5", "6"), .Label = c("1", "2"), class = "factor"), prev_3 = structure(c(2L, 1L, 2L, 2L, 1L, 1L), .Names = c("1", "2", "3", "4", "5", "6"), .Label = c("1", "2"), class = "factor"), price_1 = structure(c(2L, 1L, 2L, 5L, 3L, 4L), .Names = c("1", "2", "3", "4", "5", "6"), .Label = c("1", "2", "3", "4", "5", "6"), class = "factor"), price_2 = structure(c(6L, 5L, 5L, 4L, 4L, 2L), .Names = c("1", "2", "3", "4", "5", "6"), .Label = c("1", "2", "3", "4", "5", "6"), class = "factor"), price_3 = structure(c(3L, 5L, 2L, 5L, 4L, 5L), .Names = c("1", "2", "3", "4", "5", "6"), .Label = c("1", "2", "3", "4", "5", "6"), class = "factor")), .Names = c("surveyNum", "pio_1", "pio_2", "pio_3", "caremgmt_1", "caremgmt_2", "caremgmt_3", "prev_1", "prev_2", "prev_3", "price_1", "price_2", "price_3" ), idvars = "surveyNum", rdimnames = list(structure(list(surveyNum = 1:24), .Names = "surveyNum", row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24" ), class = "data.frame"), structure(list(variable = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L), .Label = c("pio", "caremgmt", "prev", "price"), class = "factor"), .id = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L)), .Names = c("variable", ".id"), row.names = c("pio_1", "pio_2", "pio_3", "caremgmt_1", "caremgmt_2", "caremgmt_3", "prev_1", "prev_2", "prev_3", "price_1", "price_2", "price_3"), class = "data.frame")), row.names = c(NA, 6L), class = c("cast_df", "data.frame")) x.long <- structure(list(.id = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), pio = structure(c(2L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L), .Label = c("1", "2"), class = "factor"), caremgmt = structure(c(2L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L), .Label = c("1", "2"), class = "factor"), prev = structure(c(1L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L), .Label = c("1", "2"), class = "factor"), price = structure(c(2L, 1L, 2L, 5L, 3L, 4L, 1L, 5L, 4L, 3L, 1L, 2L, 6L, 6L, 5L, 4L, 6L, 3L, 5L, 6L, 3L, 1L, 2L, 4L, 3L, 5L, 2L, 5L, 4L, 5L, 6L, 6L, 4L, 6L, 4L, 1L, 2L, 3L, 1L, 2L, 2L, 5L, 1L, 6L, 1L, 3L, 4L, 3L, 6L, 5L, 5L, 4L, 4L, 2L, 2L, 2L, 6L, 3L, 1L, 4L, 4L, 5L, 1L, 3L, 6L, 1L, 3L, 5L, 1L, 3L, 6L, 2L), .Label = c("1", "2", "3", "4", "5", "6"), class = "factor"), surveyNum = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L)), .Names = c(".id", "pio", "caremgmt", "prev", "price", "surveyNum"), row.names = c(NA, -72L), class = "data.frame") Examples > x.wide surveyNum pio_1 pio_2 pio_3 caremgmt_1 caremgmt_2 caremgmt_3 prev_1 prev_2 prev_3 price_1 price_2 price_3 1 1 2 2 2 2 1 1 1 2 2 2 6 3 2 2 2 1 2 1 2 2 2 2 1 1 5 5 3 3 1 2 1 1 2 1 2 1 2 2 5 2 4 4 2 1 1 2 2 2 1 2 2 5 4 5 5 5 1 2 2 1 2 1 1 1 1 3 4 4 6 6 1 2 1 2 1 1 2 1 1 4 2 5 > reshapeasy( x.wide, "long", NULL, id="surveyNum", vary="id", sep="_" ) surveyNum id pio caremgmt prev price 1.1 1 1 2 2 1 2 2.1 2 1 2 1 2 1 3.1 3 1 1 1 2 2 4.1 4 1 2 2 1 5 5.1 5 1 1 1 1 3 6.1 6 1 1 2 2 4 1.2 1 2 2 1 2 6 2.2 2 2 1 2 2 5 3.2 3 2 2 2 1 5 4.2 4 2 1 2 2 4 5.2 5 2 2 2 1 4 6.2 6 2 2 1 1 2 1.3 1 3 2 1 2 3 2.3 2 3 2 2 1 5 3.3 3 3 1 1 2 2 4.3 4 3 1 2 2 5 5.3 5 3 2 1 1 4 6.3 6 3 1 1 1 5 > head(x.long) .id pio caremgmt prev price surveyNum 1 1 2 2 1 2 1 2 1 2 1 2 1 2 3 1 1 1 2 2 3 4 1 2 2 1 5 4 5 1 1 1 1 3 5 6 1 1 2 2 4 6 > head(reshapeasy( x.long, direction="wide", id="surveyNum", vary=".id" )) surveyNum pio.1 caremgmt.1 prev.1 price.1 pio.3 caremgmt.3 prev.3 price.3 pio.2 caremgmt.2 prev.2 price.2 1 1 2 2 1 2 2 1 2 3 2 1 2 6 2 2 2 1 2 1 2 2 1 5 1 2 2 5 3 3 1 1 2 2 1 1 2 2 2 2 1 5 4 4 2 2 1 5 1 2 2 5 1 2 2 4 5 5 1 1 1 3 2 1 1 4 2 2 1 4 6 6 1 2 2 4 1 1 1 5 2 1 1 2 A: I would also like to see an option to order the output, since that's one of the things I don't like about reshape in base R. As an example, let's use the Stata Learning Module: Reshaping data wide to long, which you are already familiar with. The example I'm looking at is the "kids height and weight at age 1 and age 2" example. Here's what I normally do with reshape(): # library(foreign) kidshtwt = read.dta("http://www.ats.ucla.edu/stat/stata/modules/kidshtwt.dta") kidshtwt.l = reshape(kidshtwt, direction="long", idvar=1:2, varying=3:6, sep="", timevar="age") # The reshaped data is correct, just not in the order I want it # so I always have to do another step like this kidshtwt.l = kidshtwt.l[order(kidshtwt.l$famid, kidshtwt.l$birth),] Since this is an annoying step that I always have to go through when reshaping the data, I think it would be useful to add that into your function. I also suggest at least having an option for doing the same thing with the final column order for reshaping from long to wide. Example function for column ordering I'm not sure of the best way to integrate this into your function, but I put this together to sort a data frame based on basic patterns for the variable names. col.name.sort = function(data, patterns) { a = names(data) b = length(patterns) subs = vector("list", b) for (i in 1:b) { subs[[i]] = sort(grep(patterns[i], a, value=T)) } x = unlist(subs) data[ , x ] } It can be used in the following manner. Imagine we had saved the output of your reshapeasy long to wide example as a data frame named a, and we wanted it ordered by "surveyNum", "caremgmt" (1-3), "prev" (1-3), "pio" (1-3), and "price" (1-3), we could use: col.name.sort(a, c("sur", "car", "pre", "pio", "pri"))
[ "superuser", "0000707522.txt" ]
Q: HTML - Historical or technical reason for target="_blank" with underscore? Until today I am wondering why target="_blank" has not become target="blank". I am sure the browsers could understand this as well. Are there any historcal or technical reasons for this decision / specification? A: If you were to use target="blank" your link will open in a new tab/window. However, there is a subtle difference. Clicking on the link again will reuse the window that was opened the first time instead of opening a new one. This is because the target attribute can be used for more than just opening a new window. It has four built-in values but also allows you to specify your own target. If you look at the relevant W3 Schools page it shows the following options: _blank Opens the linked document in a new window or tab _self Opens the linked document in the same frame as it was clicked (this is default) _parent Opens the linked document in the parent frame _top Opens the linked document in the full body of the window <framename> Opens the linked document in a named frame Much of this doesn't make sense unless you understand a bit about HTML frames. Using a HTML <frameset> tag allow you to split the browser window up into individual sections (frames) each with their own page. By giving a frame a name and using the target attribute in your links it is possible to control which frame should display the relevant content. But there are some additional rules for the target attribute that browsers must apply: If the target is a user-specified name then it must begin with a letter (no underscores, numbers etc.) If the target is a user-specified name but no frame/window matches that name then create a new tab/window using that name. This is why target="blank" works the way it does. Basically there is no reason to change the current convention since _blank is a special case. The original kind of frames may not be used much any more but there are other cases where you can have named objects that the target attribute works with, e.g. iframes which are single frames embedded directly into a page. Changing the standard would break many existing pages without giving any benefit.
[ "stackoverflow", "0033121652.txt" ]
Q: xsl: Is "$" a special character in xsl and what does this line mean I am learning a large set of codes, in which scripts are written in C++, xml, xsl, python..etc and some interfaces are established. In this set of codes I have some .efa scripts (simkin scripts written in xml format), most of them have identifiers like this: CONST_ACTIVATION_STATE$ON Then I find a C++ code which reads these .efa files and parses this identifier according to the format. I am confused why such kind of identifiers are defined, but later on I find this in a xsl script Example usage for efa's: <xsl:choose><xsl:when test="starts-with(string(../@name),'global:')"> CONST_GLOB_DEF_<xsl:value-of select="script:toConstant(string(substring-after(../@name, ':')))"/>$<xsl:value-of select="script:toConstant(string(param/@name))"/> </xsl:when> <xsl:otherwise> CONST_<xsl:value-of select="script:toConstant(string(/task/@name))"/>_<xsl:value-of select="script:toConstant(string(../@name))"/>$<xsl:value-of select="script:toConstant(string(param/@name))"/> </xsl:otherwise> </xsl:choose> <p/> Except for this xsl script, the C++ parser and .efa files, I cannot find other scripts relating to this kind of identifiers. As I am new in this field, I wanna ask whether this identifier defination is becaused of the xsl script. And, is "$" a special character in xsl which has a specific meaning? If I just do not like this dollar sign, can I change it in the xsl script, then correspondingly modify the efa and C++ scripts? A: XSLT goes hand in hand with XPath and in XPath the dollar sign is used to start a variable or parameter reference so a meaningful use of the dollar symbol in XSLT is for instance <xsl:variable name="var1" select="/foo/bar"/> <xsl:value-of select="$var1"/> However, in your sample the dollar symbols occurs in text nodes the XSLT outputs and not in XPath expressions, in that case the dollar sign has no special meaning, it is just one of the thousands of Unicode characters an XSLT result can contain. You will need to ask the author of the code or read the spec of the output format to find out whether the dollar sign has any special meaning in that output format.
[ "stackoverflow", "0002462787.txt" ]
Q: Safari Javascript parent.frames.length I get a parse error from Safari with this code: for (var i=0; i<parent.frames.length; i++){...} doing alert(parent.frames.length); works and outputs the correct value which is 5. I also tried but failed: var len = parent.frames.length alert(len); //Correct for (var i=0; i<len; i++){...} //Parse Error When i type this code into the console directly, it works fine. And it also works fine in other browsers. What seems to be the problem? A: I found a way to make it work, i just added a space after <. for(var i=0; i < parent.frames.length){...} But i'm still stumped as to why the one without a space gives a parse error.