id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
28,284,105
Font awesome icon and text in input submit button?
<p>I have a similar problem like <a href="https://stackoverflow.com/questions/11686007/font-awesome-input-type-submit#answer-22478072">here</a> , i want to place font awesome icon into my submit button and also a text, it looks so: <a href="http://prntscr.com/608exx" rel="noreferrer">http://prntscr.com/608exx</a></p> <p>Content of my input submit value is Buy now <code>&amp;nbsp;&amp;#xf07a;</code></p> <p>The icon is visible because i set on input field <code>font-family: FontAwesome;</code> my question is, how can i set on my text inside the button standard font family?</p>
28,284,294
3
0
null
2015-02-02 18:16:00.943 UTC
4
2020-12-03 12:52:23.153 UTC
2017-05-23 12:17:14.027 UTC
null
-1
null
3,436,969
null
1
33
html|fonts|submit
67,767
<p>Try </p> <pre><code>&lt;button type="submit" class="btn btn-default"&gt; &lt;i class="fa fa-shopping-cart"&gt;&lt;/i&gt; Buy Now &lt;/button&gt; </code></pre>
8,912,659
Multiple level nesting in YAML
<p>I'm trying to use YAML to create list of all stored procs used in an application and from where they are called. I envisioned something like below but I think YAML does not allow multiple level nesting. </p> <pre><code>access_log: stored_proc: getsomething uses: usedin: some-&gt;bread-&gt;crumb usedin: something else here stored_proc: anothersp uses: usedin: blahblah reporting: stored_proc: reportingsp uses: usedin: breadcrumb </code></pre> <p>Is there a way to do this in YAML and if not, what other alternatives are there?</p>
8,912,842
3
0
null
2012-01-18 15:22:56.077 UTC
3
2021-11-15 15:07:29.993 UTC
2012-01-18 19:29:44.46 UTC
null
405,017
null
654,203
null
1
24
ruby|yaml
56,416
<p>That's exactly how I've used nested levels in YAML for configuration files for perl scripts. <a href="http://rhnh.net/2011/01/31/yaml-tutorial" rel="nofollow noreferrer">This YAML Tutorial</a> might be a good reference for you on how to handle the structure you want in Ruby.</p> <p>I think your problem is trying to mix types. I suggest revising like this:</p> <pre><code>reporting: stored_procs: - name: reportingsp uses: usedin: breadcrumb - name: secondProc uses: usedin: something_else </code></pre>
8,985,295
EditText setError() with icon but without Popup message
<p>I want to to have some validation for my EditText wherein I want to show "<a href="https://i.stack.imgur.com/1luXA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1luXA.png" alt="enter image description here"></a>" icon (that comes when you put <code>editText.setError("blah blah"))</code> but don't want the text in the popup displaying that "blah blah".</p> <p>Is there any way to do it? One way is to create a custom layout which will show the image icon in the EditText. But is there any better solution?</p>
9,161,958
6
0
null
2012-01-24 10:34:06.21 UTC
17
2018-04-04 05:09:33.93 UTC
2016-07-13 12:19:41.993 UTC
null
4,414,557
null
840,669
null
1
39
android|android-edittext
68,437
<p>Problem solved after a lot of research and permutations- (Also thanks to @van)</p> <p>Create a new class that will extend <code>EditText</code> something like this-</p> <pre><code>public class MyEditText extends EditText { public MyEditText(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void setError(CharSequence error, Drawable icon) { setCompoundDrawables(null, null, icon, null); } } </code></pre> <p>Use this class as a view in your xml like this-</p> <pre><code>&lt;com.raj.poc.MyEditText android:id="@+id/et_test" android:layout_width="fill_parent" android:layout_height="wrap_content"/&gt; </code></pre> <p>Now in the third step, just set a <code>TextWatcher</code> to your custom text view like this-</p> <pre><code> et = (MyEditText) findViewById(R.id.et_test); errorIcon = getResources().getDrawable(R.drawable.ic_error); errorIcon.setBounds(new Rect(0, 0, errorIcon.getIntrinsicWidth(), errorIcon.getIntrinsicHeight())); et.setError(null,errorIcon); et.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { if(s.toString().length()&gt;6){ et.setError("", null); }else{ et.setError("", errorIcon); } } }); </code></pre> <p>where <code>R.drawable.ic_error</code> = <img src="https://i.stack.imgur.com/1luXA.png" /></p> <p>Keeping text null solves the problem But if we keep only null in setError(null), this won't show the validation error; it should be null along with second param.</p>
8,509,723
Select something that has more/less than x character
<p>Was wondering if it's possible to select something that has more/less than x characters in SQL.</p> <p>For example, I have an employee table and I want to show all employee names that has more than 4 characters in their name.</p> <p>Here's an example table</p> <pre><code>ID EmpName Dept 1 Johnny ACC 2 Dan IT 3 Amriel PR 4 Amy HR </code></pre>
8,509,736
4
0
null
2011-12-14 18:26:25.4 UTC
15
2020-07-01 15:56:07.703 UTC
2016-08-31 07:13:05.737 UTC
null
2,223,706
null
704,677
null
1
144
sql
461,767
<p>If you are using SQL Server, Use the <code>LEN</code> (Length) function:</p> <pre><code>SELECT EmployeeName FROM EmployeeTable WHERE LEN(EmployeeName) &gt; 4 </code></pre> <p>MSDN for it states:</p> <blockquote> <p>Returns the number of characters of the specified string expression,<br> excluding trailing blanks.</p> </blockquote> <p><a href="http://msdn.microsoft.com/en-us/library/ms190329.aspx" rel="noreferrer">Here's the link to the MSDN</a></p> <p>For oracle/plsql you can use <code>Length()</code>, mysql also uses Length.</p> <p>Here is the Oracle documentation:</p> <p><a href="http://www.techonthenet.com/oracle/functions/length.php" rel="noreferrer">http://www.techonthenet.com/oracle/functions/length.php</a></p> <p>And here is the mySQL Documentation of <code>Length(string)</code>:</p> <p><a href="http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_length" rel="noreferrer">http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_length</a></p> <p>For PostgreSQL, you can use <code>length(string)</code> or <code>char_length(string)</code>. Here is the PostgreSQL documentation:</p> <p><a href="http://www.postgresql.org/docs/current/static/functions-string.html#FUNCTIONS-STRING-SQL" rel="noreferrer">http://www.postgresql.org/docs/current/static/functions-string.html#FUNCTIONS-STRING-SQL</a></p>
47,665,886
VS Code will not build c++ programs with multiple .ccp source files
<p>Note that I'm using VS Code on Ubuntu 17.10 and using the GCC Compiler.</p> <p>I'm having trouble building a simple program which makes use of additional .ccp files. I'm probably missing something obvious here as I'm fairly new to programming but I'll explain what I've done so far. This is something that is stopping me from continuing with a tutorial I'm doing.</p> <p>I have written a very simple program to demonstrate my point as follows.</p> <h1>main.ccp</h1> <hr /> <pre><code>#include &lt;iostream&gt; #include &quot;Cat.h&quot; using namespace std; int main () { speak(); return 0; } </code></pre> <h1>Cat.h</h1> <hr /> <pre><code>#pragma once void speak(); </code></pre> <h1>Cat.ccp</h1> <hr /> <pre><code>#include &lt;iostream&gt; #include &quot;Cat.h&quot; using namespace std; void speak() { std::cout &lt;&lt; &quot;Meow!!&quot; &lt;&lt; std::endl; } </code></pre> <p>This simple program builds in both Codeblocks and Visual Studio Community 2017 no problem and I can't figure out what I need to do to make it run. This error at the bottom indicates that the Cat.ccp file is not being picked up at all. If I was to drop the definition from this Cat.ccp into the header file the program compiles and runs fine but I need to make use of that .ccp file as I understand this is the accepted way of separating code. I'll note that all the files are in the same folder too.</p> <p>I understand that I may need to tell VS Code where to look for the Cat.ccp file but it's strange to me that it finds the header in the same location. Nevertheless, after looking online I've been reading that I may need to place a directory into the c_cpp_intellisense_properties.json. Here's what mine looks like.</p> <pre><code>{ &quot;configurations&quot;: [ { &quot;name&quot;: &quot;Mac&quot;, &quot;includePath&quot;: [ &quot;/usr/include&quot;, &quot;/usr/local/include&quot;, &quot;${workspaceRoot}&quot; ], &quot;defines&quot;: [], &quot;intelliSenseMode&quot;: &quot;clang-x64&quot;, &quot;browse&quot;: { &quot;path&quot;: [ &quot;/usr/include&quot;, &quot;/usr/local/include&quot;, &quot;${workspaceRoot}&quot; ], &quot;limitSymbolsToIncludedHeaders&quot;: true, &quot;databaseFilename&quot;: &quot;&quot; }, &quot;macFrameworkPath&quot;: [ &quot;/System/Library/Frameworks&quot;, &quot;/Library/Frameworks&quot; ] }, { &quot;name&quot;: &quot;Linux&quot;, &quot;includePath&quot;: [ &quot;/usr/include/c++/7&quot;, &quot;/usr/include/x86_64-linux-gnu/c++/7&quot;, &quot;/usr/include/c++/7/backward&quot;, &quot;/usr/lib/gcc/x86_64-linux-gnu/7/include&quot;, &quot;/usr/local/include&quot;, &quot;/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed&quot;, &quot;/usr/include/x86_64-linux-gnu&quot;, &quot;/usr/include&quot;, &quot;/home/danny/Documents/C++_Projects/24_-_Classes/Cat.cpp&quot;, &quot;${workspaceRoot}&quot;, &quot;/home/danny/Documents/C++_Projects/24_-_Classes/&quot;, &quot;/home/danny/Documents/C++_Projects/24_-_Classes/.vscode&quot;, &quot;/home/danny/Documents/C++_Projects/24_-_Classes/.vscode/Cat.cpp&quot; ], &quot;defines&quot;: [], &quot;intelliSenseMode&quot;: &quot;clang-x64&quot;, &quot;browse&quot;: { &quot;path&quot;: [ &quot;/usr/include/c++/7&quot;, &quot;/usr/include/x86_64-linux-gnu/c++/7&quot;, &quot;/usr/include/c++/7/backward&quot;, &quot;/usr/lib/gcc/x86_64-linux-gnu/7/include&quot;, &quot;/usr/local/include&quot;, &quot;/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed&quot;, &quot;/usr/include/x86_64-linux-gnu&quot;, &quot;/usr/include&quot;, &quot;${workspaceRoot}&quot;, &quot;/home/danny/Documents/C++_Projects/24_-_Classes/&quot;, &quot;/home/danny/Documents/C++_Projects/24_-_Classes/.vscode/Cat.cpp&quot; ], &quot;limitSymbolsToIncludedHeaders&quot;: true, &quot;databaseFilename&quot;: &quot;&quot; } }, { &quot;name&quot;: &quot;Win32&quot;, &quot;includePath&quot;: [ &quot;C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/include&quot;, &quot;${workspaceRoot}&quot; ], &quot;defines&quot;: [ &quot;_DEBUG&quot;, &quot;UNICODE&quot; ], &quot;intelliSenseMode&quot;: &quot;msvc-x64&quot;, &quot;browse&quot;: { &quot;path&quot;: [ &quot;C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/include/*&quot;, &quot;${workspaceRoot}&quot; ], &quot;limitSymbolsToIncludedHeaders&quot;: true, &quot;databaseFilename&quot;: &quot;&quot; } } ], &quot;version&quot;: 3 } </code></pre> <p>At one point I wondered if I need to add a double command in there to tell the compiler to build both .ccp files in the <em>tasks.json</em> but I haven't managed to figure out how to do that, or even if that's the right approach.</p> <h1>tasks.json</h1> <hr /> <pre><code>{ // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format &quot;version&quot;: &quot;2.0.0&quot;, &quot;tasks&quot;: [ { &quot;label&quot;: &quot;Build&quot;, &quot;type&quot;: &quot;shell&quot;, &quot;command&quot;: &quot;g++ -g /home/danny/Documents/C++_Projects/24_-_Classes/main.cpp -o Classes&quot;, &quot;group&quot;: { &quot;kind&quot;: &quot;build&quot;, &quot;isDefault&quot;: true }, &quot;problemMatcher&quot;:&quot;$gcc&quot; } ] } </code></pre> <p>Appreciate any help. And just in case you're wondering, the reason I don't just finish the tutorial in Codeblocks or VS Community is that I like to know what's going on under the hood in most things. Plus I'd like to get VS Code working for me as it's been great so far.</p>
59,236,875
14
1
null
2017-12-06 02:29:51.273 UTC
22
2022-08-12 11:39:50.733 UTC
2022-03-18 00:11:40.757 UTC
null
5,782,522
null
5,782,522
null
1
41
c++|linux|ubuntu|gcc|visual-studio-code
73,119
<p>in tasks.json:</p> <pre><code> "label": "g++.exe build active file", "args": [ "-g", "${fileDirname}\\**.cpp", //"${fileDirname}\\**.h", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe", ], </code></pre> <p>in launch.json:</p> <pre><code>"preLaunchTask": "g++.exe build active file" </code></pre> <p>it will work if your sources are in separated folder</p>
53,861,302
Passing data between screens in Flutter
<p>As I'm learning Flutter I've come to navigation. I want to pass data between screens similarly to <a href="https://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application">passing data between Activities in Android</a> and <a href="https://stackoverflow.com/questions/5210535/passing-data-between-view-controllers">passing data between View Controllers in iOS</a>. How do I do it in Flutter?</p> <p>Related questions:</p> <ul> <li><a href="https://stackoverflow.com/questions/48910814/the-best-way-to-passing-data-between-widgets-in-flutter">The best way to passing data between widgets in Flutter</a></li> <li><a href="https://stackoverflow.com/questions/53391246/flutter-pass-data-between-widgets">Flutter pass data between widgets?</a></li> <li><a href="https://stackoverflow.com/questions/50245348/flutter-how-to-pass-and-get-data-between-statefulwidget?rq=1">Flutter/ How to pass and get data between Statefulwidget</a></li> </ul>
53,861,303
11
6
null
2018-12-20 01:21:07.607 UTC
58
2022-06-11 15:47:53.19 UTC
2019-05-06 15:24:05.64 UTC
null
3,681,880
null
3,681,880
null
1
109
dart|flutter|flutter-navigation
190,660
<p>This answer will cover both passing data forward and passing data back. Unlike Android Activities and iOS ViewControllers, different screens in Flutter are just widgets. Navigating between them involves creating something called a route and using the <code>Navigator</code> to push and pop the routes on and off the stack.</p> <h1>Passing data forward to the next screen</h1> <p><a href="https://i.stack.imgur.com/KcrwL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KcrwL.png" alt="enter image description here"></a></p> <p>To send data to the next screen you do the following things:</p> <ol> <li><p>Make the <code>SecondScreen</code> constructor take a parameter for the type of data that you want to send to it. In this particular example, the data is defined to be a <code>String</code> value and is set here with <code>this.text</code>.</p> <pre><code>class SecondScreen extends StatelessWidget { final String text; SecondScreen({Key key, @required this.text}) : super(key: key); ... </code></pre></li> <li><p>Then use the <code>Navigator</code> in the <code>FirstScreen</code> widget to push a route to the <code>SecondScreen</code> widget. You put the data that you want to send as a parameter in its constructor. </p> <pre><code>Navigator.push( context, MaterialPageRoute( builder: (context) =&gt; SecondScreen(text: 'Hello',), )); </code></pre></li> </ol> <p>The full code for <code>main.dart</code> is here:</p> <pre><code>import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( title: 'Flutter', home: FirstScreen(), )); } class FirstScreen extends StatefulWidget { @override _FirstScreenState createState() { return _FirstScreenState(); } } class _FirstScreenState extends State&lt;FirstScreen&gt; { // this allows us to access the TextField text TextEditingController textFieldController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('First screen')), body: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.all(32.0), child: TextField( controller: textFieldController, style: TextStyle( fontSize: 24, color: Colors.black, ), ), ), RaisedButton( child: Text( 'Go to second screen', style: TextStyle(fontSize: 24), ), onPressed: () { _sendDataToSecondScreen(context); }, ) ], ), ); } // get the text in the TextField and start the Second Screen void _sendDataToSecondScreen(BuildContext context) { String textToSend = textFieldController.text; Navigator.push( context, MaterialPageRoute( builder: (context) =&gt; SecondScreen(text: textToSend,), )); } } class SecondScreen extends StatelessWidget { final String text; // receive data from the FirstScreen as a parameter SecondScreen({Key key, @required this.text}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Second screen')), body: Center( child: Text( text, style: TextStyle(fontSize: 24), ), ), ); } } </code></pre> <h1>Passing data back to the previous screen</h1> <p><a href="https://i.stack.imgur.com/cspnX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cspnX.png" alt="enter image description here"></a></p> <p>When passing data back you need to do the following things:</p> <ol> <li><p>In the <code>FirstScreen</code>, use the <code>Navigator</code> to push (start) the <code>SecondScreen</code> in an <code>async</code> method and wait for the result that it will return when it finishes.</p> <pre><code>final result = await Navigator.push( context, MaterialPageRoute( builder: (context) =&gt; SecondScreen(), )); </code></pre></li> <li><p>In the <code>SecondScreen</code>, include the data that you want to pass back as a parameter when you pop the <code>Navigator</code>.</p> <pre><code>Navigator.pop(context, 'Hello'); </code></pre></li> <li><p>Then in the <code>FirstScreen</code> the <code>await</code> will finish and you can use the result.</p> <pre><code>setState(() { text = result; }); </code></pre></li> </ol> <p>Here is the complete code for <code>main.dart</code> for your reference.</p> <pre><code>import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( title: 'Flutter', home: FirstScreen(), )); } class FirstScreen extends StatefulWidget { @override _FirstScreenState createState() { return _FirstScreenState(); } } class _FirstScreenState extends State&lt;FirstScreen&gt; { String text = 'Text'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('First screen')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.all(32.0), child: Text( text, style: TextStyle(fontSize: 24), ), ), RaisedButton( child: Text( 'Go to second screen', style: TextStyle(fontSize: 24), ), onPressed: () { _awaitReturnValueFromSecondScreen(context); }, ) ], ), ), ); } void _awaitReturnValueFromSecondScreen(BuildContext context) async { // start the SecondScreen and wait for it to finish with a result final result = await Navigator.push( context, MaterialPageRoute( builder: (context) =&gt; SecondScreen(), )); // after the SecondScreen result comes back update the Text widget with it setState(() { text = result; }); } } class SecondScreen extends StatefulWidget { @override _SecondScreenState createState() { return _SecondScreenState(); } } class _SecondScreenState extends State&lt;SecondScreen&gt; { // this allows us to access the TextField text TextEditingController textFieldController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Second screen')), body: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.all(32.0), child: TextField( controller: textFieldController, style: TextStyle( fontSize: 24, color: Colors.black, ), ), ), RaisedButton( child: Text( 'Send text back', style: TextStyle(fontSize: 24), ), onPressed: () { _sendDataBack(context); }, ) ], ), ); } // get the text in the TextField and send it back to the FirstScreen void _sendDataBack(BuildContext context) { String textToSendBack = textFieldController.text; Navigator.pop(context, textToSendBack); } } </code></pre>
43,492,519
How to put a component inside another component in Angular2?
<p>I'm new at Angular and I'm still trying to understand it. I've followed the course on the Microsoft Virtual Academy and it was great, but I found a little discrepancy between what they said and how my code behave! Specifically, I've tried to "put a component inside another component" like this:</p> <pre class="lang-ts prettyprint-override"><code>@Component({ selector: 'parent', directives: [ChildComponent], template: ` &lt;h1&gt;Parent Component&lt;/h1&gt; &lt;child&gt;&lt;/child&gt; ` }) export class ParentComponent{} @Component({ selector: 'child', template: ` &lt;h4&gt;Child Component&lt;/h4&gt; ` }) export class ChildComponent{} </code></pre> <p>This is the same example that they make on the course, but in my code doesn't work! In particular VisualStudio says to me that the 'directives' property doesn't exist in the component decorator. How can I solve this? </p>
43,492,670
3
0
null
2017-04-19 10:04:22.607 UTC
12
2018-02-19 22:39:59.313 UTC
2017-04-19 11:26:04.147 UTC
null
573,032
null
6,300,872
null
1
58
angular|angular2-directives
207,334
<p>You <em>don't put</em> a component in <code>directives</code></p> <p>You <em>register</em> it in <code>@NgModule</code> declarations:</p> <pre><code>@NgModule({ imports: [ BrowserModule ], declarations: [ App , MyChildComponent ], bootstrap: [ App ] }) </code></pre> <p>and then You just put it in the Parent's Template HTML as : <code>&lt;my-child&gt;&lt;/my-child&gt;</code></p> <p>That's it.</p>
770,173
How to get Excel instance or Excel instance CLSID using the Process ID?
<p>I'm working with C#, I need to obtain a specific instance of excel by it's process ID; I get the Process ID of the instance that I need from another application but I don't know what else to do, I don't know how can I get a running instance of excel given his process ID.</p> <p>I have researched a lot on the web, but I have only see examples of using Marshal.GetActiveObject(...) or Marshal.BindToMoniker(...), which I can't use since the first one returns the first Excel instance registered in the ROT and not precisely the one that I need, and the second one requires that you save the excel file before trying to get the instance.</p> <p>Also, if I where able to get the CLSID of the excel instance that I need, using the process ID, then I may be able to call </p> <pre><code>GetActiveObject(ref _guid, _ptr, out objApp);</code></pre> <p>that ultimately will return the excel instance that I need.</p>
770,327
3
1
null
2009-04-20 21:27:57.453 UTC
9
2009-04-20 22:30:57.117 UTC
null
null
null
null
58,434
null
1
13
c#|excel
15,339
<p>Once you identify the process via the process id, you can get the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.mainwindowhandle.aspx" rel="noreferrer">Process.MainWindowHandle</a> and then use that along with the <a href="http://msdn.microsoft.com/en-us/library/dd317978(VS.85).aspx" rel="noreferrer">AccessibleObjectFromWindow API</a> to get access to the Excel object model for that process.</p> <p>The article <a href="http://blogs.officezealot.com/whitechapel/archive/2005/04/10/4514.aspx" rel="noreferrer">Getting the Application Object in a Shimmed Automation Add-in</a> by Andrew Whitechapel describes this technique in detail, along with sample code.</p> <p>The key code in that article for you begins at the line:</p> <pre><code>int hwnd = (int)Process.GetCurrentProcess().MainWindowHandle </code></pre> <p>Which in your case might look more like:</p> <pre><code>int excelId = 1234; // Change as appropriate! int hwnd = (int)Process.GetProcessById(excelId).MainWindowHandle </code></pre> <p>where the 'excelId' is the process id number that you are looking for. Otherwise, the code should be essentially the same as given in the article. (Ignore the fact that his code is written for an add-in; that aspect won't affect your needs here, so just ignore it.)</p> <p>If you do not have the process id, then you you would want to use <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getprocessesbyname.aspx" rel="noreferrer">Process.GetProcessesByName</a>, whereby you could enumerate each one and grab control of each Excel instance with access to the object model, as needed.</p> <p>Hope this helps,</p> <p>Mike</p>
358,382
Where did Open Table go in SQL Server 2008?
<p>As of SQL Server 2005, you used to be able to open a flat file in SQL Management Studio off the right click menu for any database table. Once opened, you could add or update records right there in the grid.</p> <p>Now that SQL Server 2008 is out, Microsoft has hidden that feature, at least from the right-click menu.</p> <p>Where did it go?</p>
358,417
3
0
null
2008-12-11 03:38:20.823 UTC
5
2011-12-07 14:53:35.037 UTC
2009-01-28 16:39:53.41 UTC
Fabian Steeg
18,154
John Dunagan
28,939
null
1
26
sql|database|sql-server-2008
96,727
<p>It's replaced by "Edit Top 200 Rows". You can change that command in the Tools > Options > SQL Server Object Explorer > Commands.</p> <p>But once you right-click a table, choose "Edit Top 200 Rows", hunt on the toolbar for a button called "Show SQL Pane". From here you can edit the query so the grid shows a subset of the data that you want.</p> <p>They did this because people were accidentally opening huge tables with the old Open Table command. This method seems to work pretty well, though in general I find that the 2008 version is pretty wonky when talking to 2005 databases, but that's another matter....</p>
842,737
Cocoa Custom Notification Example
<p>Can someone please show me an example of a Cocoa Obj-C object, with a custom notification, how to fire it, subscribe to it, and handle it?</p>
842,764
3
3
null
2009-05-09 05:10:24.923 UTC
30
2014-06-06 04:38:13.787 UTC
2014-06-06 04:38:13.787 UTC
null
437,679
null
65,890
null
1
70
objective-c|cocoa|notifications
50,042
<pre><code>@implementation MyObject // Posts a MyNotification message whenever called - (void)notify { [[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:self]; } // Prints a message whenever a MyNotification is received - (void)handleNotification:(NSNotification*)note { NSLog(@"Got notified: %@", note); } @end // somewhere else MyObject *object = [[MyObject alloc] init]; // receive MyNotification events from any object [[NSNotificationCenter defaultCenter] addObserver:object selector:@selector(handleNotification:) name:@"MyNotification" object:nil]; // create a notification [object notify]; </code></pre> <p>For more information, see the documentation for <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html#//apple_ref/doc/uid/20000219-2831" rel="noreferrer">NSNotificationCenter</a>.</p>
1,048,199
Easiest way to read from a URL into a string in .NET
<p>Given a URL in a string:</p> <pre><code>http://www.example.com/test.xml </code></pre> <p>What's the easiest/most succinct way to download the contents of the file from the server (pointed to by the url) into a string in C#?</p> <p>The way I'm doing it at the moment is:</p> <pre><code>WebRequest request = WebRequest.Create("http://www.example.com/test.xml"); WebResponse response = request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); </code></pre> <p>That's a lot of code that could essentially be one line:</p> <pre><code>string responseFromServer = ????.GetStringFromUrl("http://www.example.com/test.xml"); </code></pre> <p>Note: I'm not worried about asynchronous calls - this is not production code.</p>
1,048,204
3
0
null
2009-06-26 09:26:20.91 UTC
29
2022-09-23 06:49:51.167 UTC
2018-06-12 23:18:27.893 UTC
null
100,142
null
100,142
null
1
126
c#|http|networking
106,813
<p>Important: this was correct when written, but in <code>$current_year$</code>, please see the <code>HttpClient</code> answer below</p> <hr /> <pre><code>using(WebClient client = new WebClient()) { string s = client.DownloadString(url); } </code></pre>
13,115,266
How to insist that a users input is an int?
<p>Basic problem here.. I will start off by asking that you please not respond with any code, as that likely will only confuse me further (programming noob). I am looking for a clear explanation on how to solve this issue that I'm having.</p> <p>I have a scanner that reads input from the user. The user is prompted to enter an int value between 1 to 150 (whole numbers only). I obtain the value as follows:</p> <pre><code> Scanner scan = new Scanner(System.in); int input = scan.nextInt(); </code></pre> <p>And continue on with my program, and everything works fine.</p> <p>Unfortunately, the code isn't exactly bulletproof, since any input that is not an integer can break it (letters, symbols, etc).</p> <p>How can I make the code more robust, where it would verify that only an int was entered?</p> <p>These are the results I'm hoping for:</p> <p>Lets say the input was:</p> <pre><code>23 -&gt; valid fx -&gt; display an error message, ask the user for input again (a while loop would do..) 7w -&gt; error, again 3.7 -&gt; error $$ -&gt; error etc </code></pre>
13,115,286
7
0
null
2012-10-29 02:43:26.323 UTC
5
2018-04-19 18:59:34.577 UTC
2012-10-29 02:50:01.87 UTC
null
418,556
null
1,188,439
null
1
1
java|input|int|java.util.scanner
46,386
<p><a href="http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()" rel="noreferrer">Scanner.hasNextInt()</a> returns <code>true</code> if the next token is a number, returns <code>false</code> otherwise.</p> <p>In this example, I call hasNextInt(). If it returns <code>true</code>, I go past the while and set the input; if it returns <code>false</code>, then I discard the input (<code>scanner.next();</code>) and repeat.</p> <pre><code>Scanner scan = new Scanner(System.in); while(!scan.hasNextInt()) { scan.next(); } int input = scan.nextInt(); </code></pre>
6,999,889
How to extract text from the PDF document?
<p>How to extract text from the PDF document <em>using PHP</em>?</p> <p>(I can't use other tools, I don't have root access)</p> <p>I've found some functions working for plain text, but they don't handle well Unicode characters:</p> <p><a href="http://www.hashbangcode.com/blog/zend-lucene-and-pdf-documents-part-2-pdf-data-extraction-437.html" rel="noreferrer">http://www.hashbangcode.com/blog/zend-lucene-and-pdf-documents-part-2-pdf-data-extraction-437.html</a></p>
7,001,377
1
2
null
2011-08-09 16:55:35.783 UTC
30
2020-04-10 19:19:07.893 UTC
null
null
null
null
865,831
null
1
68
php|pdf|text|unicode
128,688
<p>Download the <strong>class.pdf2text.php</strong> @ <a href="http://pastebin.com/dvwySU1a" rel="noreferrer">https://pastebin.com/dvwySU1a</a> or <a href="http://www.phpclasses.org/browse/file/31030.html" rel="noreferrer">http://www.phpclasses.org/browse/file/31030.html</a> (Registration required)</p> <p>Code:</p> <pre><code>include('class.pdf2text.php'); $a = new PDF2Text(); $a-&gt;setFilename('filename.pdf'); $a-&gt;decodePDF(); echo $a-&gt;output(); </code></pre> <hr> <ul> <li><p><code>class.pdf2text.php</code> <a href="https://webcheatsheet.com/php/reading_clean_text_from_pdf.php" rel="noreferrer">Project Home</a></p></li> <li><p><code>pdf2textclass</code> doesn't work with all the PDF's I've tested, If it doesn't work for you, try <a href="https://www.pdfparser.org/demo" rel="noreferrer">PDF Parser</a></p></li> </ul> <hr>
41,833,424
How to access Vuex module getters and mutations?
<p>I'm trying to switch to using Vuex instead of my homegrown store object, and I must say I'm not finding the docs as clear as elsewhere in the Vue.js world. Let's say I have a Vuex module called 'products', with its own state, mutations, getters, etc. How do I reference an action in that module called, say, 'clearWorking Data'? The docs give this example of accessing a module's state:</p> <pre><code>store.state.a // -&gt; moduleA's state </code></pre> <p>But nothing I can see about getters, mutations, actions, etc.</p>
41,833,552
7
2
null
2017-01-24 16:31:09.107 UTC
25
2022-04-22 07:24:07.82 UTC
2019-04-24 05:48:38.61 UTC
null
46,914
null
3,633,102
null
1
72
vue.js|vuex
82,144
<p>In your example it would be <code>store.dispatch('products/clearWorkingData')</code> you can think of actions/mutations as a file system in a way. The deeper the modules are nested the deeper in the tree they are.</p> <p>so you could go <code>store.commit('first/second/third/method')</code> if you had a tree that was three levels deep.</p>
36,439,780
Mongoose Schema vs Mongo Validator
<p>Mongo 3.2 have document validation, can we use the same to define a schema instead of using mongoose to do so.? For example : </p> <p><strong>Mongoose</strong></p> <pre><code>userschema = mongoose.Schema({ org: String, username: String, fullname: String, password: String, email: String }); </code></pre> <p><strong>MongoDB</strong></p> <pre><code>db.createCollection( "example",{ validator:{ $and:[ { "org":{$type:"string"}}, { "username":{$type:"string"}}, { "fullname":{$type:"double"}}, {"password":$type:"string"}}, {"email":{$type:"string"}} ] }, validationLevel:"strict", validationAction:"error" }) </code></pre> <p>What ar ethe difference between these tow and can we provide an optional field using validator as in schema ?</p>
45,158,994
2
2
null
2016-04-06 01:16:20.547 UTC
9
2020-08-28 20:05:04.023 UTC
2016-04-06 01:30:30.13 UTC
null
2,313,887
null
3,978,887
null
1
19
node.js|mongodb|validation|mongoose|schema
4,403
<p>I use both because they each have different limitations:</p> <ul> <li><p>Mongoose validators do not run on all types of update queries, and validators only run on paths with values in the update doc because the validators can't know if, for example, a required field is already defined in the database but not in your client's memory (see <a href="https://github.com/Automattic/mongoose/issues/3124" rel="noreferrer">issue</a>). <em>This is a major reason to use MongoDB validators [in addition to Mongoose validators].</em></p> <blockquote> <p>update validators only run on <code>$set</code> and <code>$unset</code> operations (and <code>$push</code> and <code>$addToSet</code> in &gt;= 4.8.0).</p> </blockquote> <p>So you can have a field with <code>required: true</code> in your Mongoose schema, but an <code>update</code> operation will not actually require that field! A MongoDB validator can solve this:</p> <pre><code> db.runCommand({collMod: &quot;collection&quot;, validator: {myfield: {$exists: true}}}) </code></pre> </li> <li><p>MongoDB for the most part cannot reference other fields during validation. For example, you can't say <code>{field1: {$lte: field2}}</code>. Mongoose validators can reference other fields.</p> <p>You can do some very basic types of cross-field referencing though:</p> <pre><code> {validator: {myfield1: &quot;Value 1&quot;, $and: [/* other validators */]} </code></pre> <p>This comes in handy if you're using Mongoose discriminators (inheritance) and have different requirements for each child type.</p> </li> <li><p>MongoDB does not provide &quot;nice&quot; errors in case of validation failure; it simply says something like <code>writeError: {code: 121, errmsg: &quot;Document failed validation}</code>. Mongoose will typically say something like <code>Path 'foo.bar' failed validation</code>.</p> <p><a href="https://jira.mongodb.org/browse/SERVER-20547" rel="noreferrer">MongoDB is fixing this in v4.6</a>.</p> </li> </ul> <p>Abilities that they share:</p> <ul> <li><p>Type validation. Mongoose by default attempts to cast values to the type specified in the schema. MongoDB with the <code>$type</code> attribute will cause a validation failure in case of a type mismatch.</p> </li> <li><p>Min and max number values. Mongoose uses <code>min</code> and <code>max</code> attributes on the schema. MongoDB uses <code>$lt</code>, <code>$lte</code>, <code>$gt</code> and <code>$gte</code>.</p> </li> <li><p>String enums. Mongoose uses <code>enum: [values]</code>. MongoDB uses <code>$in: [values]</code>.</p> </li> <li><p>String length validation. Mongoose: <code>minlength: 2, maxlength: 10</code>. MongoDB, use a regex: <code>{fieldname: {$regex: /.{2,10}/}}</code>.</p> </li> <li><p>Array length validation. Mongoose you have to use a custom validator. MongoDB: <code>{fieldName: {$size: 2}}</code>.</p> </li> <li><p>String RegExp matching. Mongoose you have to use a custom validator.</p> </li> </ul> <hr /> <p>The first bullet point is a major one. MongoDB <strike>does not have transactions</strike>now has transactions, but it does have powerful (and cheap) atomic updates. You often times can't reliably or safely read -&gt; change -&gt; validate -&gt; write with MongoDB, so using MongoDB native validators is critical in these cases.</p>
34,908,332
Float image in center
<p>I have an inline image in a paragraph. I want to float that image in the middle of the paragraph. I tried to center it with...</p> <pre><code>&lt;center&gt; </code></pre> <p>...but I saw it was depreciated in HTML5.<br> I tried to use float it with...</p> <pre><code>&lt;img style="float: middle;"&gt; </code></pre> <p>...but it turns out that that doesn't even exist.</p> <p>Is there a short way to do this, preferably inside the img tag, like with the style attribute?<br> Here is my HTML so far...</p> <pre><code>&lt;p&gt; &lt;img id="resize" width="70%" src="../logo.png" alt="Alt" style="CENTER THIS IMAGE... SOMEHOW..."&gt; &lt;/p&gt; </code></pre>
34,908,374
4
1
null
2016-01-20 19:03:31.36 UTC
1
2016-01-20 19:16:35.863 UTC
null
null
null
user5626618
null
null
1
4
css|html
59,842
<p>You can do it inline using <code>style="display:block; margin-left: auto; margin-right: auto;"</code></p> <p>or add it to a css class </p> <pre><code> .myimage { display:block; margin-left: auto; margin-right: auto; } </code></pre> <p><strong>Updated Based on CBore comment</strong></p>
35,914,758
XML Rendering errors Android preview N
<p>I have updated android SDK to android preview N after updating, I am getting this xml rendering error. After clicking on details it is showing following stack trace How to avoid this</p> <p><a href="https://i.stack.imgur.com/PabMN.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/PabMN.jpg" alt="?"></a></p> <pre><code>org.jetbrains.android.uipreview.RenderingException: Failed to load the LayoutLib: com/android/layoutlib/bridge/Bridge : Unsupported major.minor version 52.0 at org.jetbrains.android.uipreview.LayoutLibraryLoader.load(LayoutLibraryLoader.java:90) at org.jetbrains.android.sdk.AndroidTargetData.getLayoutLibrary(AndroidTargetData.java:180) at com.android.tools.idea.rendering.RenderService.createTask(RenderService.java:166) at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.doRender(AndroidLayoutPreviewToolWindowManager.java:649) at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.access$1700(AndroidLayoutPreviewToolWindowManager.java:80) at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$7$1.run(AndroidLayoutPreviewToolWindowManager.java:594) at com.intellij.openapi.progress.impl.CoreProgressManager$2.run(CoreProgressManager.java:152) at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:452) at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:402) at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54) at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:137) at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$7.run(AndroidLayoutPreviewToolWindowManager.java:589) at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:320) at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:310) at com.intellij.util.ui.update.MergingUpdateQueue$2.run(MergingUpdateQueue.java:254) at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:269) at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:227) at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:217) at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238) at com.intellij.util.Alarm$Request$1.run(Alarm.java:351) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) </code></pre>
35,917,202
4
2
null
2016-03-10 11:09:54.647 UTC
11
2017-05-29 08:41:37.153 UTC
2016-03-10 11:18:35.437 UTC
null
4,626,831
null
4,546,990
null
1
93
android|xml|android-studio|android-n-preview
31,540
<p>This is bug in Android Studio. Usually you get error: <strong>Unsupported major.minor version 52.0</strong></p> <p><strong>WORKAROUND:</strong> If you have installed Android N, change Android rendering version with older one and the problem will disappear.</p> <p><strong>SOLUTION:</strong> Install Android SDK Tools 25.1.3 (tools) or higher</p> <p><a href="https://i.stack.imgur.com/3HF0n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3HF0n.png" alt="enter image description here"></a></p>
5,977,285
Set session variable in Application_BeginRequest
<p>I'm using ASP.NET MVC and I need to set a session variable at <code>Application_BeginRequest</code>. The problem is that at this point the object <code>HttpContext.Current.Session</code> is always <code>null</code>. </p> <pre><code>protected void Application_BeginRequest(Object sender, EventArgs e) { if (HttpContext.Current.Session != null) { //this code is never executed, current session is always null HttpContext.Current.Session.Add("__MySessionVariable", new object()); } } </code></pre>
5,977,333
3
1
null
2011-05-12 11:31:02.863 UTC
5
2018-10-01 22:51:54.833 UTC
2014-12-31 03:59:16.11 UTC
null
76,337
null
402,081
null
1
41
asp.net|asp.net-mvc|asp.net-mvc-3|asp.net-mvc-2|global-asax
43,291
<p>Try AcquireRequestState in Global.asax. Session is available in this event which fires for each request:</p> <pre><code>void Application_AcquireRequestState(object sender, EventArgs e) { // Session is Available here HttpContext context = HttpContext.Current; context.Session["foo"] = "foo"; } </code></pre> <p><strong>Valamas - Suggested Edit:</strong></p> <p>Used this with MVC 3 successfully and avoids session error.</p> <pre><code>protected void Application_AcquireRequestState(object sender, EventArgs e) { HttpContext context = HttpContext.Current; if (context != null &amp;&amp; context.Session != null) { context.Session["foo"] = "foo"; } } </code></pre>
5,664,724
iPhone emulator for Windows that allows installation of new apps
<p>In my work I need to perform some tests on iOS iPhone, and for that I need an emulator for the iPhone.</p> <p>The problem is that this emulator should allow the installation of new applications, but among those who have researched (e.g MobiOne), there is this installation option.</p> <p>Anyone know of a program with such functionality?</p> <p>Thanks!</p> <hr> <p><strong>EDIT</strong></p> <p>I forgot to mention that I'm using Windows for this task, and I have an application that a client must be installed on this emulator.</p> <p>Then these constraints are: An emulator that works on Windows and allows the installation of this application.</p>
5,665,072
4
3
null
2011-04-14 14:25:34.727 UTC
2
2014-06-23 22:59:48.79 UTC
2014-01-06 07:46:41.013 UTC
null
-1
null
692,002
null
1
7
iphone|installation|emulation
78,408
<p>There exists no iOS device emulator that runs on Windows, or on anything else (outside of maybe Apple R&amp;D). The iOS Simulator only runs on Intel Macs running OS X 10.6.x (or newer), as the simulation environment pretty much requires an entire Mac OS X installation to run. And the iOS Simulator only runs apps compiled for x86 anyway, not ARM apps.</p> <p>The only way to test an App store app for an iPhone is on actual Apple iOS hardware.</p>
5,664,992
How to hide address bar using javascript window.open?
<p>I want to disable the address bar using javascript <code>window.open</code>. Also the script should work in IE, Safari and chrome. Any suggestions.</p>
5,665,037
4
2
null
2011-04-14 14:44:15.353 UTC
2
2019-02-22 18:55:49.457 UTC
2019-02-22 18:55:49.457 UTC
null
331,508
null
580,920
null
1
7
javascript|cross-browser|address-bar
97,822
<p>(untested)</p> <pre><code>function openWindow(){ var browser=navigator.appName; if (browser==”Microsoft Internet Explorer”) { window.opener=self; } window.open(‘filename.htm’,'null’,'width=900,height=750, toolbar=no,scrollbars=no,location=no,resizable =yes’); window.moveTo(0,0); window.resizeTo(screen.width,screen.height-100); self.close(); } </code></pre> <p>Got this from <a href="http://saher42.wordpress.com/2006/08/10/hiding-the-address-bar-on-pageload-using-javascript/">http://saher42.wordpress.com/2006/08/10/hiding-the-address-bar-on-pageload-using-javascript/</a>.</p>
5,854,647
How to put variable inside string-resources?
<p>Is it possible to put variables inside string-resources? And if yes - how do i use them.</p> <p>What i need is the following:</p> <p><code>&lt;string name="next_x_results"&gt;Next %X results&lt;/string&gt;</code></p> <p>and put an int in place of the %X.</p>
5,854,692
4
0
null
2011-05-02 07:42:36.493 UTC
8
2021-06-02 04:49:17.853 UTC
2011-05-02 08:06:23.857 UTC
null
3,713
null
423,862
null
1
79
java|android
62,936
<pre><code>&lt;string name="meatShootingMessage"&gt;You shot %1$d pounds of meat!&lt;/string&gt; int numPoundsMeat = 123; String strMeatFormat = getResources().getString(R.string.meatShootingMessage, numPoundsMeat); </code></pre> <p>Example taken from <a href="http://mobile.tutsplus.com/tutorials/android/android-sdk-format-strings/" rel="noreferrer">here</a></p>
6,168,919
How do I set up a simple delegate to communicate between two view controllers?
<p>I have two <code>UITableViewControllers</code> and need to pass the value from the child view controller to the parent using a delegate. I know what delegates are and just wanted to see a simple to follow example.</p> <p>Thank You</p>
6,169,104
4
2
null
2011-05-29 16:33:20.897 UTC
102
2018-02-12 13:27:03.457 UTC
2017-05-10 02:30:07.69 UTC
null
1,141,395
null
323,698
null
1
137
ios|objective-c|iphone|delegates
134,132
<p>Simple example...</p> <p>Let's say the child view controller has a <code>UISlider</code> and we want to pass the value of the slider back to the parent via a delegate.</p> <p>In the child view controller's header file, declare the delegate type and its methods:</p> <p><strong>ChildViewController.h</strong></p> <pre><code>#import &lt;UIKit/UIKit.h&gt; // 1. Forward declaration of ChildViewControllerDelegate - this just declares // that a ChildViewControllerDelegate type exists so that we can use it // later. @protocol ChildViewControllerDelegate; // 2. Declaration of the view controller class, as usual @interface ChildViewController : UIViewController // Delegate properties should always be weak references // See http://stackoverflow.com/a/4796131/263871 for the rationale // (Tip: If you're not using ARC, use `assign` instead of `weak`) @property (nonatomic, weak) id&lt;ChildViewControllerDelegate&gt; delegate; // A simple IBAction method that I'll associate with a close button in // the UI. We'll call the delegate's childViewController:didChooseValue: // method inside this handler. - (IBAction)handleCloseButton:(id)sender; @end // 3. Definition of the delegate's interface @protocol ChildViewControllerDelegate &lt;NSObject&gt; - (void)childViewController:(ChildViewController*)viewController didChooseValue:(CGFloat)value; @end </code></pre> <p>In the child view controller's implementation, call the delegate methods as required.</p> <p><strong>ChildViewController.m</strong></p> <pre><code>#import "ChildViewController.h" @implementation ChildViewController - (void)handleCloseButton:(id)sender { // Xcode will complain if we access a weak property more than // once here, since it could in theory be nilled between accesses // leading to unpredictable results. So we'll start by taking // a local, strong reference to the delegate. id&lt;ChildViewControllerDelegate&gt; strongDelegate = self.delegate; // Our delegate method is optional, so we should // check that the delegate implements it if ([strongDelegate respondsToSelector:@selector(childViewController:didChooseValue:)]) { [strongDelegate childViewController:self didChooseValue:self.slider.value]; } } @end </code></pre> <p>In the parent view controller's header file, declare that it implements the <code>ChildViewControllerDelegate</code> protocol.</p> <p><strong>RootViewController.h</strong></p> <pre><code>#import &lt;UIKit/UIKit.h&gt; #import "ChildViewController.h" @interface RootViewController : UITableViewController &lt;ChildViewControllerDelegate&gt; @end </code></pre> <p>In the parent view controller's implementation, implement the delegate methods appropriately.</p> <p><strong>RootViewController.m</strong></p> <pre><code>#import "RootViewController.h" @implementation RootViewController - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { ChildViewController *detailViewController = [[ChildViewController alloc] init]; // Assign self as the delegate for the child view controller detailViewController.delegate = self; [self.navigationController pushViewController:detailViewController animated:YES]; } // Implement the delegate methods for ChildViewControllerDelegate - (void)childViewController:(ChildViewController *)viewController didChooseValue:(CGFloat)value { // Do something with value... // ...then dismiss the child view controller [self.navigationController popViewControllerAnimated:YES]; } @end </code></pre> <p>Hope this helps!</p>
5,865,868
how lisp implemented in assembly language?
<p>many (may be all?) programming language consist of assembly language</p> <p>how lisp implemented in assembly language?</p> <p>is there any good reference, manual, tutorial, or keyword for google?</p> <p>any official rule/convention for build your own lisp implementation?</p> <p>such as tail recursion should follow some embodiment rule or something..</p> <p>thanks</p>
5,871,236
5
1
null
2011-05-03 06:28:44.84 UTC
14
2013-08-08 16:16:50.663 UTC
2013-08-08 16:16:50.663 UTC
user1228
null
null
464,689
null
1
11
assembly|lisp|implementation|convention
10,981
<p>Although the other comments and posts are right, this question is overly vague and maybe a bit confused, I can't help but share some recommendations. I've collected a number of links and books on implementing Lisp as I have recently developed a bit of a fascination with language implementation. It's a deep topic, of course, but reading the stuff related to Lisp is especially compelling because you can skip a lot of the intense reading on parsing if you implement a Lisp compiler or interpreter in Lisp, and just use <code>read</code>. This allows the authors to get to the meat of compilation or interpretation quickly. These recommendations are books I've read or started or am reading, and mostly deal with Scheme, not Common Lisp, but still might be of some interest.</p> <p>If you've got no background in language implementation, and have never had the pleasure of reading about the classic Lisp and Scheme "metacircular evaluators", I would recommend <a href="http://mitpress.mit.edu/sicp/full-text/book/book.html" rel="noreferrer">Structure and Interpretation of Computer Programs</a>. If you've seen Lisp-in-Lisp (or Scheme-in-Scheme...) you can skip ahead. In the last two chapters of SICP, the authors present a few different interpreters for Lisp/Scheme and a few variants, as well as a byte-code compiler and a virtual machine. It's simply a brilliant book, and free.</p> <p>If you don't have time to read SICP, or don't want to slog through it just to get to the interpretation and compilation chapters, I would recommend <a href="https://rads.stackoverflow.com/amzn/click/com/0262560992" rel="noreferrer" rel="nofollow noreferrer">The Little Schemer</a>. Even though it's very short and intended for newcomers to Lisp and Scheme, if you've never seen a Lisp interpreter written in Lisp, they do present one, and it's quite a delightful book, but might not be for everyone due to the cute style.</p> <p>There's another free book on Scheme similar to SICP, called <a href="http://www.cs.rpi.edu/academics/courses/fall00/ai/scheme/reference/schintro-v14/schintro_toc.html" rel="noreferrer">An Introduction to Scheme and its Implementation</a>, which I haven't read but used as a reference for a few bits. There are sections on interpreters and compilers in there, and it seems to go a bit deeper than SICP, dealing with hairier things like parsing too. It maybe needed an editor, but it's an impressive offering nonetheless.</p> <p>With a decent idea of how to do Lisp in Lisp, you can approach implementing Lisp in something lower level.</p> <p><a href="https://rads.stackoverflow.com/amzn/click/com/0521562473" rel="noreferrer" rel="nofollow noreferrer">Lisp in Small Pieces</a> is frequently recommended. I've read most of it, and can say it's definitely a great book, full of nitty gritty stuff. I'm going back over it with a fine comb, because it's easy to skim when you don't understand stuff. I also struggled with getting the code from the author's site to run; if you get it, I recommend using Gambit Scheme and running the code that relies on Meroonet with Meroon, from <a href="http://www.math.purdue.edu/~lucier/software/Meroon/" rel="noreferrer">this</a> distribution. Lisp in Small Pieces presents a number of interpreters written in Scheme as well as a byte-code compiler and a compiler-to-C.</p> <p>Lisp in Small Pieces moves fast, and it's quite dense. If it's too much for you, perhaps start with <a href="http://www.eopl3.com/" rel="noreferrer">The Essentials of Programming Languages</a>. I've read some of it and it's quite good, but it's more interpreters. Apparently one of the older editions (1st? I'm not sure...) included a compiler. There seems to be a lot of change between the 3 editions, but the first is super cheap on Amazon, so check it out.</p> <p>As for compilation to C, this is kind of a gross subject with lots of hairy bits. Compilation to C brings up all these weird corner issues, like how to optimize tail-calls and handle closures, first-class continuations and garbage collection, but it's pretty interesting, and a lot of "real" implementations of Scheme go this route. Marc Feeley's presentation on this is pretty interesting, titled <a href="http://www.iro.umontreal.ca/~boucherd/mslug/meetings/20041020/minutes-en.html" rel="noreferrer">The 90 Minute Scheme to C compiler</a>.</p> <p>I have fewer resources on compiling all the way down to assembly, but there is a often recommended paper which introduces compilation of Scheme to x86, called <a href="http://scheme2006.cs.uchicago.edu/11-ghuloum.pdf" rel="noreferrer">An Incremental Approach to Compiler Construction.</a> It assumes little of the reader, however I found that it simply goes too fast and doesn't fill in enough details. Maybe you'll have better luck.</p> <p>A lot of the above recommendation comes from this monster comment on Hacker News from over a year ago, from <a href="http://news.ycombinator.com/item?id=835020" rel="noreferrer">mahmud</a>. It references a number of ML resources, and compilation using continuations. I haven't gotten that far in my study, so I can't say what's good or not. But it's an incredibly valuable comment. The referenced works include Andrew Appel's "Compiling with Continuations" and Paul Wilson's "Uniprocessor Garbage Collection Techniques" paper.</p> <p>Good luck!</p>
1,973,705
convert vector to list
<p>How to convert a vector to a list?</p>
1,973,713
2
1
null
2009-12-29 09:22:22.61 UTC
5
2009-12-29 10:11:57.773 UTC
2009-12-29 09:54:04.723 UTC
anon355079
null
null
230,237
null
1
26
java|list|vector
50,807
<p><a href="http://java.sun.com/javase/6/docs/api/java/util/Vector.html" rel="noreferrer"><code>Vector</code></a> is a concrete class that implements the <a href="http://java.sun.com/javase/6/docs/api/java/util/List.html" rel="noreferrer"><code>List</code></a> interface so technically it is already a <code>List</code>. You can do this:</p> <pre><code>List list = new Vector(); </code></pre> <p>or:</p> <pre><code>List&lt;String&gt; list = new Vector&lt;String&gt;(); </code></pre> <p>(assuming a <code>Vector</code> of <code>String</code>s).</p> <p>If however you want to convert it to an <a href="http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html" rel="noreferrer"><code>ArrayList</code></a>, which is the closest <code>List</code> implementation to a `Vector~ in the Java Collections Framework then just do this:</p> <pre><code>List newList = new ArrayList(vector); </code></pre> <p>or for a generic version, assuming a <code>Vector</code> of <code>String</code>s:</p> <pre><code>List&lt;String&gt; newList = new ArrayList&lt;String&gt;(vector); </code></pre>
1,501,235
Change user.home system property
<p>How do I change the user.home system property from outside my java program, so that it thinks it's a different directory from D:\Documents and Settings\%USERNAME%? Via environment variables, or VM arguments?</p>
1,501,261
2
0
null
2009-09-30 23:41:34.67 UTC
5
2017-04-27 14:14:09.343 UTC
2017-04-27 14:14:09.343 UTC
null
149,412
null
149,412
null
1
29
java|system-properties
42,823
<p>Setting VM argument should work:</p> <pre><code>java -Duser.home=&lt;new_location&gt; &lt;your_program&gt; </code></pre> <p>Here's a test case:</p> <pre><code>public class test { public static void main(String[] args) { System.out.println(System.getProperty("user.home")); } } </code></pre> <p>Tested with java 1.5.0_17 on Win XP and Linux</p> <pre><code>java test /home/ChssPly76 java -Duser.home=overwritten test overwritten </code></pre>
46,008,760
how to build multiple language website using pure html, js, jquery?
<p>i am using html to build pages. The problem is how to build multiple language switch? Language translate is not issue, i have the terms. However, I don't know how to switch btw every page through the language button/dropdown list on the menu bar? If there is a existing example or template, that would be even better. Thanks in advance.</p>
46,008,865
2
2
null
2017-09-01 22:36:12.95 UTC
25
2018-04-30 05:58:30.257 UTC
null
null
null
null
2,962,555
null
1
27
javascript|jquery|html|multilingual
95,304
<p>ok. as an edit to the my answer, please follow: </p> <p><strong>1 -</strong> create a folder called language and add 2 files to it ( es.json and en.json )</p> <p>The json files should be identical in structure but different in translation as below: </p> <p><strong>en.json</strong></p> <pre><code>{ "date": "Date", "save": "Save", "cancel": "Cancel" } </code></pre> <p><strong>es.json</strong> </p> <pre><code>{ "date": "Fecha", "save": "Salvar", "cancel": "Cancelar" } </code></pre> <p><strong>2</strong> - Create an html page containing a sample div and put 2 links to select the language pointing to the js function listed in step 3. </p> <pre><code>&lt;a href="#" onclick="setLanguage('en')"&gt;English&lt;/a&gt; &lt;a href="#" onclick="setLanguage('es')"&gt;Spanish&lt;/a&gt; &lt;div id="div1"&gt;&lt;/div&gt; </code></pre> <p><strong>3 -</strong> Create 2 java script functions to get/set the selected language: </p> <pre><code>&lt;script&gt; var language; function getLanguage() { (localStorage.getItem('language') == null) ? setLanguage('en') : false; $.ajax({ url: '/language/' + localStorage.getItem('language') + '.json', dataType: 'json', async: false, dataType: 'json', success: function (lang) { language = lang } }); } function setLanguage(lang) { localStorage.setItem('language', lang); } &lt;/script&gt; </code></pre> <p><strong>4</strong> - Use the variable language to populate the text. </p> <pre><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function(){ $('#div1').text(language.date); }); &lt;/script&gt; </code></pre> <p>I believe this answers the question as I have the same concept implemented cross multiple sites. </p> <p>Note: You can make instant translation ( without reload ) just by using an onclick event other than document.ready from JQuery. It depends on your scenario. </p>
29,470,478
Blade, Use html inside variable being passed into partial view is not being rendered
<p>I'm using a partial view to display page header, that view accepts two variables one is Icon the other is a title. pageHeader.blade.php:</p> <pre><code>&lt;div class="page-header"&gt; &lt;div class="row"&gt; &lt;!-- Page header, center on small screens --&gt; &lt;h1 class="col-xs-12 col-sm-4 text-center text-left-sm"&gt;&lt;i class="fa {{$icon}} page-header-icon"&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;{{$title}}&lt;/h1&gt; &lt;/div&gt; </code></pre> <p></p> <p>and I'm using it like so:</p> <pre><code>@include('zdashboard._partials.pageHeader',['icon'=&gt;'fa-pencil','title'=&gt;'&lt;strong&gt;Editing&lt;/strong&gt;'.$center-&gt;translations()-&gt;whereLang('en')-&gt;first()-&gt;name]) </code></pre> <p>Sometimes I like to make one word strong or italic like the example above but, blade engine won't render the HTML tags I'm typing as part of <code>title</code> variable (the output like the photo down).</p> <p>So is there any idea how to solve this? Am I doing it!</p> <p>wrong?</p> <p><a href="http://i.stack.imgur.com/t1AGV.png">The output</a></p>
29,470,508
2
0
null
2015-04-06 11:35:28.003 UTC
1
2018-02-07 04:23:22.707 UTC
null
null
null
null
2,131,039
null
1
35
html|laravel|laravel-5|laravel-blade
40,369
<p>By default in Laravel 5 <code>{{ $title }}</code> construction wil be escaped.</p> <p>If you don't want the data to be escaped, you may use the following syntax:</p> <pre><code>{!! $title !!} </code></pre> <p>Read more about Blade control structures: <a href="http://laravel.com/docs/5.0/templates#other-blade-control-structures">http://laravel.com/docs/5.0/templates#other-blade-control-structures</a></p>
5,920,070
Why can't you mix Aggregate values and Non-Aggregate values in a single SELECT?
<p>I know that if you have one aggregate function in a SELECT statement, then all the other values in the statement must be either aggregate functions, or listed in a GROUP BY clause. I don't understand <em>why</em> that's the case.</p> <p>If I do:</p> <pre><code>SELECT Name, 'Jones' AS Surname FROM People </code></pre> <p>I get:</p> <pre><code>NAME SURNAME Dave Jones Susan Jones Amy Jones </code></pre> <p>So, the DBMS has taken a value from each row, and appended a single value to it in the result set. That's fine. But if that works, why can't I do:</p> <pre><code>SELECT Name, COUNT(Name) AS Surname FROM People </code></pre> <p>It seems like the same idea, take a value from each row and append a single value. But instead of:</p> <pre><code>NAME SURNAME Dave 3 Susan 3 Amy 3 </code></pre> <p>I get:</p> <blockquote> <p>You tried to execute a query that does not include the specified expression 'ContactName' as part of an aggregate function.</p> </blockquote> <p>I know it's not allowed, but the two circumstances seem so similar that I don't understand why. Is it to make the DBMS easier to implement? If anyone can explain to me why it doesn't work like I think it should, I'd be very grateful.</p>
5,920,259
6
3
null
2011-05-07 08:55:24.74 UTC
8
2013-01-19 06:36:11.57 UTC
null
null
null
null
55,155
null
1
23
sql|aggregate-functions
43,973
<p>Aggregates doesn't work on a complete result, they only work on a group in a result.</p> <p>Consider a table containing:</p> <pre><code>Person Pet -------- -------- Amy Cat Amy Dog Amy Canary Dave Dog Susan Snake Susan Spider </code></pre> <p>If you use a query that groups on Person, it will divide the data into these groups:</p> <pre><code>Amy: Amy Cat Amy Dog Amy Canary Dave: Dave Dog Susan: Susan Snake Susan Spider </code></pre> <p>If you use an aggreage, for exmple the count aggregate, it will produce one result for each group:</p> <pre><code>Amy: Amy Cat Amy Dog Amy Canary count(*) = 3 Dave: Dave Dog count(*) = 1 Susan: Susan Snake Susan Spider count(*) = 2 </code></pre> <p>So, the query <code>select Person, count(*) from People group by Person</code> gives you one record for each group:</p> <pre><code>Amy 3 Dave 1 Susan 2 </code></pre> <p>If you try to get the Pet field in the result also, that doesn't work because there may be multiple values for that field in each group.</p> <p>(Some databases, like MySQL, does allow that anyway, and just returns any random value from within the group, and it's your responsibility to know if the result is sensible or not.)</p> <p>If you use an aggregate, but doesn't specify any grouping, the query will still be grouped, and the entire result is a single group. So the query <code>select count(*) from Person</code> will create a single group containing all records, and the aggregate can count the records in that group. The result contains one row from each group, and as there is only one group, there will be one row in the result.</p>
6,280,978
how to uniqify a list of dict in python
<p>I have a list:</p> <pre><code>d = [{'x':1, 'y':2}, {'x':3, 'y':4}, {'x':1, 'y':2}] </code></pre> <p><code>{'x':1, 'y':2}</code> comes more than once I want to remove it from the list.My result should be:</p> <pre><code> d = [{'x':1, 'y':2}, {'x':3, 'y':4} ] </code></pre> <p><strong>Note:</strong> <code>list(set(d))</code> is not working here throwing an error.</p>
6,281,063
6
4
null
2011-06-08 15:04:29.33 UTC
3
2018-09-26 09:42:14.353 UTC
2011-06-08 15:11:01.623 UTC
null
115,845
null
789,425
null
1
30
python
26,374
<p>If your value is hashable this will work:</p> <pre><code>&gt;&gt;&gt; [dict(y) for y in set(tuple(x.items()) for x in d)] [{'y': 4, 'x': 3}, {'y': 2, 'x': 1}] </code></pre> <p>EDIT:</p> <p>I tried it with no duplicates and it seemed to work fine</p> <pre><code>&gt;&gt;&gt; d = [{'x':1, 'y':2}, {'x':3, 'y':4}] &gt;&gt;&gt; [dict(y) for y in set(tuple(x.items()) for x in d)] [{'y': 4, 'x': 3}, {'y': 2, 'x': 1}] </code></pre> <p>and</p> <pre><code>&gt;&gt;&gt; d = [{'x':1,'y':2}] &gt;&gt;&gt; [dict(y) for y in set(tuple(x.items()) for x in d)] [{'y': 2, 'x': 1}] </code></pre>
5,709,258
jQuery change input text value
<p>I can't find the right selector for:</p> <pre><code>&lt;input maxlength="6" size="6" id="colorpickerField1" name="sitebg" value="#EEEEEE" type="text"&gt; </code></pre> <p>I want to change the value to = 000000. I need the selector to find the "name" not the id of the text input.</p> <p>Shouldn't this work?:</p> <pre><code>$("text.sitebg").val("000000"); </code></pre> <p>The presented solution does not work, what's the problem with this?</p> <pre><code>$.getJSON("http://www.mysitehere.org/wp-content/themes/ctr-theme/update_genform.php",function(data) { $("#form1").append(data.sitebg); $('input.sitebg').val('000000'); }); </code></pre> <p>The JSON data is working correctly; the idea is to later pass the JSON values into the form input text values. But is not working :(</p>
5,709,272
6
0
null
2011-04-18 21:43:44.923 UTC
37
2021-04-16 03:35:24.883 UTC
2015-03-25 00:25:01.607 UTC
null
814,702
null
700,418
null
1
188
jquery
740,260
<p>no, you need to do something like:</p> <pre><code>$('input.sitebg').val('000000'); </code></pre> <p>but you should really be using unique IDs if you can.</p> <p>You can also get more specific, such as: </p> <pre><code>$('input[type=text].sitebg').val('000000'); </code></pre> <p>EDIT:</p> <p>do this to find your input based on the name attribute:</p> <pre><code>$('input[name=sitebg]').val('000000'); </code></pre>
6,221,510
Django calling save on a QuerySet object - 'QuerySet' object has no attribute 'save'
<p>How would I get the below to work?</p> <pre><code>player = Player.objects.get(pk=player_id) game = Game.objects.get(pk=game_id) game_participant = GameParticipant.objects.filter(player=player, game=game) game_participant.save() </code></pre> <p>I when the object already exists in the datbase then I get:</p> <blockquote> <p>'QuerySet' object has no attribute 'save'. </p> </blockquote> <p>In terms of my Models, <code>GameParticipant</code> has <code>ForeignKey</code> to both <code>Game</code> and <code>Player</code>. I understand that filter returns a QuerySet but I'm not sure how to cast that to a <code>GameParticipant</code> or is that not the right thinking?</p> <pre><code>class Player(models.Model): name = models.CharField(max_length=30) email = models.EmailField() class Game(models.Model): game_date = models.DateTimeField() team = models.ForeignKey(Team) description = models.CharField(max_length=100, null=True, blank=True) score = models.CharField(max_length=10, null=True, blank=True) class GameParticipant(models.Model): STATUS_CHOICES = (('Y','Yes'),('N','No'),('M','Maybe')) status = models.CharField(max_length=10, choices=STATUS_CHOICES) game = models.ForeignKey(Game) player = models.ForeignKey(Player) </code></pre> <p>OR IS THERE A BETTER WAY TO DO WHAT IM TRYING TO DO? ie. with a .get() instead of a .filter() but then i run into other issues???</p>
6,221,575
8
2
null
2011-06-02 23:29:28.593 UTC
6
2022-07-04 06:14:34.473 UTC
2011-06-03 01:41:57.69 UTC
null
688,266
null
688,266
null
1
22
python|django
50,433
<p>You'll want to use the <code>update</code> method since you're dealing with multiple objects:</p> <p><a href="https://docs.djangoproject.com/en/2.0/topics/db/queries/#updating-multiple-objects-at-once" rel="noreferrer">https://docs.djangoproject.com/en/2.0/topics/db/queries/#updating-multiple-objects-at-once</a></p>
5,826,649
Returning a file to View/Download in ASP.NET MVC
<p>I'm encountering a problem sending files stored in a database back to the user in ASP.NET MVC. What I want is a view listing two links, one to view the file and let the mimetype sent to the browser determine how it should be handled, and the other to force a download.</p> <p>If I choose to view a file called <code>SomeRandomFile.bak</code> and the browser doesn't have an associated program to open files of this type, then I have no problem with it defaulting to the download behavior. However, if I choose to view a file called <code>SomeRandomFile.pdf</code> or <code>SomeRandomFile.jpg</code> I want the file to simply open. But I also want to keep a download link off to the side so that I can force a download prompt regardless of the file type. Does this make sense?</p> <p>I have tried <code>FileStreamResult</code> and it works for most files, its constructor doesn't accept a filename by default, so unknown files are assigned a file name based on the URL (which does not know the extension to give based on content type). If I force the file name by specifying it, I lose the ability for the browser to open the file directly and I get a download prompt. Has anyone else encountered this?</p> <p>These are the examples of what I've tried so far.</p> <pre><code>//Gives me a download prompt. return File(document.Data, document.ContentType, document.Name); </code></pre> <p></p> <pre><code>//Opens if it is a known extension type, downloads otherwise (download has bogus name and missing extension) return new FileStreamResult(new MemoryStream(document.Data), document.ContentType); </code></pre> <p></p> <pre><code>//Gives me a download prompt (lose the ability to open by default if known type) return new FileStreamResult(new MemoryStream(document.Data), document.ContentType) {FileDownloadName = document.Name}; </code></pre> <p>Any suggestions?</p> <hr> <p><strong>UPDATE:</strong> This questions seems to strike a chord with a lot of people, so I thought I'd post an update. The warning on the accepted answer below that was added by Oskar regarding international characters is completely valid, and I've hit it a few times due to using the <code>ContentDisposition</code> class. I've since updated my implementation to fix this. While the code below is from my most recent incarnation of this problem in an ASP.NET Core (Full Framework) app, it should work with minimal changes in an older MVC application as well since I'm using the <code>System.Net.Http.Headers.ContentDispositionHeaderValue</code> class.</p> <pre><code>using System.Net.Http.Headers; public IActionResult Download() { Document document = ... //Obtain document from database context //"attachment" means always prompt the user to download //"inline" means let the browser try and handle it var cd = new ContentDispositionHeaderValue("attachment") { FileNameStar = document.FileName }; Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString()); return File(document.Data, document.ContentType); } // an entity class for the document in my database public class Document { public string FileName { get; set; } public string ContentType { get; set; } public byte[] Data { get; set; } //Other properties left out for brevity } </code></pre>
5,830,215
9
0
null
2011-04-29 00:38:49.96 UTC
116
2020-04-24 00:20:31.427 UTC
2020-04-24 00:20:31.427 UTC
null
466,224
null
466,224
null
1
329
c#|asp.net-mvc|asp.net-mvc-3|download|http-headers
454,582
<pre><code>public ActionResult Download() { var document = ... var cd = new System.Net.Mime.ContentDisposition { // for example foo.bak FileName = document.FileName, // always prompt the user for downloading, set to true if you want // the browser to try to show the file inline Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(document.Data, document.ContentType); } </code></pre> <p><em>NOTE:</em> This example code above fails to properly account for international characters in the filename. See RFC6266 for the relevant standardization. I believe recent versions of ASP.Net MVC's <code>File()</code> method and the <code>ContentDispositionHeaderValue</code> class properly accounts for this. - Oskar 2016-02-25</p>
6,026,285
PhoneGap application: "ERROR: Start Page at `www/index.html` was not found"
<p>I have created a Phone Gap based application on iPhone. After the first run, I have dragged my <code>www</code> folder, containing <code>index.html</code> into the project, but still I am getting the following error in the simulator:</p> <blockquote> <p>ERROR: Start Page at <code>www/index.html</code> was not found. </p> </blockquote> <p>Do I have to mention the name of <code>index.html</code> in a plist file or anywhere else? How can I resolve this; can any one help me?</p>
6,434,212
10
1
null
2011-05-17 04:35:26.947 UTC
16
2021-09-19 19:45:01.487 UTC
2017-05-08 03:40:51.793 UTC
null
2,840,103
null
766,047
null
1
42
ios|cordova
36,541
<p>It's an incompatibility between PhoneGap and XCode 4. To resolve:</p> <ul> <li>right click on your project and choose "Add files to [project name]...";</li> <li>choose the <code>www</code> folder from your curent project's folder (it's included in there, but not added as a reference);</li> <li>when you select the folder, make sure you choose <strong>"Copy items into destination group's folder"</strong> as well as <strong>"Create folder references for any added folders"</strong>.</li> </ul> <p><strong>Note:</strong> if you choose "Create groups for any added folders", the app will still fail at runtime.</p>
5,816,419
IntelliJ does not show project folders
<p>I have an issue with IntelliJ. It doesn't show any folders in my project view on the left. My setting is "View As: Project" How can I manage it so that the folders and packages are shown again? I don't have any clue because I didn't change any options!</p> <p>I'm using IntelliJ 10.0.3. I am working on a Maven Lift Project.</p>
28,375,299
36
9
null
2011-04-28 09:23:57.537 UTC
71
2022-09-14 19:32:04.4 UTC
2016-01-19 18:33:30.433 UTC
null
266,531
null
543,219
null
1
453
intellij-idea
345,695
<p>So after asking another question, someone helped me figure out that under <strong>File > Project Structure > Modules</strong>, there's supposed to be stuff there. If it's empty (says "Nothing to show"), do the following:</p> <ol> <li>In <strong>File > Project Structure > Modules</strong>, click the "+" button, </li> <li>Press <kbd>Enter</kbd> (because weirdly it won't let me click on "New Module") <a href="https://i.stack.imgur.com/VJ1h4.png"><img src="https://i.stack.imgur.com/VJ1h4.png" alt="step 2"></a></li> <li>In the window that pops up, click on the "..." next button which takes you to the Content root. Find your root folder and select it <a href="https://i.stack.imgur.com/Kszzl.png"><img src="https://i.stack.imgur.com/Kszzl.png" alt="step 3 part 1"></a> <a href="https://i.stack.imgur.com/wjrrK.png"><img src="https://i.stack.imgur.com/wjrrK.png" alt="step 3"></a></li> <li>Click the "ok" button</li> <li>Ignore any warning that says the name is already in use</li> </ol>
44,334,106
How can I style horizontal scrollbar by CSS?
<p>I styled my vertical scrollbars with the following code: </p> <pre><code>::-webkit-scrollbar { width: 4px; border: 1px solid #d5d5d5; } ::-webkit-scrollbar-track { border-radius: 0; background: #eeeeee; } ::-webkit-scrollbar-thumb { border-radius: 0; background: #b0b0b0; } </code></pre> <p>Now, my vertical scrollbar looks like this:</p> <p><a href="https://i.stack.imgur.com/0Rbkh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0Rbkh.png" alt="enter image description here"></a></p> <p>However, my horizontal scrollbar looks like this :</p> <p><a href="https://i.stack.imgur.com/W6dQm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/W6dQm.png" alt="enter image description here"></a></p> <p>How can I set a 2-4px height for it? </p>
44,334,343
6
1
null
2017-06-02 17:05:05.11 UTC
6
2022-03-02 11:20:51.847 UTC
2017-06-02 17:15:03.403 UTC
null
1,946,501
null
3,498,235
null
1
76
html|css
119,062
<pre><code>::-webkit-scrollbar { height: 4px; /* height of horizontal scrollbar ← You're missing this */ width: 4px; /* width of vertical scrollbar */ border: 1px solid #d5d5d5; } </code></pre> <p>since logically one cannot force a <strong>vertical scrollbar</strong> to be a certain <em>height</em> (since dictated by the positioned parent) - therefore such <strong><code>height</code> property</strong> is to target the <strong>horizontal's scrollbar</strong> height - and <em>vice-versa</em> (<code>width</code> for the width of the vertical scrollbar.).</p>
65,459,034
VS code CSS class selector not found with angular and bootstrap 5 beta
<p>I'm using bootstrap 5 with angular and I add style and script to angular.json but the problem in VS Code it does not recognize the bootstrap classes.</p> <p><a href="https://i.stack.imgur.com/vbCV1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vbCV1.png" alt="1" /></a></p> <p><a href="https://i.stack.imgur.com/wrBDp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wrBDp.png" alt="2" /></a></p>
65,463,311
13
0
null
2020-12-26 17:42:48.577 UTC
5
2022-02-12 17:35:01.957 UTC
2021-01-18 07:56:05.26 UTC
null
217,666
null
14,415,210
null
1
31
angular|visual-studio-code|vscode-extensions|bootstrap-5
11,991
<p>Uninstall this extension named &quot;HTML CSS Support&quot; and then reload. It worked for me, I hope it would work for you as well.</p>
32,908,621
how can I create a data-container only using docker-compose.yml?
<p>This question is coming from an issue on the Docker's repository:<br> <a href="https://github.com/docker/compose/issues/942" rel="noreferrer">https://github.com/docker/compose/issues/942</a></p> <p>I can't figure it out how to create a data container (no process running) with docker compose.</p>
32,916,890
4
2
null
2015-10-02 13:46:50.587 UTC
5
2021-06-09 15:31:53.933 UTC
2015-10-02 14:32:45.453 UTC
null
6,309
null
2,428,468
null
1
31
docker|docker-compose|volumes
23,913
<p><strong>UPDATE:</strong> Things have changed in the last years. Please refer to the answer from @Frederik Wendt for a good and up-to-date solution.</p> <p><strong>My old answer:</strong> Exactly how to do it depends a little on what image you are using for your data-only-container. If your image has an <code>entrypoint</code>, you need to overwrite this in your <code>docker-compose.yml</code>. For example this is a solution for the official MySql image from docker hub:</p> <pre><code>DatabaseData: image: mysql:5.6.25 entrypoint: /bin/bash DatabaseServer: image: mysql:5.6.25 volumes_from: - DatabaseData environment: MYSQL_ROOT_PASSWORD: blabla </code></pre> <p>When you do a <code>docker-compose up</code> on this, you will get a container like <code>..._DatabaseData_1</code> which shows a status of <code>Exited</code> when you call <code>docker ps -a</code>. Further investigation with <code>docker inspect</code> will show, that it has a timestamp of <code>0</code>. That means the container was never run. Like it is stated by the owner of docker compose <a href="https://github.com/docker/compose/issues/942#issuecomment-76547569" rel="nofollow noreferrer">here</a>.</p> <p>Now, as long as you don't do a <code>docker-compose rm -v</code>, your data only container (<code>..._DatabaseData_1</code>) will not loose its data. So you can do <code>docker-compose stop</code> and <code>docker-compose up</code> as often as you like.</p> <p>In case you like to use a dedicated data-only image like <code>tianon/true</code> this works the same. Here you don't need to overwrite the <code>entrypoint</code>, because it doesn't exist. It seems like there are some problems with that image and docker compose. I haven't tried it, but <a href="http://dockermeetupsinbordeaux.github.io/docker-compose/data-container/2015/03/01/minimalistic-docker-data-container.html" rel="nofollow noreferrer">this article</a> could be worth reading in case you experience any problems.</p> <p>In general it seems to be a good idea to use the same image for your data-only container that you are using for the container accessing it. See <a href="http://container42.com/2014/11/18/data-only-container-madness/" rel="nofollow noreferrer">Data-only container madness</a> for more details.</p>
9,464,261
How to find the exact word using a regex in Java?
<p>Consider the following code snippet:</p> <pre><code>String input = "Print this"; System.out.println(input.matches("\\bthis\\b")); </code></pre> <p>Output</p> <pre><code>false </code></pre> <p>What could be possibly wrong with this approach? If it is wrong, then what is the right solution to find the exact word match? </p> <p>PS: I have found a variety of similar questions here but none of them provide the solution I am looking for. Thanks in advance.</p>
9,464,309
6
0
null
2012-02-27 11:28:38.583 UTC
8
2020-05-17 19:29:00.827 UTC
2018-07-05 17:57:46.977 UTC
null
371,396
null
371,396
null
1
24
java|regex
92,865
<p>When you use the <code>matches()</code> method, it is trying to match the entire input. In your example, the input <em>"Print this"</em> doesn't match the pattern because the word <em>"Print"</em> isn't matched.</p> <p>So you need to add something to the regex to match the initial part of the string, e.g.</p> <pre><code>.*\\bthis\\b </code></pre> <p>And if you want to allow extra text at the end of the line too:</p> <pre><code>.*\\bthis\\b.* </code></pre> <p>Alternatively, use a <code>Matcher</code> object and use <code>Matcher.find()</code> to find matches <em>within</em> the input string:</p> <pre><code> Pattern p = Pattern.compile("\\bthis\\b"); Matcher m = p.matcher("Print this"); m.find(); System.out.println(m.group()); </code></pre> <p>Output:</p> <pre><code>this </code></pre> <p>If you want to find multiple matches in a line, you can call <code>find()</code> and <code>group()</code> repeatedly to extract them all.</p>
9,527,366
Cannot enable migrations for Entity Framework in class library
<p>I just got on board with EF 5 and am using their code-first migrations tool but I seem to get an error when I try to enable migrations.</p> <p>I type <code>Enable-Migrations</code> into the package manager console and then it says</p> <blockquote> <p>No classes deriving from DbContext found in the current project.<br> Edit the generated Configuration class to specify the context to enable migrations for.<br> Code First Migrations enabled for project MyApp.MvcUI.</p> </blockquote> <p>It then creates a Migrations folder and a Configuration class in my MvcUI project. Thing is, my DbContext lives in a class library project called MyApp.Domain. It should be doing all that in that project and should have no problem finding my DbContext.</p>
9,527,372
2
0
null
2012-03-02 02:57:28.24 UTC
4
2014-02-23 03:55:34.713 UTC
2014-02-23 03:55:34.713 UTC
null
498,624
null
498,624
null
1
43
c#|entity-framework|ef-code-first|entity-framework-5|entity-framework-migrations
25,939
<p>Oh wow, nevermind. I'm dumb.</p> <p>In the Nuget package manager console there is a dropdown menu at the top labeled "Default Project:". Make sure you set that to the project you want to run the command against.</p> <p>Hopefully this helps someone else avoid my embarrassing mistake.</p>
47,283,908
Parsing JSON string with jsoncpp
<p>I'm trying to parse a JSON string encoded with PHP and sent over TCP to a C++ client.</p> <p>My JSON strings are like this:</p> <pre><code>{"1":{"name":"MIKE","surname":"TAYLOR"},"2":{"name":"TOM","surname":"JERRY"}} </code></pre> <p>On the C++ client I'm using the jsoncpp libraries:</p> <pre><code>void decode() { string text = {"1":{"name":"MIKE","surname":"TAYLOR"},"2":{"name":"TOM","surname":"JERRY"}}; Json::Value root; Json::Reader reader; bool parsingSuccessful = reader.parse( text, root ); if ( !parsingSuccessful ) { cout &lt;&lt; "Error parsing the string" &lt;&lt; endl; } const Json::Value mynames = root["name"]; for ( int index = 0; index &lt; mynames.size(); ++index ) { cout &lt;&lt; mynames[index] &lt;&lt; endl; } } </code></pre> <p>The problem is that I'm not getting anything as output, not even the error about the parsing(if any). Could you possibly help me to understand what I'm doing wrong ?</p>
47,284,656
2
2
null
2017-11-14 10:56:06.23 UTC
4
2018-11-02 11:06:34.23 UTC
2017-11-14 11:36:13.467 UTC
null
698,496
null
8,120,400
null
1
16
c++|json|jsoncpp
53,538
<p>Your problem is: there is no <strong>root["name"]</strong>. Your document should be like this: </p> <pre><code>{ "people": [{"id": 1, "name":"MIKE","surname":"TAYLOR"}, {"id": 2, "name":"TOM","surname":"JERRY"} ]} </code></pre> <p>And your code like this: </p> <pre><code>void decode() { string text ="{ \"people\": [{\"id\": 1, \"name\":\"MIKE\",\"surname\":\"TAYLOR\"}, {\"id\": 2, \"name\":\"TOM\",\"surname\":\"JERRY\"} ]}"; Json::Value root; Json::Reader reader; bool parsingSuccessful = reader.parse( text, root ); if ( !parsingSuccessful ) { cout &lt;&lt; "Error parsing the string" &lt;&lt; endl; } const Json::Value mynames = root["people"]; for ( int index = 0; index &lt; mynames.size(); ++index ) { cout &lt;&lt; mynames[index] &lt;&lt; endl; } } </code></pre> <p>If you want to keep your data as is:</p> <pre><code>void decode() { //string text ="{ \"people\": [{\"id\": 1, \"name\":\"MIKE\",\"surname\":\"TAYLOR\"}, {\"id\": 2, \"name\":\"TOM\",\"surname\":\"JERRY\"} ]}"; string text ="{ \"1\": {\"name\":\"MIKE\",\"surname\":\"TAYLOR\"}, \"2\": {\"name\":\"TOM\",\"surname\":\"JERRY\"} }"; Json::Value root; Json::Reader reader; bool parsingSuccessful = reader.parse( text, root ); if ( !parsingSuccessful ) { cout &lt;&lt; "Error parsing the string" &lt;&lt; endl; } for( Json::Value::const_iterator outer = root.begin() ; outer != root.end() ; outer++ ) { for( Json::Value::const_iterator inner = (*outer).begin() ; inner!= (*outer).end() ; inner++ ) { cout &lt;&lt; inner.key() &lt;&lt; ": " &lt;&lt; *inner &lt;&lt; endl; } } } </code></pre> <p>Traverse the root object directly, using iterators (don't treat it as it was an array.</p> <p>If <em>Json::Reader</em> doesn't work, try <em>Json::CharReader</em> instead: </p> <pre><code>void decode() { string text ="{\"1\":{\"name\":\"MIKE\",\"surname\":\"TAYLOR\"},\"2\":{\"name\":\"TOM\",\"surname\":\"JERRY\"}}"; Json::CharReaderBuilder builder; Json::CharReader * reader = builder.newCharReader(); Json::Value root; string errors; bool parsingSuccessful = reader-&gt;parse(text.c_str(), text.c_str() + text.size(), &amp;root, &amp;errors); delete reader; if ( !parsingSuccessful ) { cout &lt;&lt; text &lt;&lt; endl; cout &lt;&lt; errors &lt;&lt; endl; } for( Json::Value::const_iterator outer = root.begin() ; outer != root.end() ; outer++ ) { for( Json::Value::const_iterator inner = (*outer).begin() ; inner!= (*outer).end() ; inner++ ) { cout &lt;&lt; inner.key() &lt;&lt; ": " &lt;&lt; *inner &lt;&lt; endl; } } } </code></pre>
10,616,417
Debugging core files generated on a Customer's box
<p>We get core files from running our software on a Customer's box. Unfortunately because we've always compiled with -O2 <em>without</em> debugging symbols this has lead to situations where we could not figure out why it was crashing, we've modified the builds so now they generate -g and -O2 together. We then advice the Customer to run a -g binary so it becomes easier to debug.</p> <p>I have a few questions:</p> <ol> <li>What happens when a core file is generated from a Linux distro other than the one we are running in Dev? Is the stack trace even meaningful?</li> <li>Are there any good books for debugging on Linux, or Solaris? Something example oriented would be great. I am looking for real-life examples of figuring out why a routine crashed and how the author arrived at a solution. Something more on the intermediate to advanced level would be good, as I have been doing this for a while now. Some assembly would be good as well.</li> </ol> <p>Here's an example of a crash that requires us to tell the Customer to get a -g ver. of the binary:</p> <pre><code>Program terminated with signal 11, Segmentation fault. #0 0xffffe410 in __kernel_vsyscall () (gdb) where #0 0xffffe410 in __kernel_vsyscall () #1 0x00454ff1 in select () from /lib/libc.so.6 ... &lt;omitted frames&gt; </code></pre> <p>Ideally I'd like to solve find out why exactly the app crashed - I suspect it's memory corruption but I am not 100% sure.</p> <p>Remote debugging is strictly not allowed.</p> <p>Thanks</p>
10,629,444
5
1
null
2012-05-16 10:12:03.19 UTC
12
2021-09-22 04:39:45.207 UTC
null
null
null
null
241,993
null
1
10
c++|linux|debugging|gdb
15,107
<blockquote> <p>What happens when a core file is generated from a Linux distro other than the one we are running in Dev? Is the stack trace even meaningful?</p> </blockquote> <p>It the executable is dynamically linked, as yours is, the stack GDB produces will (most likely) <strong>not</strong> be meaningful.</p> <p>The reason: GDB knows that your executable crashed by calling something in <code>libc.so.6</code> at address <code>0x00454ff1</code>, but it doesn't know what code was at that address. So it looks into <em>your</em> copy of <code>libc.so.6</code> and discovers that this is in <code>select</code>, so it prints that.</p> <p>But the chances that <code>0x00454ff1</code> is also in select in your <em>customers</em> copy of <code>libc.so.6</code> are quite small. Most likely the customer had some other procedure at that address, perhaps <code>abort</code>.</p> <p>You can use <code>disas select</code>, and observe that <code>0x00454ff1</code> is either in the middle of instruction, or that the previous instruction is not a <code>CALL</code>. If either of these holds, your stack trace is meaningless.</p> <p>You <em>can</em> however help yourself: you just need to get a copy of all libraries that are listed in <code>(gdb) info shared</code> from the customer system. Have the customer tar them up with e.g.</p> <pre><code>cd / tar cvzf to-you.tar.gz lib/libc.so.6 lib/ld-linux.so.2 ... </code></pre> <p>Then, on your system:</p> <pre><code>mkdir /tmp/from-customer tar xzf to-you.tar.gz -C /tmp/from-customer gdb /path/to/binary (gdb) set solib-absolute-prefix /tmp/from-customer (gdb) core core # Note: very important to set solib-... before loading core (gdb) where # Get meaningful stack trace! </code></pre> <blockquote> <p>We then advice the Customer to run a -g binary so it becomes easier to debug.</p> </blockquote> <p>A <em>much</em> better approach is:</p> <ul> <li>build with <code>-g -O2 -o myexe.dbg</code></li> <li><code>strip -g myexe.dbg -o myexe</code></li> <li>distribute <code>myexe</code> to customers</li> <li>when a customer gets a <code>core</code>, use <code>myexe.dbg</code> to debug it</li> </ul> <p>You'll have full symbolic info (file/line, local variables), without having to ship a special binary to the customer, and without revealing too many details about your sources.</p>
10,836,843
ggplot2 plot area margins?
<p>Is there an easy way to increase the space between the plot title and plot area below it (i.e., the box with the data). Similarly, I'd prefer to have some space between the axis title and axis labels.</p> <p>In other words, is there a way to &quot;move the title a bit up, the y axis title a bit left, and the x axis title a bit down&quot;?</p>
10,840,417
1
1
null
2012-05-31 15:35:38.74 UTC
26
2022-01-06 00:36:59.363 UTC
2022-01-06 00:36:59.363 UTC
null
15,293,191
KT.
318,964
null
1
112
r|ggplot2|data-visualization
153,283
<p>You can adjust the plot margins with <code>plot.margin</code> in <code>theme()</code> and then move your axis labels and title with the <code>vjust</code> argument of <code>element_text()</code>. For example :</p> <pre><code>library(ggplot2) library(grid) qplot(rnorm(100)) + ggtitle("Title") + theme(axis.title.x=element_text(vjust=-2)) + theme(axis.title.y=element_text(angle=90, vjust=-0.5)) + theme(plot.title=element_text(size=15, vjust=3)) + theme(plot.margin = unit(c(1,1,1,1), "cm")) </code></pre> <p>will give you something like this :</p> <p><img src="https://i.stack.imgur.com/aHWbF.png" alt="enter image description here"></p> <p>If you want more informations about the different <code>theme()</code> parameters and their arguments, you can just enter <code>?theme</code> at the R prompt.</p>
22,592,064
How to align text below an image in CSS?
<p>HTML</p> <pre><code> &lt;div class=&quot;image1&quot;&gt; &lt;img src=&quot;images/img1.png&quot; width=&quot;250&quot; height=&quot;444&quot; alt=&quot;Screen 1&quot;/&gt; &lt;img src=&quot;images/img2.png&quot; width=&quot;250&quot; height=&quot;444&quot; alt=&quot;Screen 2&quot;/&gt; &lt;img src=&quot;../images/img3.png&quot; width=&quot;250&quot; height=&quot;444&quot; alt=&quot;Screen 3&quot;/&gt; &lt;/div&gt; </code></pre> <p>If I add a paragraph text between img1 and img2 they get separated (img2 goes to a newline)</p> <p>What I'm attempting to do is this (with some space between the images):</p> <pre><code>[image1] [image2] [image3] [text] [text] [text] </code></pre> <p>I haven't given the images their own individual class names because the images don't align horizontally to one another.</p>
22,592,136
7
1
null
2014-03-23 14:18:21.583 UTC
11
2021-12-11 22:27:08.13 UTC
2021-12-11 22:25:06.517 UTC
null
14,807,111
null
966,825
null
1
47
html|css
230,771
<p>Add a container div for the image and the caption:</p> <pre><code>&lt;div class="item"&gt; &lt;img src=""/&gt; &lt;span class="caption"&gt;Text below the image&lt;/span&gt; &lt;/div&gt; </code></pre> <p>Then, with a bit of CSS, you can make an automatically wrapping image gallery:</p> <pre><code>div.item { vertical-align: top; display: inline-block; text-align: center; width: 120px; } img { width: 100px; height: 100px; background-color: grey; } .caption { display: block; } </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>div.item { /* To correctly align image, regardless of content height: */ vertical-align: top; display: inline-block; /* To horizontally center images and caption */ text-align: center; /* The width of the container also implies margin around the images. */ width: 120px; } img { width: 100px; height: 100px; background-color: grey; } .caption { /* Make the caption a block so it occupies its own line. */ display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="item"&gt; &lt;img src=""/&gt; &lt;span class="caption"&gt;Text below the image&lt;/span&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img src=""/&gt; &lt;span class="caption"&gt;Text below the image&lt;/span&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img src=""/&gt; &lt;span class="caption"&gt;An even longer text below the image which should take up multiple lines.&lt;/span&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img src=""/&gt; &lt;span class="caption"&gt;Text below the image&lt;/span&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img src=""/&gt; &lt;span class="caption"&gt;Text below the image&lt;/span&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img src=""/&gt; &lt;span class="caption"&gt;An even longer text below the image which should take up multiple lines.&lt;/span&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/ZhLk4/1/" rel="noreferrer">http://jsfiddle.net/ZhLk4/1/</a></p> <p><strong>Updated answer</strong></p> <p>Instead of using 'anonymous' div and spans, you can also use the HTML5 <code>figure</code> and <code>figcaption</code> elements. The advantage is that these tags add to the semantic structure of the document. Visually there is no difference, but it may (positively) affect the usability and indexability of your pages.</p> <p>The tags are different, but the structure of the code is exactly the same, as you can see in this updated snippet and fiddle:</p> <pre class="lang-html prettyprint-override"><code>&lt;figure class="item"&gt; &lt;img src=""/&gt; &lt;figcaption class="caption"&gt;Text below the image&lt;/figcaption&gt; &lt;/figure&gt; </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>figure.item { /* To correctly align image, regardless of content height: */ vertical-align: top; display: inline-block; /* To horizontally center images and caption */ text-align: center; /* The width of the container also implies margin around the images. */ width: 120px; } img { width: 100px; height: 100px; background-color: grey; } .caption { /* Make the caption a block so it occupies its own line. */ display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;figure class="item"&gt; &lt;img src=""/&gt; &lt;figcaption class="caption"&gt;Text below the image&lt;/figcaption&gt; &lt;/figure&gt; &lt;figure class="item"&gt; &lt;img src=""/&gt; &lt;figcaption class="caption"&gt;Text below the image&lt;/figcaption&gt; &lt;/figure&gt; &lt;figure class="item"&gt; &lt;img src=""/&gt; &lt;figcaption class="caption"&gt;An even longer text below the image which should take up multiple lines.&lt;/figcaption&gt; &lt;/figure&gt; &lt;figure class="item"&gt; &lt;img src=""/&gt; &lt;figcaption class="caption"&gt;Text below the image&lt;/figcaption&gt; &lt;/figure&gt; &lt;figure class="item"&gt; &lt;img src=""/&gt; &lt;figcaption class="caption"&gt;Text below the image&lt;/figcaption&gt; &lt;/figure&gt; &lt;figure class="item"&gt; &lt;img src=""/&gt; &lt;figcaption class="caption"&gt;An even longer text below the image which should take up multiple lines.&lt;/figcaption&gt; &lt;/figure&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/ZhLk4/379/" rel="noreferrer">http://jsfiddle.net/ZhLk4/379/</a></p>
23,318,875
Iterating through a vector of pointers
<p>I'm trying to iterate through a Players hand of cards.</p> <pre><code>#include &lt;vector&gt; #include &lt;iostream&gt; class Card { int card_colour, card_type; public: std::string display_card(); }; std::string Card::display_card(){ std::stringstream s_card_details; s_card_details &lt;&lt; &quot;Colour: &quot; &lt;&lt; card_colour &lt;&lt; &quot;\n&quot;; s_card_details &lt;&lt; &quot;Type: &quot; &lt;&lt; card_type &lt;&lt; &quot;\n&quot;; return s_card_details.str(); } int main() { std::vector&lt;Card*&gt;current_cards; vector&lt;Card*&gt;::iterator iter; for(iter = current_cards.begin(); iter != current_cards.end(); iter++) { std::cout &lt;&lt; iter-&gt;display_card() &lt;&lt; std::endl; } } </code></pre> <p>This line</p> <pre><code>std::cout &lt;&lt; iter-&gt;display_card() &lt;&lt; std::endl; </code></pre> <p>currently comes up with the</p> <blockquote> <p>error: Expression must have pointer-to-class type.</p> </blockquote> <p>How can I fix this?</p>
23,318,902
4
1
null
2014-04-27 02:58:25.717 UTC
7
2021-10-02 04:13:26.447 UTC
2021-10-02 04:13:26.447 UTC
null
12,334,309
null
3,543,350
null
1
24
c++|pointers|object|vector
42,628
<p>Try this:</p> <pre><code>cout &lt;&lt; (*iter)-&gt;display_card() &lt;&lt; endl; </code></pre> <p>The <code>*</code> operator gives you the item referenced by the iterator, which in your case is a pointer. Then you use the <code>-&gt;</code> to dereference that pointer.</p>
18,885,255
Why can't LLDB print view.bounds?
<p>Things like this drive me crazy when debugging:</p> <pre><code>(lldb) p self.bounds error: unsupported expression with unknown type error: unsupported expression with unknown type error: 2 errors parsing expression (lldb) p (CGRect)self.bounds error: unsupported expression with unknown type error: unsupported expression with unknown type error: C-style cast from '&lt;unknown type&gt;' to 'CGRect' is not allowed error: 3 errors parsing expression (lldb) p [self bounds] error: 'bounds' has unknown return type; cast the call to its declared return type error: 1 errors parsing expression (lldb) p (CGRect)[self bounds] (CGRect) $1 = origin=(x=0, y=0) size=(width=320, height=238) (lldb) You suck! error: 'You' is not a valid command. (lldb) … </code></pre> <p>Why did the first 3 attempts fail? Is there any simpler way to print <code>self.bounds</code>? Thanks.</p>
30,312,765
8
1
null
2013-09-19 02:16:16.48 UTC
13
2016-10-30 11:45:42.7 UTC
null
null
null
null
56,149
null
1
56
objective-c|lldb
12,805
<p>Starting from Xcode 6.3, we have a better solution. In short, you need to import UIKit for LLDB to know about these types: <code>expr @import UIKit</code>. Check out <a href="http://furbo.org/2015/05/11/an-import-ant-change-in-xcode/" rel="noreferrer">this article</a> to learn some tricks to make your life even easier.</p>
35,390,928
How To Send json Object to the server from my android app
<p>I'm at a bit of a loss as to how to send a <code>json</code>object from my android application to the database</p> <p>As I am new to this I'm not too sure where I've gone wrong, I've pulled the data from the <code>XML</code> and I have no clue how to then post the object to our server.</p> <p>any advice would be really appreciated</p> <pre><code> package mmu.tom.linkedviewproject; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; /** * Created by Tom on 12/02/2016. */ public class DeviceDetailsActivity extends AppCompatActivity { private EditText address; private EditText name; private EditText manufacturer; private EditText location; private EditText type; private EditText deviceID; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_device_details); ImageButton button1 = (ImageButton) findViewById(R.id.image_button_back); button1.setOnClickListener(new View.OnClickListener() { Class ourClass; public void onClick(View v) { Intent intent = new Intent(DeviceDetailsActivity.this, MainActivity.class); startActivity(intent); } }); Button submitButton = (Button) findViewById(R.id.submit_button); submitButton.setOnClickListener(new View.OnClickListener() { Class ourClass; public void onClick(View v) { sendDeviceDetails(); } }); setContentView(R.layout.activity_device_details); this.address = (EditText) this.findViewById(R.id.edit_address); this.name = (EditText) this.findViewById(R.id.edit_name); this.manufacturer = (EditText) this.findViewById(R.id.edit_manufacturer); this.location = (EditText) this.findViewById(R.id.edit_location); this.type = (EditText) this.findViewById(R.id.edit_type); this.deviceID = (EditText) this.findViewById(R.id.edit_device_id); } protected void onPostExecute(JSONArray jsonArray) { try { JSONObject device = jsonArray.getJSONObject(0); name.setText(device.getString(&quot;name&quot;)); address.setText(device.getString(&quot;address&quot;)); location.setText(device.getString(&quot;location&quot;)); manufacturer.setText(device.getString(&quot;manufacturer&quot;)); type.setText(device.getString(&quot;type&quot;)); } catch(Exception e){ e.printStackTrace(); } } public JSONArray sendDeviceDetails() { // URL for getting all customers String url = &quot;http://IP-ADDRESS:8080/IOTProjectServer/registerDevice?&quot;; // Get HttpResponse Object from url. // Get HttpEntity from Http Response Object HttpEntity httpEntity = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); // Default HttpClient HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); httpEntity = httpResponse.getEntity(); } catch (ClientProtocolException e) { // Signals error in http protocol e.printStackTrace(); //Log Errors Here } catch (IOException e) { e.printStackTrace(); } // Convert HttpEntity into JSON Array JSONArray jsonArray = null; if (httpEntity != null) { try { String entityResponse = EntityUtils.toString(httpEntity); Log.e(&quot;Entity Response : &quot;, entityResponse); jsonArray = new JSONArray(entityResponse); } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return jsonArray; } } </code></pre>
35,391,133
4
2
null
2016-02-14 10:54:58.017 UTC
6
2020-07-29 13:22:40.977 UTC
2020-07-29 12:31:55.797 UTC
null
4,166,017
null
4,166,017
null
1
13
android|json
63,348
<p>You need to be using an <code>AsyncTask</code> class to communicate with your server. Something like this:</p> <p>This is in your <code>onCreate</code> method.</p> <pre><code>Button submitButton = (Button) findViewById(R.id.submit_button); submitButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { JSONObject postData = new JSONObject(); try { postData.put("name", name.getText().toString()); postData.put("address", address.getText().toString()); postData.put("manufacturer", manufacturer.getText().toString()); postData.put("location", location.getText().toString()); postData.put("type", type.getText().toString()); postData.put("deviceID", deviceID.getText().toString()); new SendDeviceDetails().execute("http://52.88.194.67:8080/IOTProjectServer/registerDevice", postData.toString()); } catch (JSONException e) { e.printStackTrace(); } } }); </code></pre> <p>This is a new class within you activity class.</p> <pre><code>private class SendDeviceDetails extends AsyncTask&lt;String, Void, String&gt; { @Override protected String doInBackground(String... params) { String data = ""; HttpURLConnection httpURLConnection = null; try { httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream()); wr.writeBytes("PostData=" + params[1]); wr.flush(); wr.close(); InputStream in = httpURLConnection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(in); int inputStreamData = inputStreamReader.read(); while (inputStreamData != -1) { char current = (char) inputStreamData; inputStreamData = inputStreamReader.read(); data += current; } } catch (Exception e) { e.printStackTrace(); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); } } return data; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Log.e("TAG", result); // this is expecting a response code to be sent from your server upon receiving the POST data } } </code></pre> <p>The line: <code>httpURLConnection.setRequestMethod("POST");</code> makes this an HTTP POST request and should be handled as a POST request on your server.</p> <p>Then on your server you will need to create a new JSON object from the "PostData" which has been sent in the HTTP POST request. If you let us know what language you are using on your server then we can write up some code for you.</p>
3,499,095
How do you tint a bitmap in Android?
<p>I draw a bitmap onto a canvas using the following call:</p> <pre><code>_playerImage = BitmapFactory.decodeResource(getResources(), R.drawable.player); </code></pre> <p>How can I now tint this image white? I'm trying to make the image flash white like in top-scrollers when an enemy is hit by a bullet.</p> <p>Do I need to use something other than BitmapFactory?</p>
3,499,103
1
0
null
2010-08-17 03:20:46.037 UTC
15
2015-01-10 19:56:22.983 UTC
null
null
null
null
386,764
null
1
19
android|image|bitmap
21,498
<p>You can use a <code>ColorFilter</code> on your <code>Paint</code> when you draw the bitmap.</p>
21,066,077
Remove fill around legend key in ggplot
<p>I would like to remove the gray rectangle around the legend. I have tried various methods but none have worked.</p> <pre><code>ggtheme &lt;- theme( axis.text.x = element_text(colour='black'), axis.text.y = element_text(colour='black'), panel.background = element_blank(), panel.grid.minor = element_blank(), panel.grid.major = element_blank(), panel.border = element_rect(colour='black', fill=NA), strip.background = element_blank(), legend.justification = c(0, 1), legend.position = c(0, 1), legend.background = element_rect(colour = NA), legend.key = element_rect(colour = "white", fill = NA), legend.title = element_blank() ) colors &lt;- c("red", "blue") df &lt;- data.frame(year = c(1:10), value = c(10:19), gender = rep(c("male","female"),each=5)) ggplot(df, aes(x = year, y = value)) + geom_point(aes(colour=gender)) + stat_smooth(method = "loess", formula = y ~ x, level=0, size = 1, aes(group = gender, colour=gender)) + ggtheme + scale_color_manual(values = colors) </code></pre> <p><a href="https://i.stack.imgur.com/PLOFd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PLOFd.png" alt="enter image description here"></a></p>
21,066,173
3
2
null
2014-01-11 18:18:45.42 UTC
8
2018-04-08 07:31:32.523 UTC
2018-04-08 07:31:32.523 UTC
null
1,457,380
null
2,047,482
null
1
40
r|ggplot2
49,789
<p>You get this grey color inside legend keys because you use <code>stat_smooth()</code> that as default makes also confidence interval around the line with some fill (grey if <code>fill=</code> isn't used inside the <code>aes()</code>).</p> <p>One solution is to set <code>se=FALSE</code> for <code>stat_smooth()</code> if you don't need the confidence intervals.</p> <pre><code> +stat_smooth(method = "loess", formula = y ~ x, level=0, size = 1, aes(group = gender, colour=gender),se=FALSE) </code></pre> <p>Another solution is to use the function <code>guides()</code> and <code>override.aes=</code> to remove fill from the legend but keep confidence intervals around lines.</p> <pre><code> + guides(color=guide_legend(override.aes=list(fill=NA))) </code></pre>
21,004,335
HTML5 video won't play in Chrome only
<h2>some background</h2> <p>I've tested my video in FF and Safari (including iDevices) and it plays properly, but it will not play in the Chrome browser. As you can see in the code below, I've created mp4, m4v, webM, and ogv files, and I've tested all of them on my computer for any playback issues.</p> <h2>the symptoms/issue</h2> <p>In Chrome, the video seems to load, and there are <b>no errors in the console log</b>. When the play button is pressed, it loads a portion of the file, but then does not play it. Yet, interestingly, if I arbitrarily click on a later time in the time-bar, say about halfway through, it will play about 5 seconds of the video even with the subtitles, but <b>no</b> audio.</p> <h2>my research</h2> <p>I've read up on any issues that might be causing this, but I haven't found any ideas that work. To note, I've written the following in my .htaccess file:</p> <pre><code># ---------------------------------------------------------------------- # Proper MIME type for all files # ---------------------------------------------------------------------- # Audio AddType audio/ogg oga ogg AddType audio/mp4 m4a AddType audio/webm webm # Video AddType video/ogg ogv AddType video/mp4 mp4 m4v AddType video/webm webm # Assorted types AddType image/x-icon ico AddType image/webp webp AddType text/cache-manifest appcache manifest AddType text/x-component htc AddType application/x-chrome-extension crx AddType application/x-opera-extension oex AddType application/x-xpinstall xpi AddType application/octet-stream safariextz AddType application/x-web-app-manifest+json webapp AddType text/x-vcard vcf AddType text/plain srt </code></pre> <p>Also, I am using the mediaelement.js library.</p> <h2>the code</h2> <p>Here's the HTML:</p> <pre><code>&lt;video width=&quot;100%&quot; height=&quot;400&quot; poster=&quot;assets/img/myVideo.jpg&quot; controls=&quot;controls&quot; preload=&quot;none&quot;&gt; &lt;!-- M4V for Apple --&gt; &lt;source type=&quot;video/mp4&quot; src=&quot;assets/vid/PhysicsEtoys.m4v&quot; /&gt; &lt;!-- MP4 for Safari, IE9, iPhone, iPad, Android, and Windows Phone 7 --&gt; &lt;source type=&quot;video/mp4&quot; src=&quot;assets/vid/PhysicsEtoys.mp4&quot; /&gt; &lt;!-- WebM/VP8 for Firefox4, Opera, and Chrome --&gt; &lt;source type=&quot;video/webm&quot; src=&quot;assets/vid/PhysicsEtoys.webm&quot; /&gt; &lt;!-- Ogg/Vorbis for older Firefox and Opera versions --&gt; &lt;source type=&quot;video/ogg&quot; src=&quot;assets/vid/PhysicsEtoys.ogv&quot; /&gt; &lt;!-- Subtitles --&gt; &lt;track kind=&quot;subtitles&quot; src=&quot;assets/vid/subtitles.srt&quot; srclang=&quot;en&quot; /&gt; &lt;track kind=&quot;subtitles&quot; src=&quot;assets/vid/subtitles.vtt&quot; srclang=&quot;en&quot; /&gt; &lt;!-- Flash fallback for non-HTML5 browsers without JavaScript --&gt; &lt;object width=&quot;100%&quot; height=&quot;400&quot; type=&quot;application/x-shockwave-flash&quot; data=&quot;flashmediaelement.swf&quot;&gt; &lt;param name=&quot;movie&quot; value=&quot;flashmediaelement.swf&quot; /&gt; &lt;param name=&quot;flashvars&quot; value=&quot;controls=true&amp;file=assets/vid/PhysicsEtoys.mp4&quot; /&gt; &lt;!-- Image as a last resort --&gt; &lt;img src=&quot;assets/img/myVideo.jpg&quot; width=&quot;320&quot; height=&quot;240&quot; title=&quot;No video playback capabilities&quot; /&gt; &lt;/object&gt; &lt;/video&gt; </code></pre> <p>Here's the simple js:</p> <pre><code>$('video,audio').mediaelementplayer({ features: ['playpause','progress','current','tracks','volume'], startLanguage: 'en' }); </code></pre> <p>Any ideas?</p> <p>Thanks for any and all help in this matter!</p>
21,023,787
8
3
null
2014-01-08 19:03:33.277 UTC
6
2022-07-22 19:16:00.083 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
2,236,423
null
1
25
html|google-chrome|html5-video|mediaelement.js
112,644
<p>With some help from another person, we figured out it was an issue of ordering the source files within the HTML file. I learned that browsers accept the first usable format, and their seems to be an issue with the .m4v file, so I started with the .mp4, then .webm. Here's the order that works in Safari (even on my iPhone 5), Firefox, <b>and Chrome</b>:</p> <pre><code>&lt;video width="100%" height="400" poster="assets/img/myVideo.jpg" controls="controls" preload="none"&gt; &lt;!-- MP4 for Safari, IE9, iPhone, iPad, Android, and Windows Phone 7 --&gt; &lt;source type="video/mp4" src="assets/vid/PhysicsEtoys.mp4" /&gt; &lt;!-- WebM/VP8 for Firefox4, Opera, and Chrome --&gt; &lt;source type="video/webm" src="assets/vid/PhysicsEtoys.webm" /&gt; &lt;!-- M4V for Apple --&gt; &lt;source type="video/mp4" src="assets/vid/PhysicsEtoys.m4v" /&gt; &lt;!-- Ogg/Vorbis for older Firefox and Opera versions --&gt; &lt;source type="video/ogg" src="assets/vid/PhysicsEtoys.ogv" /&gt; &lt;!-- Subtitles --&gt; &lt;track kind="subtitles" src="assets/vid/subtitles.srt" srclang="en" /&gt; &lt;track kind="subtitles" src="assets/vid/subtitles.vtt" srclang="en" /&gt; &lt;!-- Flash fallback for non-HTML5 browsers without JavaScript --&gt; &lt;object width="100%" height="400" type="application/x-shockwave-flash" data="flashmediaelement.swf"&gt; &lt;param name="movie" value="flashmediaelement.swf" /&gt; &lt;param name="flashvars" value="controls=true&amp;file=assets/vid/PhysicsEtoys.mp4" /&gt; &lt;!-- Image as a last resort --&gt; &lt;img src="assets/img/myVideo.jpg" width="320" height="240" title="No video playback capabilities" /&gt; &lt;/object&gt; &lt;/video&gt; </code></pre> <p>Now, I'll have to re-check the encoding on the m4v file (perhaps an issue of Baseline vs Main, High, etc.).</p>
28,201,794
Slow startup on Tomcat 7.0.57 because of SecureRandom
<p>I'm using Tomcat 7.0.57 on CentOS 6.6 32 bit and openJDK7. When I start 14 different instances of Tomcat on my server(production environment), many of them take too much time to start.</p> <p>This is part of the startup log, which tells me where is taking all the time</p> <pre><code>Jan 28, 2015 2:49:41 PM org.apache.catalina.util.SessionIdGenerator createSecureRandom INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [199,620] milliseconds. </code></pre> <p>What's the best practice/solution for this problem?</p> <p>Thanks!</p>
28,202,322
8
2
null
2015-01-28 20:28:40.49 UTC
9
2021-11-01 12:15:46.76 UTC
null
null
null
null
4,470,833
null
1
37
java|tomcat7
42,846
<p>The secure random calls may be blocking as there is not enough entropy to feed them in /dev/random.</p> <p>If you have the line </p> <pre><code>securerandom.source=file:/dev/random </code></pre> <p>in /jre/lib/security/java.security, changing this to urandom may improve things (although this is probably already the default).</p> <p>Alternatively there are some suggestions on how to feed the pool here</p> <p><a href="https://security.stackexchange.com/questions/89/feeding-dev-random-entropy-pool">https://security.stackexchange.com/questions/89/feeding-dev-random-entropy-pool</a></p>
1,715,772
Best way to decode unknown unicoding encoding in Python 2.5
<p>Have I got that all the right way round? Anyway, I am parsing a lot of html, but I don't always know what encoding it's meant to be (a surprising number lie about it). The code below easily shows what I've been doing so far, but I'm sure there's a better way. Your suggestions would be much appreciated.</p> <pre><code>import logging import codecs from utils.error import Error class UnicodingError(Error): pass # these encodings should be in most likely order to save time encodings = [ "ascii", "utf_8", "big5", "big5hkscs", "cp037", "cp424", "cp437", "cp500", "cp737", "cp775", "cp850", "cp852", "cp855", "cp856", "cp857", "cp860", "cp861", "cp862", "cp863", "cp864", "cp865", "cp866", "cp869", "cp874", "cp875", "cp932", "cp949", "cp950", "cp1006", "cp1026", "cp1140", "cp1250", "cp1251", "cp1252", "cp1253", "cp1254", "cp1255", "cp1256", "cp1257", "cp1258", "euc_jp", "euc_jis_2004", "euc_jisx0213", "euc_kr", "gb2312", "gbk", "gb18030", "hz", "iso2022_jp", "iso2022_jp_1", "iso2022_jp_2", "iso2022_jp_2004", "iso2022_jp_3", "iso2022_jp_ext", "iso2022_kr", "latin_1", "iso8859_2", "iso8859_3", "iso8859_4", "iso8859_5", "iso8859_6", "iso8859_7", "iso8859_8", "iso8859_9", "iso8859_10", "iso8859_13", "iso8859_14", "iso8859_15", "johab", "koi8_r", "koi8_u", "mac_cyrillic", "mac_greek", "mac_iceland", "mac_latin2", "mac_roman", "mac_turkish", "ptcp154", "shift_jis", "shift_jis_2004", "shift_jisx0213", "utf_32", "utf_32_be", "utf_32_le", "utf_16", "utf_16_be", "utf_16_le", "utf_7", "utf_8_sig" ] def unicode(string): '''make unicode''' for enc in self.encodings: try: logging.debug("unicoder is trying " + enc + " encoding") utf8 = unicode(string, enc) logging.info("unicoder is using " + enc + " encoding") return utf8 except UnicodingError: if enc == self.encodings[-1]: raise UnicodingError("still don't recognise encoding after trying do guess.") </code></pre>
1,715,913
3
2
null
2009-11-11 15:06:57.553 UTC
9
2017-01-30 13:32:21.723 UTC
2010-01-28 05:27:13.83 UTC
null
60,075
null
132,262
null
1
7
python|html|unicode|encoding|character-encoding
11,367
<p>There are two general purpose libraries for detecting unknown encodings:</p> <ul> <li>chardet, part of <a href="http://feedparser.org" rel="noreferrer">Universal Feed Parser</a></li> <li>UnicodeDammit, part of <a href="http://www.crummy.com/software/BeautifulSoup/" rel="noreferrer">Beautiful Soup</a></li> </ul> <p>chardet is supposed to be a port of the <a href="http://www.mozilla.org/projects/intl/chardet.html" rel="noreferrer">way that firefox does it</a></p> <p>You can use the following regex to detect utf8 from byte strings:</p> <pre><code>import re utf8_detector = re.compile(r"""^(?: [\x09\x0A\x0D\x20-\x7E] # ASCII | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16 )*$""", re.X) </code></pre> <p>In practice if you're dealing with English I've found the following works 99.9% of the time:</p> <ol> <li>if it passes the above regex, it's ascii or utf8</li> <li>if it contains any bytes from 0x80-0x9f but not 0xa4, it's Windows-1252</li> <li>if it contains 0xa4, assume it's latin-15</li> <li>otherwise assume it's latin-1</li> </ol>
1,859,113
Append date and time to an environment variable in linux makefile
<p>In my Makefile I want to create an environment variable using the current date and time. Pseudo code:</p> <pre><code>LOG_FILE := $LOG_PATH + $SYSTEM_DATE + $SYSTEM_TIME </code></pre> <p>Any help appreciated - thanks.</p>
1,859,205
3
0
null
2009-12-07 10:23:35.263 UTC
4
2019-11-10 02:17:56.807 UTC
2015-11-28 14:38:00.49 UTC
null
4,640,499
null
36,860
null
1
30
makefile|environment-variables
49,062
<p>you can use this:</p> <pre><code>LOGFILE=$(LOGPATH) `date +'%y.%m.%d %H:%M:%S'` </code></pre> <p>NOTE (from comments): </p> <p>it will cause LOGFILE to be evaluated every time while used. to avoid that:</p> <pre><code>LOGFILE=$(LOGPATH)$(shell date) </code></pre>
8,628,326
What is the difference between a wrapper, a binding, and a port?
<p>In a software portability context, what is the difference between these three concepts?</p> <p>For example, I want to use the <a href="https://en.wikipedia.org/wiki/Ncurses" rel="noreferrer">ncurses</a> library, the original ncurses library is written in C, but my application is being written in C++, and then I found "ncurses wrapper", "bindings to ncurses", and "ncurses port". Which one should I use?</p> <p>What are the pros and cons of each one?</p>
8,628,481
2
1
null
2011-12-25 05:15:37.507 UTC
34
2019-11-21 14:14:46.753 UTC
2019-11-21 14:14:46.753 UTC
null
63,550
null
478,249
null
1
34
binding|port|wrapper|portability
8,946
<p>A <a href="http://en.wikipedia.org/wiki/Wrapper_library" rel="noreferrer">wrapper</a> is a bit of code that sits on top of other code to recycle it's functionality but with a different interface. This usually implies an interface written in the same language. It should also be noted that sometimes people will say wrapper when what they technically mean is a binding (myself included).</p> <p>Pros: </p> <ul> <li>It's in the same language as the original</li> <li>Wrappers enhance or reuse functionality without needing a full rewrite.</li> <li>Relatively quick to accomplish</li> <li>Trivial updates when the source library changes. You'll probably only need to bind new functions unless they broke backwards compatibility by changing expected input/outputs of functions/classes.</li> </ul> <p>Cons:</p> <ul> <li>Wrapping an entire library can be extremely repetitive</li> </ul> <p>A <a href="http://en.wikipedia.org/wiki/Language_binding" rel="noreferrer">binding</a> is another bit of code that sits on top of other code to recycle it's functionality except this time bindings are written in a language different than the thing they bind. A notable example is PyQt which is the python binding for QT.</p> <p>Pros:</p> <ul> <li>Bring functionality from another language into the language of your choice.</li> <li>Relatively fast in comparison to a port</li> <li>Same level of trivial changes are needed as in wrapping- You'll probably only need to wrap new functions/classes unless they broke backwards compatibility by changing expected input/outputs of functions/classes.</li> </ul> <p>Cons:</p> <ul> <li>Just as repetitive as a wrapper</li> <li>You're probably taking a fairly large performance hit, especially any wrapper involving an interpreted language on either end</li> </ul> <p>A <a href="http://en.wikipedia.org/wiki/Porting" rel="noreferrer">Port</a> is when you translate some code to work in a different environment. Common analogies include games that come out for say... XBox and are later released for PS3.</p> <p>Pros:</p> <ul> <li>Gives you the opportunity to make improvements to the code base as you see inadequacies</li> <li>You'll be intimately familiar with HOW the code runs, not just what it does.</li> </ul> <p>Cons:</p> <ul> <li>By far the lengthiest solution in terms of time/requires a complete rewrite</li> <li>You need to make sure that whatever functionality the source library needs in a language is available in your target port language or you'll end up wrapping needed functionality (and potentially defeating the purpose.)</li> <li>Every time the source library updates, you have to update too by translating whatever changes they made or risk falling behind.</li> </ul>
26,967,509
AttributeError: '_io.TextIOWrapper' object has no attribute 'next' python
<p>I am using python 3.3.3. I am doing the tutorial from tutorialspoint.com. I am unable to understand what this error is.</p> <p>Here is my code:</p> <pre><code>fo = open("foo.txt", "w") print ("Name of the file: ", fo.name) # Assuming file has following 5 lines # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line seq = ["This is 6th line\n", "This is 7th line"] # Write sequence of lines at the end of the file. fo.seek(0, 2) line = fo.writelines( seq ) # Now read complete file from beginning. fo.seek(0,0) for index in range(7): # line = fo.next() print ("Line No %d - %s" % (index, line)+"\n") # Close opend file fo.close() </code></pre> <p>Error: </p> <pre><code>Name of the file: foo.txt Traceback (most recent call last): File "C:/Users/DELL/Desktop/python/s/fyp/filewrite.py", line 19, in &lt;module&gt; line = fo.next() AttributeError: '_io.TextIOWrapper' object has no attribute 'next' </code></pre>
26,967,622
4
3
null
2014-11-17 07:23:31.753 UTC
2
2021-02-24 20:48:54.617 UTC
2015-01-10 17:35:56.617 UTC
null
2,379,433
user3185892
null
null
1
28
python
59,805
<p>There's two reasons you're running into issues here. The first is that you've created <code>fo</code> in write-only mode. You need a file object that can read and write. You can also use the <code>with</code> keyword to automatically destruct a file object after you're done with it, rather than having to worry about closing it manually:</p> <pre><code># the plus sign means "and write also" with open("foo.txt", "r+") as fo: # do write operations here # do read operations here </code></pre> <p>The second is that (like the error you've pasted very strongly suggests) the file object <code>fo</code>, a text file object, doesn't have a <code>next</code> method. You're using an tutorial written for Python 2.x, but you're using Python 3.x. This isn't going to go well for you. (I believe <code>next</code> was/maybe is valid in Python 2.x, but it is not in 3.x.) Rather, what's most analogous to <code>next</code> in Python 3.x is <code>readline</code>, like so:</p> <pre><code>for index in range(7): line = fo.readline() print("Line No %d - %s % (index, line) + "\n") </code></pre> <p>Note that this will only work if the file has at least 7 lines. Otherwise, you'll encounter an exception. A safer, and simpler way of iterating through a text file is with a for loop:</p> <pre><code>index = 0 for line in file: print("Line No %d - %s % (index, line) + "\n") index += 1 </code></pre> <p>Or, if you wanted to get a little more pythonic, you could use the <a href="https://docs.python.org/3.4/library/functions.html#enumerate" rel="noreferrer">enumerate</a> function:</p> <pre><code>for index, line in enumerate(file): print("Line No %d - %s % (index, line) + "\n") </code></pre>
731,049
How to print a ReportViewer's report without showing a form
<p>While I realize that I could just show the form off-screen and hide it, along with many other forms of WinForms hackish wizardry, I'd rather stick with the zen path and get this done right. I have a SSRS local report (so no server) that I want to give the user the option of either viewing or printing (in other words, I don't want to force them to view to print). Unfortunately, the ReportViewer control complains about its "state" when I try to print it either as a component I'm creating explicitly in my code (inside a using() block, of course) or if I try to instantiate my viewer form and just print without ever showing it.</p> <p>Is there a means to do this that will sit well with me, or should I just show it off-screen and move on with my life?</p>
742,401
4
0
null
2009-04-08 17:46:23.777 UTC
5
2019-06-18 16:08:46.273 UTC
null
null
null
null
82,187
null
1
14
c#|.net|reporting-services
51,090
<p>I have a sample that does this posted on my blog here: <a href="http://blogs.msdn.com/brianhartman/archive/2009/02/27/manually-printing-a-report.aspx" rel="noreferrer">http://blogs.msdn.com/brianhartman/archive/2009/02/27/manually-printing-a-report.aspx</a></p> <p>The LocalReport object can be instantiated independently of the ReportViewer control and used directly in the sample code attached to that blog post. Or you can pass in ReportViewer.LocalReport even if you don't first display the report in the UI.</p>
74,986
XBAP Application, can these work in Google Chrome?
<p>I'm developing a .NET 3.5 XBAP application that runs perfectly fine in FF3 and IE6/7 etc. I'm just wondering if its possible to get these to run under other browsers, specifically (as its in the limelight at the moment) Google Chrome.</p>
588,987
4
0
null
2008-09-16 17:45:57.853 UTC
10
2012-10-21 14:12:08.07 UTC
null
null
null
Kieran Benton
5,777
null
1
24
c#|.net|google-chrome|xbap
32,570
<p>XBAP applications do work in google chrome, however you have to set your environments PATH variable to the directory where xpcom.dll is located.</p> <p>for example SET PATH=PATH;"C:\Program Files\Mozilla Firefox"</p>
663,059
Why do inner classes make private methods accessible?
<p>I don't understand why this compiles. f() and g() are visible from the inner classes, despite being private. Are they treated special specially because they are inner classes?</p> <p>If A and B are not static classes, it's still the same.</p> <pre><code>class NotPrivate { private static class A { private void f() { new B().g(); } } private static class B { private void g() { new A().f(); } } } </code></pre>
663,147
4
2
null
2009-03-19 17:01:44.287 UTC
15
2019-04-23 12:27:17.147 UTC
2013-01-04 11:40:58.807 UTC
null
1,670,258
mparaz
48,256
null
1
32
java|inner-classes
15,745
<p>(Edit: expanded on the answer to answer some of the comments)</p> <p>The compiler takes the inner classes and turns them into top-level classes. Since private methods are only available to the inner class the compiler has to add new "synthetic" methods that have package level access so that the top-level classes have access to it. </p> <p>Something like this (the $ ones are added by the compiler):</p> <pre><code>class A { private void f() { final B b; b = new B(); // call changed by the compiler b.$g(); } // method generated by the compiler - visible by classes in the same package void $f() { f(); } } class B { private void g() { final A a; a = new A(); // call changed by the compiler a.$f(); } // method generated by the compiler - visible by classes in the same package void $g() { g(); } } </code></pre> <p>Non-static classes are the same, but they have the addition of a reference to the outer class so that the methods can be called on it.</p> <p>The reason Java does it this way is that they did not want to require VM changes to support inner classes, so all of the changes had to be at the compiler level. </p> <p>The compiler takes the inner class and turns it into a top level class (thus, at the VM level there is no such thing as an inner class). The compiler then also has to generate the new "forwarding" methods. They are made at the package level (not public) to ensure that only classes in the same package can access them. The compiler also updated the method calls to the private methods to the generated "forwarding" methods.</p> <p>You can avoid having the compiler generate the method my declaring the methods as "package" (the absence of public, private, and protected). The downside to that is that any class in the package can call the methods.</p> <p>Edit:</p> <p>Yes, you can call the generated (synthetic) method, but DON'T DO THIS!:</p> <pre><code>import java.lang.reflect.Constructor; import java.lang.reflect.Method; public class Main { public static void main(final String[] argv) throws Exception { final Class&lt;?&gt; clazz; clazz = Class.forName("NotPrivate$A"); for(final Method method : clazz.getDeclaredMethods()) { if(method.isSynthetic()) { final Constructor constructor; final Object instance; constructor = clazz.getDeclaredConstructor(new Class[0]); constructor.setAccessible(true); instance = constructor.newInstance(); method.setAccessible(true); method.invoke(null, instance); } } } } </code></pre>
837,752
Setting the TabIndex property of many form controls in Visual Studio?
<p>What is the most efficient way to set/re-order the TabIndex properties of many form controls in Visual Studio? When I change the layout on a large form, or even on initial design, I often wonder if there's a faster way than clicking each individual control then setting the TabIndex in the properties window.</p>
837,787
4
2
null
2009-05-08 00:48:53.82 UTC
7
2022-01-07 15:06:12.297 UTC
2019-02-13 22:56:27.22 UTC
null
43,846
null
101,915
null
1
54
winforms
43,486
<p>While in Designer mode, select Tab Order from the View menu then click on each control in the order you want. Then <strong>remember to turn off Tab Order when you're finished</strong>, otherwise when you select a control to do something else you lose the work you've just done (I wish Tab Order would turn off when you Save..)</p>
51,761,599
Cannot find stdio.h
<p>I am using macOS.</p> <p>I am trying to build the code of mozilla-central.</p> <p>While running the command <code>./mach build</code>, the build fails at the compile step. Here are the relevant stack traces:</p> <pre><code>stack backtrace: 0:20.24 0: 0x10436b5ff - std::sys::unix::backtrace::tracing::imp::unwind_backtrace::hed04c7a1477ef1e3 0:20.24 1: 0x10434499d - std::sys_common::backtrace::print::h336400f22676933f 0:20.24 2: 0x104373bd3 - std::panicking::default_hook::{{closure}}::h0d6700a02d682978 0:20.24 3: 0x10437395c - std::panicking::default_hook::h90363c6d6ac04260 0:20.24 4: 0x1043742fb - std::panicking::rust_panic_with_hook::h81c4f3add25e6667 0:20.24 5: 0x1043740ce - std::panicking::continue_panic_fmt::hfa057b7c1de88179 0:20.24 6: 0x104374020 - std::panicking::begin_panic_fmt::hd1123702300ea9f2 0:20.24 7: 0x1035f4e6d - build_script_build::build_gecko::bindings::write_binding_file::h2d9a397b93e6a614 0:20.24 8: 0x1035f651c - build_script_build::build_gecko::bindings::generate_bindings::ha066bc11b076e01d 0:20.24 9: 0x1043808fe - __rust_maybe_catch_panic 0:20.24 10: 0x1035eea9f - std::panicking::try::hcbd901ede6e8004c 0:20.32 11: 0x1035e335c - &lt;F as alloc::boxed::FnBox&lt;A&gt;&gt;::call_box::h638a7c5eb8c94414 0:20.33 12: 0x104373037 - std::sys_common::thread::start_thread::h78b1dd404be976ad 0:20.33 13: 0x1043436c8 - std::sys::unix::thread::Thread::new::thread_start::h27c6becca8cf44e0 0:20.33 14: 0x7fff636208cc - _pthread_body 0:20.33 15: 0x7fff6362083e - _pthread_start 0:20.33 /usr/local/Cellar/llvm/6.0.1/include/c++/v1/stdio.h:108:15: fatal error: 'stdio.h' file not found 0:20.33 /usr/local/Cellar/llvm/6.0.1/include/c++/v1/stdio.h:108:15: fatal error: 'stdio.h' file not found, err: true 0:20.37 thread '&lt;unnamed&gt;' panicked at 'Failed to generate bindings </code></pre> <p>According to me, the root cause is:</p> <pre><code>/usr/local/Cellar/llvm/6.0.1/include/c++/v1/stdio.h:108:15: fatal error: 'stdio.h' file not found, err: true </code></pre> <p>The solution listed online was to install xcode command line tools using:</p> <pre><code>xcode-select --install </code></pre> <p>I have already done this.</p>
52,511,046
7
0
null
2018-08-09 07:53:49.463 UTC
7
2022-01-25 09:46:41.48 UTC
2018-08-13 18:26:19.627 UTC
null
3,048,763
null
6,451,802
null
1
28
macos
35,950
<p>The root reason is due to a missing <code>/usr/include</code> directory.</p> <p>Installing command-line tools (<code>xcode-select --install</code>), sometimes, will not automatically add it. </p> <p>The <a href="https://forums.developer.apple.com/thread/104296" rel="noreferrer">Link</a> shows the correct way: After installing command-line tools Install the package at:</p> <pre><code># run this in Terminal open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg </code></pre> <p>After that,</p> <p>you should have a directory <code>/usr/include</code> with header files</p>
52,473,974
Binding PlayerView with SimpleExoPlayer from a service
<p>I have implemented a Service to run the audio in background which runs perfectly but I am unable to get the instance of the SimpleExoPlayer from the service to the activity to update the UI and also the Audio plays twice in the background if I exit and reopen the activity.</p> <p><strong>AudioPlayerService</strong></p> <pre><code>public class AudioPlayerService extends Service { private final IBinder mBinder = new LocalBinder(); private SimpleExoPlayer player; private Item item; private PlayerNotificationManager playerNotificationManager; @Override public void onCreate() { super.onCreate(); } @Override public void onDestroy() { playerNotificationManager.setPlayer(null); player.release(); player = null; super.onDestroy(); } @Nullable @Override public IBinder onBind(Intent intent) { return mBinder; } enter code here public SimpleExoPlayer getplayerInstance() { return player; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Bundle b = intent.getBundleExtra(AppConstants.BUNDLE_KEY); if (b != null) { item = b.getParcelable(AppConstants.ITEM_KEY); } startPlayer(); return START_STICKY; } private void startPlayer() { final Context context = this; Uri uri = Uri.parse(item.getUrl()); player = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector()); DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(context, Util.getUserAgent(context, getString(R.string.app_name))); MediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory) .createMediaSource(uri); player.prepare(mediaSource); player.setPlayWhenReady(true); playerNotificationManager = PlayerNotificationManager.createWithNotificationChannel(context, AppConstants.PLAYBACK_CHANNEL_ID, R.string.playback_channel_name, AppConstants.PLAYBACK_NOTIFICATION_ID, new PlayerNotificationManager.MediaDescriptionAdapter() { @Override public String getCurrentContentTitle(Player player) { return item.getTitle(); } @Nullable @Override public PendingIntent createCurrentContentIntent(Player player) { Intent intent = new Intent(context, PlayerActivity.class); Bundle serviceBundle = new Bundle(); serviceBundle.putParcelable(AppConstants.ITEM_KEY, item); intent.putExtra(AppConstants.BUNDLE_KEY, serviceBundle); return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } @Nullable @Override public String getCurrentContentText(Player player) { return item.getSummary(); } @Nullable @Override public Bitmap getCurrentLargeIcon(Player player, PlayerNotificationManager.BitmapCallback callback) { return item.getBitmap(); } } ); playerNotificationManager.setNotificationListener(new PlayerNotificationManager.NotificationListener() { @Override public void onNotificationStarted(int notificationId, Notification notification) { startForeground(notificationId, notification); } @Override public void onNotificationCancelled(int notificationId) { stopSelf(); } }); playerNotificationManager.setPlayer(player); } public class LocalBinder extends Binder { public AudioPlayerService getService() { return AudioPlayerService.this; } } } </code></pre> <p>This is my activity where I am starting the service and binding to it. I have to pass the Item object in-order the service to run, if I don't pass the data using the intent the service will crash so I can't do startService() in the service itself I have to start in the activity I guess.</p> <p><strong>PlayerActivity</strong></p> <pre><code>public class PlayerActivity extends BaseActivity { @BindView(R.id.video_view) PlayerView mPlayerView; @BindView(R.id.tvTitle) TextView mTvTitle; @BindView(R.id.tvSummary) TextView mTvSummary; @BindView(R.id.ivThumbnail) ImageView mIvThumb; private SimpleExoPlayer player; private String mURL, mTitle, mSummary, mImage; private AudioPlayerService mService; private boolean mBound = false; private Intent intent; private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { AudioPlayerService.LocalBinder binder = (AudioPlayerService.LocalBinder) iBinder; mService = binder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName componentName) { mBound = false; } }; @SuppressLint("MissingSuperCall") @Override protected void onCreate(Bundle savedInstanceState) { onCreate(savedInstanceState, R.layout.activity_player); Bundle b = getIntent().getBundleExtra(AppConstants.BUNDLE_KEY); if (b != null) { Item item = b.getParcelable(AppConstants.ITEM_KEY); mURL = item.getUrl(); mImage = item.getImage(); mTitle = item.getTitle(); mSummary = item.getSummary(); intent = new Intent(this, AudioPlayerService.class); Bundle serviceBundle = new Bundle(); serviceBundle.putParcelable(AppConstants.ITEM_KEY, item); intent.putExtra(AppConstants.BUNDLE_KEY, serviceBundle); Util.startForegroundService(this, intent); } } private void initializePlayer() { if (player == null &amp;&amp; !mURL.isEmpty() &amp;&amp; mBound) { player = mService.getplayerInstance(); mPlayerView.setPlayer(player); mPlayerView.setControllerHideOnTouch(false); mPlayerView.setControllerShowTimeoutMs(10800000); } } @Override public void onStart() { super.onStart(); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); initializePlayer(); setUI(); } private void setUI() { mTvTitle.setText(mTitle); mTvSummary.setText(mSummary); GlideApp.with(this) .load(mImage) .placeholder(R.color.colorPrimary) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(mIvThumb); } @Override protected void onStop() { unbindService(mConnection); mBound = false; releasePlayer(); super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.player_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.share_podcast: //Logic for Share return true; case R.id.download_podcast: //Logic for download return true; case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } private void releasePlayer() { if (player != null) { player.release(); player = null; } } @Override public void onToolBarSetUp(Toolbar toolbar, ActionBar actionBar) { TextView tvHeader = toolbar.findViewById(R.id.tvClassName); tvHeader.setText(R.string.app_name); actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp); } } </code></pre> <p>I have tried everything I know but I'm unable to move forward because of this.</p>
52,680,590
1
0
null
2018-09-24 06:48:54.837 UTC
8
2019-09-11 19:18:03.357 UTC
2018-10-05 11:13:30.88 UTC
null
9,419,047
null
9,419,047
null
1
11
android|service|exoplayer|exoplayer2.x|bindservice
5,957
<p>So after a lot of research I was able to resolve this using the bound service and getting the SimpleExoPlayer instance from the service and set the Player view to always show up using the following method.</p> <pre><code>mPlayerView.showController() </code></pre> <p>After all the modification and setup it takes only two classes to achieve background audio playback with notification control, one is the activity and the other is the service using the latest exoplayer release.</p> <p><strong>PlayerActivity</strong></p> <pre><code> public class PlayerActivity extends BaseActivity { @BindView(R.id.video_view) PlayerView mPlayerView; @BindView(R.id.tvTitle) TextView mTvTitle; @BindView(R.id.tvSummary) TextView mTvSummary; @BindView(R.id.ivThumbnail) ImageView mIvThumb; private String mUrl, mTitle, mSummary, mImage; private AudioPlayerService mService; private Intent intent; private String shareableLink; private boolean mBound = false; private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { AudioPlayerService.LocalBinder binder = (AudioPlayerService.LocalBinder) iBinder; mService = binder.getService(); mBound = true; initializePlayer(); } @Override public void onServiceDisconnected(ComponentName componentName) { mBound = false; } }; @SuppressLint("MissingSuperCall") @Override protected void onCreate(Bundle savedInstanceState) { onCreate(savedInstanceState, R.layout.activity_player); Bundle b = getIntent().getBundleExtra(AppConstants.BUNDLE_KEY); if (b != null) { Item item = b.getParcelable(AppConstants.ITEM_KEY); shareableLink = b.getString(AppConstants.SHARE_KEY); mImage = item.getImage(); mUrl = item.getUrl(); mTitle = item.getTitle(); mSummary = item.getSummary(); intent = new Intent(this, AudioPlayerService.class); Bundle serviceBundle = new Bundle(); serviceBundle.putParcelable(AppConstants.ITEM_KEY, item); intent.putExtra(AppConstants.BUNDLE_KEY, serviceBundle); Util.startForegroundService(this, intent); mPlayerView.setUseController(true); mPlayerView.showController(); mPlayerView.setControllerAutoShow(true); mPlayerView.setControllerHideOnTouch(false); } } private void initializePlayer() { if (mBound) { SimpleExoPlayer player = mService.getplayerInstance(); mPlayerView.setPlayer(player); } } @Override public void onStart() { super.onStart(); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); initializePlayer(); setUI(); } private void setUI() { mTvTitle.setText(mTitle); mTvSummary.setText(mSummary); GlideApp.with(this) .load(mImage) .placeholder(R.color.colorPrimary) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(mIvThumb); } @Override protected void onStop() { unbindService(mConnection); mBound = false; super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.player_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.share_podcast: Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_SUBJECT, mTitle); shareIntent.putExtra(Intent.EXTRA_TEXT, mTitle + "\n\n" + shareableLink); shareIntent.setType("text/plain"); startActivity(Intent.createChooser(shareIntent, getString(R.string.share_text))); return true; case R.id.download_podcast: Uri uri = Uri.parse(mUrl); ProgressiveDownloadAction progressiveDownloadAction = new ProgressiveDownloadAction(uri, false, null, null); AudioDownloadService.startWithAction(PlayerActivity.this, AudioDownloadService.class, progressiveDownloadAction, false); return true; case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onToolBarSetUp(Toolbar toolbar, ActionBar actionBar) { TextView tvHeader = toolbar.findViewById(R.id.tvClassName); tvHeader.setText(R.string.app_name); actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp); } } </code></pre> <p><strong>AudioPlayerService</strong></p> <pre><code> public class AudioPlayerService extends Service { private final IBinder mBinder = new LocalBinder(); private SimpleExoPlayer player; private Item item; private PlayerNotificationManager playerNotificationManager; @Override public void onCreate() { super.onCreate(); } @Override public void onDestroy() { releasePlayer(); super.onDestroy(); } private void releasePlayer() { if (player != null) { playerNotificationManager.setPlayer(null); player.release(); player = null; } } @Nullable @Override public IBinder onBind(Intent intent) { return mBinder; } public SimpleExoPlayer getplayerInstance() { if (player == null) { startPlayer(); } return player; } @Override public int onStartCommand(Intent intent, int flags, int startId) { //releasePlayer(); Bundle b = intent.getBundleExtra(AppConstants.BUNDLE_KEY); if (b != null) { item = b.getParcelable(AppConstants.ITEM_KEY); } if (player == null) { startPlayer(); } return START_STICKY; } private void startPlayer() { final Context context = this; Uri uri = Uri.parse(item.getUrl()); player = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector()); DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(context, Util.getUserAgent(context, getString(R.string.app_name))); CacheDataSourceFactory cacheDataSourceFactory = new CacheDataSourceFactory( DownloadUtil.getCache(context), dataSourceFactory, CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR); MediaSource mediaSource = new ExtractorMediaSource.Factory(cacheDataSourceFactory) .createMediaSource(uri); player.prepare(mediaSource); player.setPlayWhenReady(true); playerNotificationManager = PlayerNotificationManager.createWithNotificationChannel(context, AppConstants.PLAYBACK_CHANNEL_ID, R.string.playback_channel_name, AppConstants.PLAYBACK_NOTIFICATION_ID, new PlayerNotificationManager.MediaDescriptionAdapter() { @Override public String getCurrentContentTitle(Player player) { return item.getTitle(); } @Nullable @Override public PendingIntent createCurrentContentIntent(Player player) { Intent intent = new Intent(context, PlayerActivity.class); Bundle serviceBundle = new Bundle(); serviceBundle.putParcelable(AppConstants.ITEM_KEY, item); intent.putExtra(AppConstants.BUNDLE_KEY, serviceBundle); return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } @Nullable @Override public String getCurrentContentText(Player player) { return item.getSummary(); } @Nullable @Override public Bitmap getCurrentLargeIcon(Player player, PlayerNotificationManager.BitmapCallback callback) { return null; } } ); playerNotificationManager.setNotificationListener(new PlayerNotificationManager.NotificationListener() { @Override public void onNotificationStarted(int notificationId, Notification notification) { startForeground(notificationId, notification); } @Override public void onNotificationCancelled(int notificationId) { stopSelf(); } }); playerNotificationManager.setPlayer(player); } public class LocalBinder extends Binder { public AudioPlayerService getService() { return AudioPlayerService.this; } } } </code></pre>
52,795,561
flattening nested Json in pandas data frame
<p>I am trying to load the json file to pandas data frame. I found that there were some nested json. Below is the sample json:</p> <pre><code>{'events': [{'id': 142896214, 'playerId': 37831, 'teamId': 3157, 'matchId': 2214569, 'matchPeriod': '1H', 'eventSec': 0.8935539999999946, 'eventId': 8, 'eventName': 'Pass', 'subEventId': 85, 'subEventName': 'Simple pass', 'positions': [{'x': 51, 'y': 49}, {'x': 40, 'y': 53}], 'tags': [{'id': 1801, 'tag': {'label': 'accurate'}}]} </code></pre> <p>I used the following code to load json into dataframe:</p> <pre><code>with open('EVENTS.json') as f: jsonstr = json.load(f) df = pd.io.json.json_normalize(jsonstr['events']) </code></pre> <p>Below is the output of df.head()</p> <p><a href="https://i.stack.imgur.com/bYaiX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bYaiX.png" alt="output of df"></a></p> <p><a href="https://i.stack.imgur.com/bYaiX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bYaiX.png" alt="Here is the output"></a></p> <p>But I found two nested columns such as positions and tags.</p> <p>I tried using the following code to flatten it:</p> <pre><code>Position_data = json_normalize(data =jsonstr['events'], record_path='positions', meta = ['x','y','x','y'] ) </code></pre> <p>It showed me an error as follow:</p> <pre><code>KeyError: "Try running with errors='ignore' as key 'x' is not always present" </code></pre> <p>Can you advise me how to flatten positions and tags ( those having nested data).</p> <p>Thanks, Zep</p>
57,334,325
2
0
null
2018-10-13 17:33:23.893 UTC
10
2022-06-20 20:00:34.003 UTC
2021-03-03 23:13:30.273 UTC
null
7,758,804
null
9,561,497
null
1
18
python|json|pandas|flatten|json-normalize
38,244
<p>If you are looking for a more general way to unfold multiple hierarchies from a json you can use <code>recursion</code> and list comprehension to reshape your data. One alternative is presented below:</p> <pre class="lang-py prettyprint-override"><code>def flatten_json(nested_json, exclude=['']): """Flatten json object with nested keys into a single level. Args: nested_json: A nested json object. exclude: Keys to exclude from output. Returns: The flattened json object if successful, None otherwise. """ out = {} def flatten(x, name='', exclude=exclude): if type(x) is dict: for a in x: if a not in exclude: flatten(x[a], name + a + '_') elif type(x) is list: i = 0 for a in x: flatten(a, name + str(i) + '_') i += 1 else: out[name[:-1]] = x flatten(nested_json) return out </code></pre> <p>Then you can apply to your data, independent of nested levels:</p> <p><strong>New sample data</strong></p> <pre class="lang-py prettyprint-override"><code>this_dict = {'events': [ {'id': 142896214, 'playerId': 37831, 'teamId': 3157, 'matchId': 2214569, 'matchPeriod': '1H', 'eventSec': 0.8935539999999946, 'eventId': 8, 'eventName': 'Pass', 'subEventId': 85, 'subEventName': 'Simple pass', 'positions': [{'x': 51, 'y': 49}, {'x': 40, 'y': 53}], 'tags': [{'id': 1801, 'tag': {'label': 'accurate'}}]}, {'id': 142896214, 'playerId': 37831, 'teamId': 3157, 'matchId': 2214569, 'matchPeriod': '1H', 'eventSec': 0.8935539999999946, 'eventId': 8, 'eventName': 'Pass', 'subEventId': 85, 'subEventName': 'Simple pass', 'positions': [{'x': 51, 'y': 49}, {'x': 40, 'y': 53},{'x': 51, 'y': 49}], 'tags': [{'id': 1801, 'tag': {'label': 'accurate'}}]} ]} </code></pre> <p><strong>Usage</strong></p> <pre class="lang-py prettyprint-override"><code>pd.DataFrame([flatten_json(x) for x in this_dict['events']]) Out[1]: id playerId teamId matchId matchPeriod eventSec eventId \ 0 142896214 37831 3157 2214569 1H 0.893554 8 1 142896214 37831 3157 2214569 1H 0.893554 8 eventName subEventId subEventName positions_0_x positions_0_y \ 0 Pass 85 Simple pass 51 49 1 Pass 85 Simple pass 51 49 positions_1_x positions_1_y tags_0_id tags_0_tag_label positions_2_x \ 0 40 53 1801 accurate NaN 1 40 53 1801 accurate 51.0 positions_2_y 0 NaN 1 49.0 </code></pre> <p>Note that this <code>flatten_json</code> code is not mine, I have seen it <a href="https://towardsdatascience.com/flattening-json-objects-in-python-f5343c794b10" rel="noreferrer">here</a> and <a href="https://towardsdatascience.com/how-to-flatten-deeply-nested-json-objects-in-non-recursive-elegant-python-55f96533103d" rel="noreferrer">here</a> without much certainty of the original source.</p>
41,610,811
React.js, how to send a multipart/form-data to server
<p>We want to send an image file as multipart/form to the backend, we try to use html form to get file and send the file as formData, here are the codes</p> <pre><code>export default class Task extends React.Component { uploadAction() { var data = new FormData(); var imagedata = document.querySelector('input[type="file"]').files[0]; data.append("data", imagedata); fetch("http://localhost:8910/taskCreationController/createStoryTask", { mode: 'no-cors', method: "POST", headers: { "Content-Type": "multipart/form-data" "Accept": "application/json", "type": "formData" }, body: data }).then(function (res) { if (res.ok) { alert("Perfect! "); } else if (res.status == 401) { alert("Oops! "); } }, function (e) { alert("Error submitting form!"); }); } render() { return ( &lt;form encType="multipart/form-data" action=""&gt; &lt;input type="file" name="fileName" defaultValue="fileName"&gt;&lt;/input&gt; &lt;input type="button" value="upload" onClick={this.uploadAction.bind(this)}&gt;&lt;/input&gt; &lt;/form&gt; ) } } </code></pre> <p>The error in backend is <em>"nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found".</em></p> <p>After reading <a href="https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2" rel="noreferrer">this</a>, we tried to set boundary to headers in fetch:</p> <pre><code>fetch("http://localhost:8910/taskCreationController/createStoryTask", { mode: 'no-cors', method: "POST", headers: { "Content-Type": "multipart/form-data; boundary=AaB03x" + "--AaB03x" + "Content-Disposition: file" + "Content-Type: png" + "Content-Transfer-Encoding: binary" + "...data... " + "--AaB03x--", "Accept": "application/json", "type": "formData" }, body: data }).then(function (res) { if (res.ok) { alert("Perfect! "); } else if (res.status == 401) { alert("Oops! "); } }, function (e) { alert("Error submitting form!"); }); } </code></pre> <p>This time, the error in backend is: <em>Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause</em></p> <p>Do we add the multipart boundary right? Where should it be? Maybe we are wrong at first because we don't get the multipart/form-data. How can we get it correctly?</p>
41,634,303
7
0
null
2017-01-12 10:30:35.503 UTC
14
2022-05-20 04:34:41.877 UTC
null
null
null
null
5,173,154
null
1
41
reactjs|file-upload|multipartform-data
164,621
<p>We just try to remove our headers and it works!</p> <pre><code>fetch("http://localhost:8910/taskCreationController/createStoryTask", { mode: 'no-cors', method: "POST", body: data }).then(function (res) { if (res.ok) { alert("Perfect! "); } else if (res.status == 401) { alert("Oops! "); } }, function (e) { alert("Error submitting form!"); }); </code></pre>
47,360,510
Pandas groupby and aggregation output should include all the original columns (including the ones not aggregated on)
<p>I have the following data frame and want to:</p> <ul> <li>Group records by <code>month</code></li> <li>Sum <code>QTY_SOLD</code>and <code>NET_AMT</code> of each unique <code>UPC_ID</code>(per month)</li> <li>Include the rest of the columns as well in the resulting dataframe</li> </ul> <p>The way I thought I can do this is 1st: create a <code>month</code> column to aggregate the <code>D_DATES</code>, then sum <code>QTY_SOLD</code> by <code>UPC_ID</code>. </p> <p>Script:</p> <pre><code># Convert date to date time object df['D_DATE'] = pd.to_datetime(df['D_DATE']) # Create aggregated months column df['month'] = df['D_DATE'].apply(dt.date.strftime, args=('%Y.%m',)) # Group by month and sum up quantity sold by UPC_ID df = df.groupby(['month', 'UPC_ID'])['QTY_SOLD'].sum() </code></pre> <hr> <p>Current data frame:</p> <pre><code>UPC_ID | UPC_DSC | D_DATE | QTY_SOLD | NET_AMT ---------------------------------------------- 111 desc1 2/26/2017 2 10 (2 x $5) 222 desc2 2/26/2017 3 15 333 desc3 2/26/2017 1 4 111 desc1 3/1/2017 1 5 111 desc1 3/3/2017 4 20 </code></pre> <p>Desired Output:</p> <pre><code>MONTH | UPC_ID | QTY_SOLD | NET_AMT | UPC_DSC ---------------------------------------------- 2017-2 111 2 10 etc... 2017-2 222 3 15 2017-2 333 1 4 2017-3 111 5 25 </code></pre> <p>Actual Output:</p> <pre><code>MONTH | UPC_ID ---------------------------------------------- 2017-2 111 2 222 3 333 1 2017-3 111 5 ... </code></pre> <p>Questions:</p> <ul> <li>How do I include the month for each row?</li> <li>How do I include the rest of the columns of the dataframe?</li> <li>How do also sum <code>NET_AMT</code> in addition to <code>QTY_SOLD</code>? </li> </ul>
47,360,565
2
0
null
2017-11-17 22:59:48.82 UTC
7
2018-12-30 15:29:12.29 UTC
2018-12-18 15:06:19.433 UTC
null
4,909,087
null
507,624
null
1
30
python|pandas|dataframe|group-by|pandas-groupby
51,501
<h3><code>agg</code> with a <code>dict</code> of functions</h3> <p>Create a <code>dict</code> of functions and pass it to <code>agg</code>. You'll also need <code>as_index=False</code> to prevent the group columns from becoming the index in your output.</p> <pre><code>f = {'NET_AMT': 'sum', 'QTY_SOLD': 'sum', 'UPC_DSC': 'first'} df.groupby(['month', 'UPC_ID'], as_index=False).agg(f) month UPC_ID UPC_DSC NET_AMT QTY_SOLD 0 2017.02 111 desc1 10 2 1 2017.02 222 desc2 15 3 2 2017.02 333 desc3 4 1 3 2017.03 111 desc1 25 5 </code></pre> <hr /> <h3>Blanket <code>sum</code></h3> <p>Just call <code>sum</code> without any column names. This handles the numeric columns. For <code>UPC_DSC</code>, you'll need to handle it separately.</p> <pre><code>g = df.groupby(['month', 'UPC_ID']) i = g.sum() j = g[['UPC_DSC']].first() pd.concat([i, j], 1).reset_index() month UPC_ID QTY_SOLD NET_AMT UPC_DSC 0 2017.02 111 2 10 desc1 1 2017.02 222 3 15 desc2 2 2017.02 333 1 4 desc3 3 2017.03 111 5 25 desc1 </code></pre>
18,761,001
DDD - How to design associations between different bounded contexts
<p>I have setup a domain project which is being populated with an ORM. The domain contains of different aggregates each with its own root object. My question is how properties that cross the aggregate boundries should be treated?</p> <ul> <li>Should these properties simply ignore the boundries so that a domain object in bounded context A has a reference to an object in context B?</li> <li>Or, should there be no direct link from context A to B and does the object in context A have an "int ContextBId" property that can be used to get the domain object from B through the B aggregate root?</li> <li>Or ...</li> </ul> <p><strong>An example:</strong><br> Context A = Users<br> Context B = Games</p> <p>Inside the <code>Users</code> context there is an object <code>UserOwnedGames</code>. This object has a property <code>User</code> which is a reference to an object in the same <code>Users</code> context. The object also has a property to a <code>Game</code> which is obviously not in the Users but rather in the <code>Games</code> context.</p> <p>How would (or should?) this relation look like? It's clear in the database (ie 2 foreign keys) but what should the code look like?</p>
18,766,274
4
0
null
2013-09-12 09:52:18.677 UTC
9
2021-11-13 03:09:05.08 UTC
null
null
null
null
540,352
null
1
10
domain-driven-design|aggregateroot|bounded-contexts
5,209
<p>It sounds like your <code>User</code> context also needs a <code>Game</code> entity. Note however that this is not necessarily the same <code>Game</code> entity which is the root of the <code>Game</code> context. These two bounded contexts may have different ideas of what a <code>Game</code> is, and what properties it has. Only the identity ties the two Game objects together.</p> <pre><code>User Context { Aggregate Root User { Identity; Name; OwnedGames : List of Game value entities } Value Entity Game { Identity; Name; } } Game Context { Aggregate Root Game { Identity; Name; Owner : User value entity HighScore : int TimesPlayed : int ... A whole bunch of other properties which are not relevant in the User context } Value Entity User { Identity; Name; // No OwnedGames property, in this context we don't care about what other games the user owns. } } </code></pre>
42,764,494
blur event.relatedTarget returns null
<p>I have an <code>&lt;input type="text"&gt;</code> field and I need to clear it when this field loses focus (whiech means that user clicked somewhere on the page). But there is one exception. Input text field should't be cleared when user clicks on a specific element.</p> <p>I tried to use <code>event.relatedTarget</code> to detect if user clicked not just somewhere but on my specific <code>&lt;div&gt;</code>.</p> <p>However as you can see in snippet below, it simply doesn't work. <code>event.relatedTarget</code> is always returning <code>null</code>!</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function lose_focus(event) { if(event.relatedTarget === null) { document.getElementById('text-field').value = ''; } }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.special { width: 200px; height: 100px; background: #ccc; border: 1px solid #000; margin: 25px 0; padding: 15px; } .special:hover { cursor: pointer; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input id="text-field" type="text" onblur="lose_focus(event)" placeholder="Type something..."&gt; &lt;div class="special"&gt;Clicking here should not cause clearing!&lt;/div&gt;</code></pre> </div> </div> </p>
42,764,495
1
0
null
2017-03-13 13:09:44.453 UTC
16
2017-09-01 12:28:32.837 UTC
2017-03-13 13:55:55.96 UTC
null
3,050,341
null
3,050,341
null
1
74
javascript|events|onblur|lost-focus|focusout
25,496
<p><strong>Short answer:</strong> add <code>tabindex="0"</code> attribute to an element that should appear in <code>event.relatedTarget</code>.</p> <p><strong>Explanation:</strong> <code>event.relatedTarget</code> contains an element that <em>gained</em> focus. And the problem is that your <em>specific</em> div can't gain a focus because browser thinks that this element is not a button/field or some kind of a control element.</p> <p>Here are the elements that can gain focus by default:</p> <blockquote> <ul> <li><code>&lt;a&gt;</code> elements with <code>href</code> attribute specified</li> <li><code>&lt;link&gt;</code> elements with <code>href</code> attribute specified</li> <li><code>&lt;button&gt;</code> elements</li> <li><code>&lt;input&gt;</code> elements that are not <code>hidden</code></li> <li><code>&lt;select&gt;</code> elements</li> <li><code>&lt;textarea&gt;</code> elements</li> <li><code>&lt;menuitem&gt;</code> elements</li> <li>elements with attribue <code>draggable</code></li> <li><code>&lt;audio&gt;</code> and <code>&lt;video&gt;</code> elements with <code>controls</code> attribute specified</li> </ul> </blockquote> <p>So <code>event.relatedTarget</code> will contain above elements when <code>onblur</code> happens. <strong>All</strong> other elements will are not counted and clicking on them will put <code>null</code> in <code>event.relatedTarget</code>.</p> <p>But it is possible to change this behaviour. You can 'mark' DOM element as element that can gain focus with <em><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex" rel="noreferrer">tabindex</a></em> attribute. Here is what standart says:</p> <blockquote> <p>The <code>tabindex</code> content attribute allows authors to indicate that an element is supposed to be focusable, whether it is supposed to be reachable using sequential focus navigation and, optionally, to suggest where in the sequential focus navigation order the element appears.</p> </blockquote> <p>So here is the corrected code snippet:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function lose_focus(event) { if(event.relatedTarget === null) { document.getElementById('text-field').value = ''; } }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.special { width: 200px; height: 100px; background: #ccc; border: 1px solid #000; margin: 25px 0; padding: 15px; } .special:hover { cursor: pointer; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input id="text-field" type="text" onblur="lose_focus(event)" placeholder="Type something..."&gt; &lt;div tabindex="0" class="special"&gt;Clicking here should not cause clearing!&lt;/div&gt;</code></pre> </div> </div> </p>
40,038,041
java.lang.NoClassDefFoundError: org/openxmlformats/schemas/spreadsheetml/x2006/main/CTWorkbook$Factory
<p>I use example: <a href="http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/ss/examples/BusinessPlan.java" rel="noreferrer">http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/ss/examples/BusinessPlan.java</a></p> <p>This is my dependencies list:</p> <pre><code>&lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.12&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.poi&lt;/groupId&gt; &lt;artifactId&gt;poi&lt;/artifactId&gt; &lt;version&gt;3.15&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.poi&lt;/groupId&gt; &lt;artifactId&gt;poi-ooxml&lt;/artifactId&gt; &lt;version&gt;3.15&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.poi&lt;/groupId&gt; &lt;artifactId&gt;poi-ooxml-schemas&lt;/artifactId&gt; &lt;version&gt;3.15&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.github.jsqlparser&lt;/groupId&gt; &lt;artifactId&gt;jsqlparser&lt;/artifactId&gt; &lt;version&gt;0.9.6&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;repositories&gt; &lt;repository&gt; &lt;id&gt;jsqlparser-snapshots&lt;/id&gt; &lt;snapshots&gt; &lt;enabled&gt;true&lt;/enabled&gt; &lt;/snapshots&gt; &lt;url&gt;https://oss.sonatype.org/content/groups/public/&lt;/url&gt; &lt;/repository&gt; &lt;/repositories&gt; </code></pre> <p>and program:</p> <pre><code>/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.ss.examples; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.PrintSetup; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * A business plan demo Usage: BusinessPlan -xls|xlsx * * @author Yegor Kozlov */ public class BusinessPlan { private static SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM"); private static final String[] titles = { "ID", "Project Name", "Owner", "Days", "Start", "End" }; // sample data to fill the sheet. private static final String[][] data = { { "1.0", "Marketing Research Tactical Plan", "J. Dow", "70", "9-Jul", null, "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x" }, null, { "1.1", "Scope Definition Phase", "J. Dow", "10", "9-Jul", null, "x", "x", null, null, null, null, null, null, null, null, null }, { "1.1.1", "Define research objectives", "J. Dow", "3", "9-Jul", null, "x", null, null, null, null, null, null, null, null, null, null }, { "1.1.2", "Define research requirements", "S. Jones", "7", "10-Jul", null, "x", "x", null, null, null, null, null, null, null, null, null }, { "1.1.3", "Determine in-house resource or hire vendor", "J. Dow", "2", "15-Jul", null, "x", "x", null, null, null, null, null, null, null, null, null }, null, { "1.2", "Vendor Selection Phase", "J. Dow", "19", "19-Jul", null, null, "x", "x", "x", "x", null, null, null, null, null, null }, { "1.2.1", "Define vendor selection criteria", "J. Dow", "3", "19-Jul", null, null, "x", null, null, null, null, null, null, null, null, null }, { "1.2.2", "Develop vendor selection questionnaire", "S. Jones, T. Wates", "2", "22-Jul", null, null, "x", "x", null, null, null, null, null, null, null, null }, { "1.2.3", "Develop Statement of Work", "S. Jones", "4", "26-Jul", null, null, null, "x", "x", null, null, null, null, null, null, null }, { "1.2.4", "Evaluate proposal", "J. Dow, S. Jones", "4", "2-Aug", null, null, null, null, "x", "x", null, null, null, null, null, null }, { "1.2.5", "Select vendor", "J. Dow", "1", "6-Aug", null, null, null, null, null, "x", null, null, null, null, null, null }, null, { "1.3", "Research Phase", "G. Lee", "47", "9-Aug", null, null, null, null, null, "x", "x", "x", "x", "x", "x", "x" }, { "1.3.1", "Develop market research information needs questionnaire", "G. Lee", "2", "9-Aug", null, null, null, null, null, "x", null, null, null, null, null, null }, { "1.3.2", "Interview marketing group for market research needs", "G. Lee", "2", "11-Aug", null, null, null, null, null, "x", "x", null, null, null, null, null }, { "1.3.3", "Document information needs", "G. Lee, S. Jones", "1", "13-Aug", null, null, null, null, null, null, "x", null, null, null, null, null }, }; public static void main(String[] args) throws Exception { Workbook wb; if (args.length &gt; 0 &amp;&amp; args[0].equals("-xls")) wb = new HSSFWorkbook(); else wb = new XSSFWorkbook(); Map&lt;String, CellStyle&gt; styles = createStyles(wb); Sheet sheet = wb.createSheet("Business Plan"); // turn off gridlines sheet.setDisplayGridlines(false); sheet.setPrintGridlines(false); sheet.setFitToPage(true); sheet.setHorizontallyCenter(true); PrintSetup printSetup = sheet.getPrintSetup(); printSetup.setLandscape(true); // the following three statements are required only for HSSF sheet.setAutobreaks(true); printSetup.setFitHeight((short) 1); printSetup.setFitWidth((short) 1); // the header row: centered text in 48pt font Row headerRow = sheet.createRow(0); headerRow.setHeightInPoints(12.75f); for (int i = 0; i &lt; titles.length; i++) { Cell cell = headerRow.createCell(i); cell.setCellValue(titles[i]); cell.setCellStyle(styles.get("header")); } // columns for 11 weeks starting from 9-Jul Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); calendar.setTime(fmt.parse("9-Jul")); calendar.set(Calendar.YEAR, year); for (int i = 0; i &lt; 11; i++) { Cell cell = headerRow.createCell(titles.length + i); cell.setCellValue(calendar); cell.setCellStyle(styles.get("header_date")); calendar.roll(Calendar.WEEK_OF_YEAR, true); } // freeze the first row sheet.createFreezePane(0, 1); Row row; Cell cell; int rownum = 1; for (int i = 0; i &lt; data.length; i++, rownum++) { row = sheet.createRow(rownum); if (data[i] == null) continue; for (int j = 0; j &lt; data[i].length; j++) { cell = row.createCell(j); String styleName; boolean isHeader = i == 0 || data[i - 1] == null; switch (j) { case 0: if (isHeader) { styleName = "cell_b"; cell.setCellValue(Double.parseDouble(data[i][j])); } else { styleName = "cell_normal"; cell.setCellValue(data[i][j]); } break; case 1: if (isHeader) { styleName = i == 0 ? "cell_h" : "cell_bb"; } else { styleName = "cell_indented"; } cell.setCellValue(data[i][j]); break; case 2: styleName = isHeader ? "cell_b" : "cell_normal"; cell.setCellValue(data[i][j]); break; case 3: styleName = isHeader ? "cell_b_centered" : "cell_normal_centered"; cell.setCellValue(Integer.parseInt(data[i][j])); break; case 4: { calendar.setTime(fmt.parse(data[i][j])); calendar.set(Calendar.YEAR, year); cell.setCellValue(calendar); styleName = isHeader ? "cell_b_date" : "cell_normal_date"; break; } case 5: { int r = rownum + 1; String fmla = "IF(AND(D" + r + ",E" + r + "),E" + r + "+D" + r + ",\"\")"; cell.setCellFormula(fmla); styleName = isHeader ? "cell_bg" : "cell_g"; break; } default: styleName = data[i][j] != null ? "cell_blue" : "cell_normal"; } cell.setCellStyle(styles.get(styleName)); } } // group rows for each phase, row numbers are 0-based sheet.groupRow(4, 6); sheet.groupRow(9, 13); sheet.groupRow(16, 18); // set column widths, the width is measured in units of 1/256th of a // character width sheet.setColumnWidth(0, 256 * 6); sheet.setColumnWidth(1, 256 * 33); sheet.setColumnWidth(2, 256 * 20); sheet.setZoom(75); // 75% scale // Write the output to a file String file = "businessplan.xls"; if (wb instanceof XSSFWorkbook) file += "x"; FileOutputStream out = new FileOutputStream(file); wb.write(out); out.close(); wb.close(); } /** * create a library of cell styles */ private static Map&lt;String, CellStyle&gt; createStyles(Workbook wb) { Map&lt;String, CellStyle&gt; styles = new HashMap&lt;String, CellStyle&gt;(); DataFormat df = wb.createDataFormat(); CellStyle style; Font headerFont = wb.createFont(); headerFont.setBold(true); style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.CENTER); style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); style.setFont(headerFont); styles.put("header", style); style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.CENTER); style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); style.setFont(headerFont); style.setDataFormat(df.getFormat("d-mmm")); styles.put("header_date", style); Font font1 = wb.createFont(); font1.setBold(true); style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.LEFT); style.setFont(font1); styles.put("cell_b", style); style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.CENTER); style.setFont(font1); styles.put("cell_b_centered", style); style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.RIGHT); style.setFont(font1); style.setDataFormat(df.getFormat("d-mmm")); styles.put("cell_b_date", style); style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.RIGHT); style.setFont(font1); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); style.setDataFormat(df.getFormat("d-mmm")); styles.put("cell_g", style); Font font2 = wb.createFont(); font2.setColor(IndexedColors.BLUE.getIndex()); font2.setBold(true); style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.LEFT); style.setFont(font2); styles.put("cell_bb", style); style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.RIGHT); style.setFont(font1); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); style.setDataFormat(df.getFormat("d-mmm")); styles.put("cell_bg", style); Font font3 = wb.createFont(); font3.setFontHeightInPoints((short) 14); font3.setColor(IndexedColors.DARK_BLUE.getIndex()); font3.setBold(true); style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.LEFT); style.setFont(font3); style.setWrapText(true); styles.put("cell_h", style); style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.LEFT); style.setWrapText(true); styles.put("cell_normal", style); style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.CENTER); style.setWrapText(true); styles.put("cell_normal_centered", style); style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.RIGHT); style.setWrapText(true); style.setDataFormat(df.getFormat("d-mmm")); styles.put("cell_normal_date", style); style = createBorderedStyle(wb); style.setAlignment(HorizontalAlignment.LEFT); style.setIndention((short) 1); style.setWrapText(true); styles.put("cell_indented", style); style = createBorderedStyle(wb); style.setFillForegroundColor(IndexedColors.BLUE.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); styles.put("cell_blue", style); return styles; } private static CellStyle createBorderedStyle(Workbook wb) { BorderStyle thin = BorderStyle.THIN; short black = IndexedColors.BLACK.getIndex(); CellStyle style = wb.createCellStyle(); style.setBorderRight(thin); style.setRightBorderColor(black); style.setBorderBottom(thin); style.setBottomBorderColor(black); style.setBorderLeft(thin); style.setLeftBorderColor(black); style.setBorderTop(thin); style.setTopBorderColor(black); return style; } } </code></pre> <p>But have exception:</p> <pre><code>Exception in thread "main" java.lang.NoClassDefFoundError: org/openxmlformats/schemas/spreadsheetml/x2006/main/CTWorkbook$Factory at org.apache.poi.xssf.usermodel.XSSFWorkbook.onWorkbookCreate(XSSFWorkbook.java:436) at org.apache.poi.xssf.usermodel.XSSFWorkbook.&lt;init&gt;(XSSFWorkbook.java:238) at org.apache.poi.xssf.usermodel.XSSFWorkbook.&lt;init&gt;(XSSFWorkbook.java:229) at org.apache.poi.ss.examples.BusinessPlan.main(BusinessPlan.java:94) Caused by: java.lang.ClassNotFoundException: org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook$Factory at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 4 more </code></pre> <p>How to avoid the above exception?</p>
40,038,198
3
1
null
2016-10-14 08:03:56.097 UTC
4
2019-04-24 12:17:33.03 UTC
null
null
null
null
3,728,901
null
1
9
java|apache-poi
58,189
<p>Add this dependency:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.apache.poi&lt;/groupId&gt; &lt;artifactId&gt;ooxml-schemas&lt;/artifactId&gt; &lt;version&gt;1.3&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>(Because Eclipse IDE don't point specific line missing dependency make hard to detect problem).</p> <p>Reference: <a href="http://poi.apache.org/faq.html#faq-N10025" rel="noreferrer">http://poi.apache.org/faq.html#faq-N10025</a></p>
22,215,671
Convert Existing PHP/MYSQL/ website to Native IOS/Android Apps
<p>Weeks of searching and worked on a few guides to convert my existing hosted PHP/MYSQL website to Native IOS/Android Apps. So far no good result. Tried Phonegap and Cordova too. Searches from the past years back to 2009 stated it is not possible. Is it possible now? Can share a complete guide or e-book for it? The app will be just a direct link to my php website. The app is actually acting like a browser. This is my very first app.</p> <p><a href="http://tech.sarathdr.com/featured/steps-to-convert-a-web-app-into-android-phonegap-app/" rel="noreferrer">http://tech.sarathdr.com/featured/steps-to-convert-a-web-app-into-android-phonegap-app/</a></p> <p><a href="http://antonylees.blogspot.sg/2013/02/launch-website-as-mobile-app-using.html" rel="noreferrer">http://antonylees.blogspot.sg/2013/02/launch-website-as-mobile-app-using.html</a></p>
22,216,016
1
1
null
2014-03-06 05:20:57.98 UTC
7
2018-11-27 06:48:44.643 UTC
null
null
null
null
1,849,797
null
1
8
php|android|mysql|ios|native
45,156
<p>May be you should look at <code>webview</code>.. its a widget which <strong>wraps your webapp to android webview</strong>, basically It means your <strong>webapp will open in a browser</strong> but it will give <strong>look and feel like an mobile app</strong> .</p> <p>here are some tutorials and information about <code>webview</code> from <code>android-sdk</code> and <code>xda-developers</code></p> <blockquote> <p><a href="http://developer.android.com/reference/android/webkit/WebView.html" rel="nofollow noreferrer">http://developer.android.com/reference/android/webkit/WebView.html</a></p> <p><a href="http://forum.xda-developers.com/showthread.php?t=2308089" rel="nofollow noreferrer">http://forum.xda-developers.com/showthread.php?t=2308089</a></p> <p><a href="http://developer.android.com/guide/webapps/webview.html" rel="nofollow noreferrer">http://developer.android.com/guide/webapps/webview.html</a></p> </blockquote> <p>And Also check this answer too,</p> <blockquote> <p><a href="https://stackoverflow.com/questions/6634933/is-phone-gap-capable-of-converting-a-php-web-app-into-an-iphone-android-app">is Phone Gap capable of converting a php web app into an iphone/android app?</a>.. You can later on, add some features to the application by adding geolocation features for example. Here is an example using Apache Cordova <a href="https://auth0.com/blog/converting-your-web-app-to-mobile/" rel="nofollow noreferrer">https://auth0.com/blog/converting-your-web-app-to-mobile/</a></p> </blockquote> <p>let me know if you want any further guidance......</p>
23,806,471
Why is my embedded h2 program writing to a .mv.db file
<p>I followed the quickstart guide on the h2 database website to create a new database a table and insert some data. The application runs smooth and can read and write to the database without problems.</p> <blockquote> <h1>Quickstart h2</h1> <ul> <li>Add the h2*.jar to the classpath (H2 does not have any dependencies)</li> <li>Use the JDBC driver class: org.h2.Driver</li> <li>The database URL jdbc:h2:~/test opens the database test in your user home directory</li> <li>A new database is automatically created<br></li> </ul> </blockquote> <p>Now i want to look at the data with the web-frontend h2 console but everytime I try to open my database it just creates a new database.<br><br> After a long search I noticed that my Java-App, which uses the h2 embedded version writes to a file called &quot;.mv.db&quot; while the web-frontend creates the file &quot;.h2.db&quot; (which makes much more sense for me)<br><br> Also when my App writes to the database it uses extreme amounts of space (80MB for ~600 integer values)<br> How can I use the &quot;.h2.db&quot; extension for my embedded database?</p>
23,814,379
2
1
null
2014-05-22 12:11:35.487 UTC
3
2016-05-30 14:23:56.88 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
3,664,908
null
1
40
java|database|jdbc|h2
36,208
<p>This is now automatically enabled since version 1.4.177 Beta (2014-04-12).</p> <p>You can disable it by adding <code>;MV_STORE=FALSE</code> and <code>;MVCC=FALSE</code> to the database URL</p> <blockquote> <p>By default, the MV_STORE option is enabled, so it is using the new MVStore storage. The MVCC setting is by default set to the same values as the MV_STORE setting, so it is also enabled by default. For testing, both settings can be disabled by appending ";MV_STORE=FALSE" and/or ";MVCC=FALSE" to the database URL.</p> <p><a href="http://www.h2database.com/html/changelog.html" rel="noreferrer">http://www.h2database.com/html/changelog.html</a></p> </blockquote> <p>You should tell us, what exact version of H2 you use.</p>
52,980,345
router.navigate with query params Angular 5
<p>I'm having an issue with routing to a route with query params I have a function like so</p> <pre><code>goToLink(link) { this.router.navigate([`${link.split('?')[0]}`, { queryParams: this.sortParams(link)}]); } </code></pre> <p>and this function</p> <pre><code>sortParams(link) { let queryParams = url.split('?')[1]; let params = queryParams.split('&amp;'); let pair = null; let data = {}; params.forEach((d) =&gt; { pair = d.split('='); data[`${pair[0]}`] = pair[1]; }); return data; } </code></pre> <p>okay so basically what Is happening I have a function called <code>goToLink()</code> and that takes in a url and the url that gets passed is a string with query params like so..</p> <p><code>https://website.com/page?id=37&amp;username=jimmy</code></p> <p>the above is just an example thats not what it actually looks like but its a link string with query parameters now so what happens is I remove the params from the string and store them in a data object in the <code>sortParams()</code> function so when I pass the above string in I get an object that looks like this</p> <p><code>{id: 37, username: 'jimmy'}</code></p> <p>now thats what i'm passing into the <code>queryParams:</code> section in the router.navigate, </p> <p>the function should look like this when the object is returned</p> <pre><code>this.router.navigate([`${link.split('?')[0]}`, { queryParams: {id: 37, username: 'jimmy'}}]); </code></pre> <p>so i successfully route to the desired route but the query params look like this.. </p> <p><code>/page;queryParams=%5Bobject%20Object%5D</code></p> <p>Am I doing something wrong here??</p> <p>Any help would be appreciated!</p> <p><strong>EDIT</strong></p> <p>If I just change the function to this</p> <pre><code> this.router.navigate([`${link.split('?')[0]}`, { queryParams: {id: 37, username: 'jimmy'}}]); </code></pre> <p>I get the same url <code>/page;queryParams=%5Bobject%20Object%5D</code></p>
52,980,453
4
1
null
2018-10-25 02:12:07.303 UTC
7
2021-05-27 23:46:41.363 UTC
2018-10-25 02:24:04.217 UTC
null
8,724,160
null
8,724,160
null
1
75
javascript|angular|typescript|angular-router
104,598
<p>Can be of that you had placed the bracket which is supposedly for the 1st param but you had encapsulated it on the whole line of route</p> <p><strong>Your code:</strong></p> <pre><code>// This is the end of your route statement: '}}]);' which the close bracket is included this.router.navigate([`${link.split('?')[0]}`, { queryParams: {id: 37, username: 'jimmy'}}]); </code></pre> <p><strong>Update route:</strong></p> <p>place the <strong>]</strong> close bracket within the 1st parameter only, try to not place it on the last part of the route statement.</p> <pre><code>// Update end line: '}});' this.router.navigate([`${link.split('?')[0]}`], { queryParams: {id: 37, username: 'jimmy'}}); </code></pre> <hr /> <p><strong>Summary:</strong></p> <pre><code>this.router.navigate([ url ], { queryParams: { ... } }) </code></pre>
37,564,906
What are all the index.ts used for?
<p>I've been looking at a few seed projects and all the components seem to have a index.ts that exports * from that component. I can't find anywhere what it's actually used for?</p> <p>E.g <a href="https://github.com/mgechev/angular2-seed/tree/master/src/client/app/%2Bhome" rel="noreferrer">https://github.com/mgechev/angular2-seed/tree/master/src/client/app/%2Bhome</a></p> <p>Thanks</p>
37,564,980
3
1
null
2016-06-01 09:38:38.653 UTC
39
2020-04-20 17:48:38.653 UTC
null
null
null
null
4,420,821
null
1
176
angular
136,873
<p>From the <a href="https://v2.angular.io/docs/ts/latest/guide/glossary.html" rel="noreferrer">Angular.io v2's archived glossary</a> entry for <code>Barrel</code><sup>*</sup>:</p> <blockquote> <p>A barrel is a way to rollup exports from several modules into a single convenience module. The barrel itself is a module file that re-exports selected exports of other modules.</p> <p>Imagine three modules in a heroes folder:</p> <pre><code>// heroes/hero.component.ts export class HeroComponent {} // heroes/hero.model.ts export class Hero {} // heroes/hero.service.ts export class HeroService {} </code></pre> <p>Without a barrel, a consumer would need three import statements:</p> <pre><code>import { HeroComponent } from '../heroes/hero.component.ts'; import { Hero } from '../heroes/hero.model.ts'; import { HeroService } from '../heroes/hero.service.ts'; </code></pre> <p>We can add a barrel to the heroes folder (called index by convention) that exports all of these items:</p> <pre><code>export * from './hero.model.ts'; // re-export all of its exports export * from './hero.service.ts'; // re-export all of its exports export { HeroComponent } from './hero.component.ts'; // re-export the named thing </code></pre> <p>Now a consumer can import what it needs from the barrel.</p> <pre><code>import { Hero, HeroService } from '../heroes'; // index is implied </code></pre> <p>The Angular scoped packages each have a barrel named index.</p> </blockquote> <p>See also <a href="https://stackoverflow.com/questions/37997824/angular-2-di-error-exception-cant-resolve-all-parameters/38000323#38000323">EXCEPTION: Can&#39;t resolve all parameters</a></p> <hr> <p><sup>*</sup> <strong>NOTE:</strong> <code>Barrel</code> has been removed from <a href="https://angular.io/guide/glossary" rel="noreferrer">more recent versions of the Angular glossary</a>.</p> <p><strong>UPDATE</strong> With latest versions of Angular, barrel file should be edited as below,</p> <blockquote> <pre><code>export { HeroModel } from './hero.model'; export { HeroService } from './hero.service'; export { HeroComponent } from './hero.component'; </code></pre> </blockquote>
34,479,040
How to install wkhtmltopdf with patched qt?
<p>I want to convert html to pdf, and I use wkhtmltopdf.</p> <p>But print size is smaller than I supposed. I want to try <code>--disable-smart-shrinking</code> option but error occured like</p> <pre><code>$ xvfb-run -- /usr/bin/wkhtmltopdf --disable-smart-shrinking $INPUT $OUTPUT The switch --disable-smart-shrinking, is not support using unpatched qt, and will be ignored.Loading page (1/2) Printing pages (2/2) Done </code></pre> <p>Maybe I have to install wkhtmltopdf with patched qt, but I don't know how to install.</p> <p>I saw following size, but gitorious.org doesn't work.</p> <p><a href="https://stackoverflow.com/questions/10981960/wkhtmltopdf-patched-qt">wkhtmltopdf patched qt?</a></p> <p>My OS is Ubuntu14.04, and wkhtmltopdf version is 0.12.2.1</p> <p>If you know other reason to be printed smaller, tell me please. thanks.</p>
34,521,838
4
3
null
2015-12-27 09:08:37.647 UTC
11
2020-10-22 13:31:55.087 UTC
2017-05-23 12:09:56.23 UTC
null
-1
null
4,333,230
null
1
45
qt|wkhtmltopdf
63,067
<p>You can install <code>wkhtmltopdf</code> with <code>--disable-smart-shrinking</code> option from <a href="http://wkhtmltopdf.org/downloads.html" rel="noreferrer">wkhtmltopdf</a>.</p> <p>Download and Install it.</p> <p><a href="http://wkhtmltopdf.org/usage/wkhtmltopdf.txt" rel="noreferrer">http://wkhtmltopdf.org/usage/wkhtmltopdf.txt</a></p> <p>The Document say</p> <blockquote> <p>wkhtmltopdf 0.12.2.1 (with patched qt)</p> </blockquote> <p>and</p> <blockquote> <p>--disable-smart-shrinking Disable the intelligent shrinking strategy used by WebKit that makes the pixel/dpi ratio none constant</p> </blockquote>
34,428,041
Error in printing data.frame in excel using XLSX package in R
<p>The dataframe is visible with out any error. But when the same is printed using write.xlsx fucnction of the package XLSX, it gives the error.</p> <pre><code>Error in .jcall(cell, "V", "setCellValue", value) : method setCellValue with signature ([D)V not found. </code></pre> <p>The dput of the data.frame looks like:</p> <pre><code>Timestamp qs pqs logqs es p_imp dep r_dep agg_rtn (time) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) 1 2015-05-04 09:29:59 0.05788732 0.0007478696 0.0007478545 0.09633803 -0.0446830986 3533.518 274079.9 -0.0006432937 2 2015-05-04 10:00:00 0.04948394 0.0006362707 0.0006362707 0.07586009 0.0088016055 2416.431 187953.1 0.0000000000 3 2015-05-04 10:30:00 0.05554795 0.0007142532 0.0007142532 0.06417808 -0.0002739726 3245.574 252422.0 0.0000000000 4 2015-05-04 10:59:59 0.04863014 0.0006194244 0.0006194244 0.08434442 0.0024951076 3563.401 279503.9 0.0000000000 5 2015-05-04 11:30:00 0.05761986 0.0007319037 0.0007319037 0.07851027 0.0154965753 2010.943 158429.1 -0.0006339144 6 2015-05-04 12:00:00 0.04957627 0.0006285051 0.0006285051 0.07025424 0.0070762712 1819.908 143546.0 0.0000000000 Variables not shown: vol_30_sum (dbl), vol_30_mean (dbl), p_return_sqr (dbl), p_return_mean (dbl), Lim_or_out (dbl), closing_price (dbl), closing_vol (dbl) </code></pre> <p>Kindly help in resolving this error.</p>
34,428,344
3
4
null
2015-12-23 03:12:57.58 UTC
8
2018-01-26 23:43:19.987 UTC
2015-12-23 03:20:52.517 UTC
null
913,184
null
5,097,101
null
1
38
r|excel|xlsx
26,051
<p>Still no reproducible example, but from your <code>class(q1)</code> it appears that <code>q1</code> is a <code>tbl_df</code> (the sort of dataframe that the <code>dplyr</code> package produces) whereas <code>write.xlsx</code> expects a <code>data.frame</code>.</p> <p>Try giving <code>write.xlsx</code> a plain <code>data.frame</code> as it expects. e.g.</p> <pre><code>write.xlsx(as.data.frame(q1), ...) </code></pre> <p>Here's a <strong><a href="https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example">reproducible example</a></strong> (i.e. you could copy-paste it into your R session to reproduce the bug + fix).</p> <pre><code>library(dplyr) iris2 &lt;- tbl_df(iris) class(iris2) # like yours # [1] "tbl_df" "tbl" "data.frame" # Now let's try to write to XLSX using command as mentioned in your comments library(xlsx) write.xlsx(iris2, file='test.xlsx', sheetName="Sheet1", col.names=TRUE, row.names=FALSE, append=TRUE) # Error in .jcall(cell, "V", "setCellValue", value) : # method setCellValue with signature ([D)V not found # In addition: Warning message: # In if (is.na(value)) { : # the condition has length &gt; 1 and only the first element will be used # ^--- we can reproduce your error. This is the point of a reproducible example, so we can see if our fixes work for you. </code></pre> <p>Now let's try fix it by making sure that write.xlsx gets a data.frame, not a tbl_df!</p> <pre><code>write.xlsx(as.data.frame(iris2), file='test.xlsx', sheetName="Sheet1", col.names=TRUE, row.names=FALSE, append=TRUE) # huzzah! </code></pre>
53,420,055
Error while sorting array of objects Cannot assign to read only property '2' of object '[object Array]'
<p>I'm having array of objects where object looks like this (values change):</p> <pre><code> { stats: { hp: 2, mp: 0, defence: 4, agility: 11, speed: 6, strength: 31 } } </code></pre> <p>I want to sort them in descending order by speed doing:</p> <pre><code> array.sort((a, b) =&gt; { return b.stats.speed - a.stats.speed }) </code></pre> <p>However I'm getting this error and I can't really decipher whats going on:</p> <p>TypeError: Cannot assign to read only property '2' of object '[object Array]'</p> <p>What am I missing?</p> <p>Edit: Array of object in redux store:</p> <pre><code>const enemyDefaultState = [ { name: 'European Boy1', stats: { hp: 2, mp: 0, defence: 4, agility: 11, speed: 6, strength: 31 } }, { name: 'European Boy2', stats: { hp: 2, mp: 0, defence: 4, agility: 4, speed: 2, strength: 31 } }, { name: 'European Boy3', stats: { hp: 2, mp: 0, defence: 4, agility: 7, speed: 7, strength: 31 } }, </code></pre> <p>]</p> <p>I import the array and assign it to the variable:</p> <pre><code> let enemies = getState().enemy; if (enemies) { //sort by speed stat enemies.sort((a, b) =&gt; { return b.stats.speed - a.stats.speed }) } </code></pre>
53,420,326
4
18
null
2018-11-21 20:32:09.647 UTC
15
2021-11-08 05:54:10.56 UTC
2018-11-21 20:44:01.987 UTC
null
8,602,776
null
8,602,776
null
1
124
javascript|sorting
78,865
<p>Because the array is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze" rel="noreferrer">frozen</a> in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode" rel="noreferrer">strict mode</a>, you'll need to copy the array before sorting it:</p> <pre><code>array = array.slice().sort((a, b) =&gt; b.stats.speed - a.stats.speed) </code></pre>
6,746,059
Parsing XML into JSON
<p>I have an XML file, like</p> <pre><code>&lt;stock&gt;&lt;name&gt;AXL&lt;/name&gt;&lt;time&gt;19-07&lt;/time&gt;&lt;price&gt;11.34&lt;/price&gt;&lt;/stock&gt; &lt;stock&gt;&lt;name&gt;AIK&lt;/name&gt;&lt;time&gt;19-07&lt;/time&gt;&lt;price&gt;13.54&lt;/price&gt;&lt;/stock&gt; &lt;stock&gt;&lt;name&gt;ALO&lt;/name&gt;&lt;time&gt;19-07&lt;/time&gt;&lt;price&gt;16.32&lt;/price&gt;&lt;/stock&gt; &lt;stock&gt;&lt;name&gt;APO&lt;/name&gt;&lt;time&gt;19-07&lt;/time&gt;&lt;price&gt;13.56&lt;/price&gt;&lt;/stock&gt; ...............more </code></pre> <p>How can I parse this into JSON structure file? </p>
6,750,423
2
3
null
2011-07-19 10:59:02.233 UTC
9
2012-07-10 07:56:59.203 UTC
2012-07-10 07:56:59.203 UTC
null
331,508
null
741,395
null
1
7
java|xml|json|xml-parsing
23,603
<p>For a simple solution, I recommend <a href="http://jackson.codehaus.org">Jackson</a>, a Java library for generating and reading JSON with an extension for XML, as it can transform arbitrarily complex XML into JSON with just a few simple lines of code.</p> <p><strong>input.xml</strong></p> <pre><code>&lt;entries&gt; &lt;stock&gt;&lt;name&gt;AXL&lt;/name&gt;&lt;time&gt;19-07&lt;/time&gt;&lt;price&gt;11.34&lt;/price&gt;&lt;/stock&gt; &lt;stock&gt;&lt;name&gt;AIK&lt;/name&gt;&lt;time&gt;19-07&lt;/time&gt;&lt;price&gt;13.54&lt;/price&gt;&lt;/stock&gt; &lt;stock&gt;&lt;name&gt;ALO&lt;/name&gt;&lt;time&gt;19-07&lt;/time&gt;&lt;price&gt;16.32&lt;/price&gt;&lt;/stock&gt; &lt;stock&gt;&lt;name&gt;APO&lt;/name&gt;&lt;time&gt;19-07&lt;/time&gt;&lt;price&gt;13.56&lt;/price&gt;&lt;/stock&gt; &lt;/entries&gt; </code></pre> <p><strong>The Java Code:</strong></p> <pre><code>import java.io.File; import java.util.List; import org.codehaus.jackson.map.ObjectMapper; import com.fasterxml.jackson.xml.XmlMapper; public class Foo { public static void main(String[] args) throws Exception { XmlMapper xmlMapper = new XmlMapper(); List entries = xmlMapper.readValue(new File("input.xml"), List.class); ObjectMapper jsonMapper = new ObjectMapper(); String json = jsonMapper.writeValueAsString(entries); System.out.println(json); // [{"name":"AXL","time":"19-07","price":"11.34"},{"name":"AIK","time":"19-07","price":"13.54"},{"name":"ALO","time":"19-07","price":"16.32"},{"name":"APO","time":"19-07","price":"13.56"}] } } </code></pre> <p>This demo uses <a href="http://wiki.fasterxml.com/JacksonDownload">Jackson 1.7.7</a> (the newer 1.7.8 should also work), <a href="https://github.com/FasterXML/jackson-xml-databind/wiki">Jackson XML Databind 0.5.3</a> (not yet compatible with Jackson 1.8), and <a href="http://wiki.fasterxml.com/WoodstoxDownload">Stax2 3.1.1</a>.</p>
7,286,966
How to check if ID in database exists
<p>Why won't this send the user to user.php if the ID don't exist in the table?</p> <pre><code>&lt;?php include 'db_connect.php'; $id_exists = false; $url_id = mysql_real_escape_string($_GET['id']); $sql = &quot;SELECT id FROM members WHERE id='$url_id'&quot;; $result = mysql_query($sql); if ($result == $url_id) { $id_exists = true; } else if ($result != $url_id) { $id_exists = false; header(&quot;location:user.php&quot;); exit(); } ?&gt; </code></pre>
7,287,044
3
1
null
2011-09-02 17:13:26.473 UTC
null
2021-04-17 05:41:30.353 UTC
2021-04-17 05:41:30.353 UTC
null
11,573,842
null
918,323
null
1
4
php|mysql|get
39,692
<pre><code>$url_id = mysql_real_escape_string($_GET['id']); $sql = "SELECT id FROM members WHERE id='$url_id'"; $result = mysql_query($sql); if(mysql_num_rows($result) &gt;0){ //found }else{ //not found } </code></pre> <p>Try something like this :). <a href="http://php.net/manual/en/function.mysql-num-rows.php" rel="noreferrer">http://php.net/manual/en/function.mysql-num-rows.php</a></p>
7,116,019
Hand Install of 64-bit MS Access ODBC drivers when 32-bit Office is present
<p>I want to do a hand install of the MS Access 64 bit odbc drivers. Uninstalling 32 bit Office and installing 64 bit Office is not an option due to the add-ins that our company uses.</p> <p>I downloaded the AccessDatabaseEngine_x64.exe and using WinRar and Universal Extractor have managed to unpack all the files into a temp directory. I believe I have all of the files necessary but am a bit unsure where to go from here and would appreciate a little guidance.</p> <p>Which DLLs need to be registered to make the MS Access ODBC drivers available in the 64 bit ODBC administrator? </p> <p>Is there a list of registry entries that I will need to make for it to be available? </p> <p>Has anyone else dealt with this in a reasonable manner?</p> <p>Thank you in advance!</p>
8,611,645
4
3
null
2011-08-19 01:26:46.107 UTC
9
2019-10-31 16:53:50.907 UTC
null
null
null
null
888,339
null
1
22
ms-access|64-bit|odbc|registry|dllregistration
69,101
<p>using the /passive switch you can install 64-bit ace drivers even if 32-bit ms office is present: <a href="http://blog.codefluententities.com/2011/01/20/microsoft-access-database-engine-2010-redistributable/" rel="noreferrer">http://blog.codefluententities.com/2011/01/20/microsoft-access-database-engine-2010-redistributable/</a></p> <p>Just be warned that installing the 2010 64-bit ACE engine on a machine with 2010 32-bit Office already installed CAN lead to some wacky behavior in your already existing Office 2010.</p>
7,423,654
Export dump file from MySql
<p>I want to create a dump file of a table in the database. So database --> king, tablename --> castle So what I want to do is create a dump file.. and then the next part is to import it in my local host. database name --> king_local. Any ideas on how to go about this!! Thanks</p>
7,423,680
4
5
null
2011-09-14 22:15:05.43 UTC
22
2021-09-20 11:29:21.233 UTC
2018-01-08 00:35:27.69 UTC
null
1,268,759
null
902,885
null
1
31
mysql|dump|workbench
95,777
<p>To export:</p> <pre><code> mysqldump -u mysql_user -p DATABASE_NAME &gt; backup.sql </code></pre> <p>To import:</p> <pre><code> mysqldump -u mysql_user -p DATABASE_NAME &lt; backup.sql </code></pre>
7,846,476
Replace column in one file with column from another using awk?
<p>I have two files:</p> <pre><code>f1: 111 aaa 444 222 bbb 555 333 ccc 666 f2: 111 333 000 444 222 444 111 555 333 555 555 666 </code></pre> <p>How can I replace second column in "f1", with third column from "f2" using awk?</p>
7,846,550
1
0
null
2011-10-21 07:49:17.097 UTC
17
2017-04-21 15:31:50.06 UTC
null
null
null
null
251,931
null
1
20
replace|awk
27,875
<p><strong>try:</strong></p> <pre><code>awk 'FNR==NR{a[NR]=$3;next}{$2=a[FNR]}1' f2 f1 </code></pre> <p><strong>Output:</strong></p> <pre><code>111 000 444 222 111 555 333 555 666 </code></pre> <p><strong>Explanation of the above code:</strong></p> <ul> <li><code>FNR==NR</code> allows you to work with one entire file at a time. In this case it is the file <code>f2</code>. <code>NR</code> and <code>FNR</code> both contain line numbers with the difference being <code>FNR</code> gets reset to 1 when a new file is read where as <code>NR</code> continues to increment. </li> <li>While we are working with <code>f2</code> file, we are creating an array called <code>a</code> using line number (<code>NR</code>) as the <code>key</code> and third column (<code>$3</code>) as the value. <code>next</code> allows us to skip the rest of the action block. </li> <li>Once <code>f2</code> file ends, we start to work on <code>f1</code> file. <code>NR==FNR</code> condition will not become false as <code>FNR</code> will increment from 1 and <code>NR</code> won't. So only second action block <code>{$2=a[FNR]}</code> will be worked upon. </li> <li>What this block does is it re-assigns second column value to array value by looking up the line number. </li> <li><code>1</code> at the end prints the line. It returns true, and in <code>awk</code> true statements results in printing of the line. </li> <li><code>f2 f1</code> is the order of files defined. Since we want to create an array from file <code>f2</code> we put that first. </li> </ul>
1,600,801
GUI patterns to edit data with many-to-many relationship
<p>I often run into a situation where I need to come up with a GUI to edit data that has a n:m relationship. I'm looking for user friendly GUI ideas.</p> <pre><code>[table1] | /|\ [table2] \|/ | [table3] </code></pre> <p>Usually the GUI resembles something like this:</p> <hr> <p><code>Grid that shows all items from table1</code> </p> <p><kbd>Add table3 item...</kbd> <sub>(shows modal window with table3 items)</sub></p> <hr> <p><code>Grid that shows all items from table3</code></p> <hr> <p>After the user picked a table3 item, I add a new row to table2 and refresh the grids.</p> <p><strong>Disadvantages:</strong></p> <ul> <li>You can only add table3 items to table1, and not the other way around;</li> <li>You can only browse table1 items and see related table3 items;</li> <li>I need to have one filtered grid of table3 items, and a similar one to pick new items;</li> </ul> <p><strong>My question:</strong></p> <p>Does anyone know a better way to visually browse and edit data that has a n:m relationship? Or any nice patterns that I could "steal" from existing software packages? </p>
1,600,836
4
2
null
2009-10-21 13:20:31.627 UTC
10
2015-08-11 09:13:22.707 UTC
null
null
null
null
38,813
null
1
28
user-interface|language-agnostic|many-to-many
11,297
<p><strong>Solution 1</strong> </p> <p>If the data sets are not too big, use a table and allow users to place checks in cells (table 1 is X axis and table3 is Y axis). </p> <p>You can probably do this for larger table1/3 data sets as long as you allow users to filter or otherwise limit which values are displayed on x and y axis.</p> <p><strong>Solution 2</strong> </p> <p>To quote from <a href="http://www.databasedev.co.uk/many_to_many_example.html" rel="noreferrer">this page</a>, "A many-to-many relationship is really two one-to-many relationships with a junction/link table".</p> <p>As such, you can, as one solution, simply take your own solution and resolve your first 2 dis-advantages by having screens/dialogs to go table 1=>3 as well as 3=>1.</p> <p>Not a perfect solution but at least provides all the needed functionality</p> <p><strong>Solution 3</strong> </p> <p>Somewhat similar to your own solution:</p> <ol> <li><p>Show a table based on table1, with:</p> <p>B. col1 containing table1 elements</p> <p>C. col2 containing a list of all elements from table3 already associated with this element from table1. </p> <p>The list can be either horizontal if there are usually few elements associated, or vertical (scrollable) if horizontal to too wide.</p> <p>The important part is that every displayed element from table3 has a "delete" icon (x) next to it to allow removal quickly.</p></li> <li><p>Allow choosing which element from table1 you want to add mappings to.</p> <p>There are 2 ways of doing this - either add a checkbox to every row in your table, and have one button labeled "add relationships to selected rows" (wording needs improvement), or simply have a 3-rd column in the table, containing button/link for adding relationships to that individual row. </p> <p>The former is a good idea if the user is likely to often add exactly the same set of element from table3 to several rows from table1.</p></li> <li><p>When "Add" button/link is clicked, you display a filterable multi-select list of elements from table3, with "add selected" button.</p></li> <li><p>As in your solution (see my #2), this is a-symmetrical so you should implement a mirror UI for mapping from table3 to table1 if needed.</p></li> </ol>
1,822,314
How do I get a DataRow from a row in a DataGridView
<p>I'm using a databound Windows Forms <code>DataGridView</code>. how do I go from a user selected row in the <code>DataGridView</code> to the <code>DataRow</code> of the <code>DataTable</code> that is its source?</p>
1,822,343
4
0
null
2009-11-30 20:52:49.277 UTC
11
2019-01-24 17:54:18.89 UTC
2016-03-25 21:21:34.853 UTC
null
85,661
null
85,661
null
1
33
c#|winforms|datagridview|datatable
64,264
<pre><code>DataRow row = ((DataRowView)DataGridViewRow.DataBoundItem).Row </code></pre> <p>Assuming you've bound an ordinary <code>DataTable</code>.</p> <pre><code>MyTypedDataRow row = (MyTypedDataRow)((DataRowView)DataGridViewRow.DataBoundItem).Row </code></pre> <p>Assuming you've bound a typed datatable.</p> <p>See the <a href="http://msdn.microsoft.com/en-us/library/4wszzzc7.aspx" rel="noreferrer">article on MSDN</a> for more information.</p>
36,482,126
How to enlarge the SVG icon in material-ui iconButtons?
<p>Has anyone build webpages using <a href="https://facebook.github.io/react/" rel="noreferrer">react.js</a> and the <a href="https://www.material-ui.com/" rel="noreferrer">Material UI</a> library? How should I resize the icon size? It is a svg icon. I just built an "create new" component, which is a piece of material paper with a content add button on the top. Here is the code.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import React from 'react'; import Paper from 'material-ui/lib/paper'; import ContentAdd from 'material-ui/lib/svg-icons/content/add'; import IconButton from 'material-ui/lib/icon-button'; const styleForPaper = { width: '96vw', height: '20vh', margin: 20, textAlign: 'center', display: 'inline-block', }; const styleForButton = { 'marginTop': '7vh', }; const PaperToAddNewWidgets = () =&gt; ( &lt;div&gt; &lt;Paper style={styleForPaper} zDepth={2}&gt; &lt;IconButton style={styleForButton} touch={true} tooltip="Add New Widget"&gt; &lt;ContentAdd/&gt; &lt;/IconButton&gt; &lt;/Paper&gt; &lt;/div&gt; ); export default PaperToAddNewWidgets;</code></pre> </div> </div> </p> <p>It looks OK (make sure you are viewing it at full size), but the icon is too small. Then I opened the chrome dev tool, and saw the following html code. </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style="background-color:#ffffff;transition:all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms;box-sizing:border-box;font-family:Roboto, sans-serif;-webkit-tap-highlight-color:rgba(0,0,0,0);box-shadow:0 3px 10px rgba(0,0,0,0.16), 0 3px 10px rgba(0,0,0,0.23);border-radius:2px;width:96vw;height:20vh;margin:20px;text-align:center;display:inline-block;mui-prepared:;" data-reactid=".0.2.0.1.0"&gt;&lt;button style="border:10px;background:none;box-sizing:border-box;display:inline-block;font:inherit;font-family:Roboto, sans-serif;tap-highlight-color:rgba(0, 0, 0, 0);cursor:pointer;text-decoration:none;outline:none;transform:translate3d(0, 0, 0);position:relative;transition:all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms;padding:12px;width:48px;height:48px;font-size:0;margin-top:7vh;mui-prepared:;-webkit-appearance:button;" tabindex="0" type="button" data-reactid=".0.2.0.1.0.0"&gt;&lt;div data-reactid=".0.2.0.1.0.0.0"&gt;&lt;span style="height:100%;width:100%;position:absolute;top:0;left:0;overflow:hidden;mui-prepared:;" data-reactid=".0.2.0.1.0.0.0.0"&gt;&lt;/span&gt;&lt;div style="position: absolute; font-family: Roboto, sans-serif; font-size: 14px; line-height: 32px; padding: 0px 16px; z-index: 3000; color: rgb(255, 255, 255); overflow: hidden; top: -10000px; border-radius: 2px; opacity: 0; left: -44px; transition: top 0ms cubic-bezier(0.23, 1, 0.32, 1) 450ms, transform 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms, opacity 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms; box-sizing: border-box; -webkit-user-select: none;" data-reactid=".0.2.0.1.0.0.0.1:0"&gt;&lt;div style="position: absolute; left: 50%; top: 0px; transform: translate(-50%, -50%); border-radius: 50%; transition: width 0ms cubic-bezier(0.23, 1, 0.32, 1) 450ms, height 0ms cubic-bezier(0.23, 1, 0.32, 1) 450ms, backgroundColor 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms; width: 0px; height: 0px; background-color: transparent;" data-reactid=".0.2.0.1.0.0.0.1:0.0"&gt;&lt;/div&gt;&lt;span style="position:relative;white-space:nowrap;mui-prepared:;" data-reactid=".0.2.0.1.0.0.0.1:0.1"&gt;Add New Widget&lt;/span&gt;&lt;/div&gt;&lt;svg style="display:inline-block;height:24px;width:24px;transition:all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms;fill:rgba(0, 0, 0, 0.87);mui-prepared:;-webkit-user-select:none;" viewBox="0 0 24 24" data-reactid=".0.2.0.1.0.0.0.1:2:$/=10"&gt;&lt;path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" data-reactid=".0.2.0.1.0.0.0.1:2:$/=10.0"&gt;&lt;/path&gt;&lt;/svg&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p>Using chrome dev tool, I revised the svg icon size and the viewbox property of svg and made the icon larger in browser. But I am not sure how I can resize the icon size in my code. If I write a CSS file to revise the svg it will be problematic if there are more than one svg elements. </p>
38,840,120
16
6
null
2016-04-07 16:31:39.233 UTC
8
2022-06-28 13:20:32.63 UTC
2018-05-11 01:34:34.027 UTC
null
5,112,086
null
5,112,086
null
1
46
css|svg|reactjs|material-design|material-ui
124,464
<p><strong>Note</strong>: iconStyle prop is no longer supported on IconButton Material UI making this answer obsolete</p> <p>You have to set the size of the icon in the <code>iconStyle</code> prop in <code>&lt;IconButton&gt;</code>. Example below <a href="http://www.material-ui.com/#/components/icon-button" rel="nofollow noreferrer">from the material-ui docs</a>.</p> <p>From my experience, if you set just the height or the width, nothing happens--only seems to work when you set height &amp; width to the same value.</p> <pre><code>import React from 'react'; import IconButton from 'material-ui/IconButton'; import ActionHome from 'material-ui/svg-icons/action/home'; const styles = { largeIcon: { width: 60, height: 60, }, }; const IconButtonExampleSize = () =&gt; ( &lt;div&gt; &lt;IconButton iconStyle={styles.largeIcon} &gt; &lt;ActionHome /&gt; &lt;/IconButton&gt; &lt;/div&gt; ); </code></pre>
36,570,193
Merging develop branch into master
<p>I have a local repo with 2 branches <code>master</code> and <code>develop</code>. </p> <ul> <li>in <code>develop</code> branch I have all my Drupal 8 core code</li> <li>in my <code>master</code> branch I have 1 commit (Initial commit)</li> </ul> <p>On my remote repo I have all my Drupal 8 core code in branch <code>develop</code>. How do I get this code in the remote master branch? How do I have to merge those repo's?</p> <p><strong>Update:</strong></p> <p>When I do <code>git status</code> I get:</p> <pre><code>On branch master Your branch is up-to-date with 'origin/master'. Untracked files: (use "git add &lt;file&gt;..." to include in what will be committed) griffioenrotterdam.sublime-project griffioenrotterdam.sublime-workspace sites/ nothing added to commit but untracked files present (use "git add" to track) </code></pre> <p>What do I have to do?</p> <p><strong>Update 2:</strong></p> <p>When I do <code>git checkout develop</code> I get:</p> <pre><code>error: The following untracked working tree files would be overwritten by checkout: sites/default/default.services.yml sites/default/default.settings.php Please move or remove them before you can switch branches. Aborting </code></pre> <p>What do I have to do?</p>
36,570,620
4
8
null
2016-04-12 10:12:46.157 UTC
12
2020-12-04 15:16:31.273 UTC
2016-11-22 09:10:07.037 UTC
null
1,480,391
null
4,822,666
null
1
22
git|merge
53,005
<p>Summary: you need to switch to your develop branch, pull the code from the remote repo, then merge it into master (locally) and push it back to remote repo (into master branch)</p> <pre><code>git checkout develop git pull origin develop git checkout master git merge develop git push origin master </code></pre>
49,073,558
Laravel 5.6 Upgrade caused Logging to break
<p>Heey!</p> <p>So I've recently been given the task to take a Laravel 5.2 up to 5.6. It seemed to be fine...until I tried to do a <code>\Log::info()</code>. Every time I run that, I get a big error, but at the end, it still prints to the log. I saw the 5.6 documentation on creating the <code>config/logger.php</code>. I took a fresh copy of it from github. The only thing I did after that was set an env variable for the <code>LOG_CHANNEL</code> to be single. Here's the error I get: </p> <blockquote> <p>[2018-03-02 08:28:59] laravel.EMERGENCY: Unable to create configured logger. Using emergency logger. {"exception":"[object] (InvalidArgumentException(code: 0): Log [] is not defined. at I:\xampp\htdocs\mtm\vendor\laravel\framework\src\Illuminate\Log\LogManager.php:181) [ ....</p> </blockquote> <p>I did a file comparison between Laravel 5.2 and 5.6. I'm not seeing anything that jumps out that would break the Logging functionality. </p> <p>Has anyone run into this with a Laravel upgrade?</p>
49,075,655
9
6
null
2018-03-02 16:42:41.533 UTC
8
2022-03-30 11:50:06.897 UTC
null
null
null
null
1,729,405
null
1
41
php|laravel|logging|laravel-5.6
34,913
<p>Add this file to your config folder <a href="https://github.com/laravel/laravel/blob/5.6/config/logging.php" rel="noreferrer">https://github.com/laravel/laravel/blob/5.6/config/logging.php</a></p> <p>and add this to your .env file <code>LOG_CHANNEL=stack</code></p> <p>Don't forget to run <code>php artisan config:clear</code> command afterwards.</p>
7,022,742
setting NODE_ENV for node.js + expressjs application as a daemon under ubuntu
<p>i got the daemon working alright with these instructions: <a href="http://kevin.vanzonneveld.net/techblog/article/run_nodejs_as_a_service_on_ubuntu_karmic/">http://kevin.vanzonneveld.net/techblog/article/run_nodejs_as_a_service_on_ubuntu_karmic/</a></p> <p>but because this starts the application in DEVELOPMENT mode, the log file gets spammed with socket.io debug logs.</p> <p>i tried setting the NODE_ENV to production in the upstart-conf-file but had no success.</p> <pre><code>script export HOME="/root" export NODE_ENV=production exec /usr/local/bin/node /where/yourprogram.js &gt;&gt; /var/log/node.log 2&gt;&amp;1 end script </code></pre> <p>didn't work.</p>
7,115,544
5
0
null
2011-08-11 08:11:36.347 UTC
13
2016-01-27 14:42:40.38 UTC
null
null
null
null
388,026
null
1
28
linux|node.js|daemon|express
65,376
<p>Try</p> <pre><code>exec NODE_ENV=production /usr/local/bin/node /where/yourprogram.js &gt;&gt; /var/log/node.log 2&gt;&amp;1 </code></pre> <p>In my setup I'm sudoing as a lesser user, so it's</p> <pre><code>exec sudo -u some-user NODE_ENV=production /usr/local/bin/node /where/yourprogram.js &gt;&gt; /var/log/node.log 2&gt;&amp;1 </code></pre> <p>and since it's spawning off another user it probably has another environment. I'm a newbie here, but it works for me.</p>
7,390,126
What should the 'pop()' method return when the stack is empty?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/4892108/c-stl-stack-question-why-does-pop-not-throw-an-exception-if-the-stack-is-emp">C++ STL stack question: Why does pop() not throw an exception if the stack is empty?</a> </p> </blockquote> <p>When designing a stack in C++, what should the <strong>pop()</strong> method (or <strong>front()</strong> method) return when the stack is empty? Which of the following design is better?</p> <ol> <li>Throw an exception</li> <li>Undefined, but require the user calling <strong>isempty()</strong> method to check before calling <strong>pop()</strong></li> <li>Return a bool code, while using an extra parameter (a reference) to pass the popped element</li> <li>Define an unique <em>empty element</em></li> </ol> <hr> <p>OK, I see that my question is not that clear, let me try to rewrite it:</p> <p>There are some data structures which can be implemented based on linked list like stack, queue, and each of them has a methods returning the front element (or the tail). </p> <p>I want to know, is there any principle guideline about designing such a method regarding the case when the data is empty.</p> <p>And my definition of better is "easy to use correctly and hard to use incorrectly".</p>
7,390,181
6
8
null
2011-09-12 15:16:33.727 UTC
5
2020-12-06 14:44:56.68 UTC
2017-05-23 11:46:21.847 UTC
null
-1
null
244,031
null
1
20
c++|c|data-structures
39,725
<p>The programming-by-contract style would be that having a non-empty stack is a <em>precondition</em> of calling <code>pop</code>, and that calling a method without meeting its preconditions has an <strong>undefined</strong> outcome. My implementation would throw a <code>std::logic_error</code>, but that would not be <em>required</em>. In C, my implementation would <code>abort</code> via <code>assert</code>.</p> <p>The caller of <code>pop</code>is responsible for ensuring that the precondition that the stack is not empty holds before calling <code>pop</code>. The stack should therefore have an <code>isEmpty</code> method for the caller to check.</p>
7,259,238
How to forward typedef'd struct in .h
<p>I have Preprocessor.h</p> <pre><code>#define MAX_FILES 15 struct Preprocessor { FILE fileVector[MAX_FILES]; int currentFile; }; typedef struct Preprocessor Prepro; void Prepro_init(Prepro* p) { (*p).currentFile = 0; } </code></pre> <p>I realized then that I had to separate declarations from definitions. So I created Preprocessor.c:</p> <pre><code>#define MAX_FILES 15 struct Preprocessor { FILE fileVector[MAX_FILES]; int currentFile; }; typedef struct Preprocessor Prepro; </code></pre> <p>And Preprocessor.h is now:</p> <pre><code>void Prepro_init(Prepro* p) { (*p).currentFile = 0; } </code></pre> <p>That obviously, doesn't work because Pr..h doesn't know Prepro type. I already tried several combinations, none of them worked. I can't find the solution.</p>
7,259,303
6
6
null
2011-08-31 15:15:48.59 UTC
7
2017-02-15 11:16:05.193 UTC
null
null
null
null
796,608
null
1
30
c|typedef|forward-declaration
48,776
<p>Move the <code>typedef struct Preprocessor Prepro;</code> to the header the file and the definition in the c file along with the Prepro_init definition. This is will forward declare it for you with no issues.</p> <p>Preprocessor.h</p> <pre><code>#ifndef _PREPROCESSOR_H_ #define _PREPROCESSOR_H_ #define MAX_FILES 15 typedef struct Preprocessor Prepro; void Prepro_init(Prepro* p); #endif </code></pre> <p>Preprocessor.c</p> <pre><code>#include "Preprocessor.h" #include &lt;stdio.h&gt; struct Preprocessor { FILE fileVector[MAX_FILES]; int currentFile; }; void Prepro_init(Prepro* p) { (*p).currentFile = 0; } </code></pre>
7,243,970
Access a window by window name
<p>If I open a window using </p> <pre><code>window.open('myurl.html', 'windowname', 'width=100,height=100'); </code></pre> <p>How do I refer to the new window (from the same page that opened it) using 'windowname'? This question is specifically about this. I'm aware that I could save a reference to the handle by using "var mywin = window.open(...)" but I don't care about that in this situation.</p> <p>Thanks, - Dave</p>
7,244,052
7
5
null
2011-08-30 13:29:58.413 UTC
7
2019-09-13 14:02:38.727 UTC
null
null
null
null
623,658
null
1
42
javascript
71,744
<p>afaik there's no way like <code>windows['windowname']</code>. The 'windowname' assigned in window.open() can be addressed as a target in <code>&lt;a target="windowname" [...] &gt;</code></p>
14,274,225
Statement goto can not cross variable definition?
<p>Suppose these code compiled in <code>g++</code>:</p> <pre><code>#include &lt;stdlib.h&gt; int main() { int a =0; goto exit; int *b = NULL; exit: return 0; } </code></pre> <p><code>g++</code> will throw errors:</p> <pre><code>goto_test.c:10:1: error: jump to label ‘exit’ [-fpermissive] goto_test.c:6:10: error: from here [-fpermissive] goto_test.c:8:10: error: crosses initialization of ‘int* b’ </code></pre> <p>It seems like that the <code>goto</code> can not cross pointer definition, but <code>gcc</code> compiles them ok, nothing complained. </p> <p>After fixed the error, we must declare all the pointers before any of the <code>goto</code> statement, that is to say you must declare these pointers even though you do not need them at the present (and violation with some principles).</p> <p>What the origin design consideration that <code>g++</code> forbidden the useful <em>tail-goto</em> statement?</p> <hr> <p>Update:</p> <p><code>goto</code> can cross variable (<em>any type</em> of variable, not limited to pointer) declaration, <em>but except those that got a initialize value</em>. If we remove the <code>NULL</code> assignment above, <code>g++</code> keep silent now. So if you want to declare variables that between <code>goto</code>-cross-area, <em>do not</em> initialize them (and still violate some principles).</p>
14,274,292
2
1
null
2013-01-11 08:25:21.073 UTC
10
2019-01-29 20:16:30.793 UTC
2017-12-14 14:20:29.123 UTC
null
342,348
null
342,348
null
1
32
g++|goto
30,109
<p>Goto can't skip over initializations of variables, because the respective objects would not exist after the jump, since lifetime of object with non-trivial initialization starts when that initialization is executed:</p> <p><strong>C++11 §3.8/1:</strong></p> <blockquote> <p>[…] The lifetime of an object of type T begins when:</p> <ul> <li><p>storage with the proper alignment and size for type T is obtained, and</p></li> <li><p>if the object has non-trivial initialization, its initialization is complete.</p></li> </ul> </blockquote> <p><strong>C++11 §6.7/3:</strong></p> <blockquote> <p>It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer (8.5).</p> </blockquote> <p>Since the error mentions <code>[-fpermissive]</code>, you can turn it to warning by specifying that compiler flag. This indicates two things. That it used to be allowed (the variable would exist, but be uninitialized after the jump) and that gcc developers believe the specification forbids it.</p> <p>The compiler only checks whether the variable should be initialized, not whether it's used, otherwise the results would be rather inconsistent. But if you don't need the variable anymore, you can end it's lifetime yourself, making the "tail-goto" viable:</p> <pre><code>int main() { int a =0; goto exit; { int *b = NULL; } exit: return 0; } </code></pre> <p>is perfectly valid.</p> <p>On a side-note, the file has extension <code>.c</code>, which suggests it is C and not C++. If you compile it with <code>gcc</code> instead of <code>g++</code>, the original version should compile, because C does not have that restriction (it only has the restriction for variable-length arrays—which don't exist in C++ at all).</p>
14,191,468
OpenSSL encoding errors while converting cer to pem
<p>I`m trying to convert the .cer file to .pem through openssl, the command is:</p> <pre><code>openssl x509 -inform der -in certnew.cer -out ymcert.pem </code></pre> <p>and that's the errors I`m getting:</p> <pre><code>unable to load certificate 140735105180124:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1319: 140735105180124:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:381:Type=X509 </code></pre> <p>What am I doing wrong?</p>
23,677,967
5
1
null
2013-01-07 07:13:17.377 UTC
4
2022-06-11 06:30:47.533 UTC
2019-04-02 01:20:04.457 UTC
null
3,274,259
null
205,554
null
1
44
linux|openssl|certificate|ssl-certificate
90,963
<p>I had this problem also. Just rename the CER to PEM was enough :)</p>
13,876,875
How to make rpm auto install dependencies
<p>I have built two RPM packages</p> <ul> <li><code>proj1-1.0-1.x86_64.rpm</code></li> <li><code>libtest1-1.0-1.x86_64.rpm</code></li> </ul> <p><code>proj1</code> depends on the file <code>libtest1.so</code> being present and it is reflected correctly in the RPM packages as seen here:</p> <pre><code>user@my-pc:~$ rpm -qp --requires proj1-1.0-1.x86_64.rpm libtest1.so()(64bit) user@my-pc:~$ rpm -qp --provides libtest1-1.0-1.x86_64.rpm libtest1.so()(64bit) </code></pre> <p>The installation of <code>proj1</code> fails due to a missing dependency.</p> <pre><code>user@my-pc:~$ rpm -ivh proj1-1.0-1.x86_64.rpm error: Failed dependencies: libtest1.so()(64bit) is needed by proj1-1.0-1.x86_64.rpm </code></pre> <p>How do I ensure that <code>libtest1-1.0-1.x86_64.rpm</code> is installed automatically during the installation of <code>proj1-1.0-1.x86_64.rpm</code>?</p> <p>I did try the <code>--aid</code> option with <code>rpm -i</code> as described <a href="http://www.redhat.com/advice/tips/rhce/rpm.html" rel="noreferrer">here</a> but it didn't work for me.</p> <p>Is there any other way?</p> <p>Thanks for any help.</p>
13,877,738
12
0
null
2012-12-14 10:30:17.763 UTC
56
2021-04-03 02:32:05.243 UTC
2013-09-13 09:55:36.207 UTC
null
1,865,794
null
1,865,794
null
1
163
linux|installation|package|rpm|yum
566,013
<p>Create a (local) repository and use <code>yum</code> to have it resolve the dependencies for you.</p> <p>The CentOS wiki has a nice page providing a how-to on this. <a href="http://wiki.centos.org/HowTos/CreateLocalRepos">CentOS wiki HowTos/CreateLocalRepos</a>.</p> <hr> <p>Summarized and further minimized (not ideal, but quickest):</p> <ol> <li>Create a directory for you local repository, e.g. <code>/home/user/repo</code>.</li> <li>Move the RPMs into that directory.</li> <li><p>Fix some ownership and filesystem permissions:</p> <pre><code># chown -R root.root /home/user/repo </code></pre></li> <li><p>Install the <code>createrepo</code> package if not installed yet, and run</p> <pre><code># createrepo /home/user/repo # chmod -R o-w+r /home/user/repo </code></pre></li> <li><p>Create a repository configuration file, e.g. <code>/etc/yum.repos.d/myrepo.repo</code> containing</p> <pre><code>[local] name=My Awesome Repo baseurl=file:///home/user/repo enabled=1 gpgcheck=0 </code></pre></li> <li><p>Install your package using</p> <pre><code># yum install packagename </code></pre></li> </ol>
43,425,090
Ionic 3 can't use ion-* components inside my custom components
<p>I have recently upgraded to Ionic 3 from Ionic 2, and I created <strong>components.module.ts</strong> file and declared and exported each custom component I have, and then imported this single file in every page module I have.</p> <p>So now the problem is that I can't use ion-* components inside my own components, because I did not imported the <code>IonicModule.forRoot(..)</code> inside my components.module.</p> <p>The error is: </p> <blockquote> <p>"Template parse errors: 'ion-spinner' is not a known element ..."</p> </blockquote> <p>What am I doing wrong?</p>
43,425,661
2
1
null
2017-04-15 10:45:45.86 UTC
6
2018-05-04 19:13:28.027 UTC
2017-04-15 10:46:41.65 UTC
null
4,826,457
null
3,315,874
null
1
33
angular|ionic2|ionic3
12,188
<p>Alright, so I figured out the solution: </p> <p>All i needed was to import <code>IonicModule</code> in <code>components.module</code>, <strong>without</strong> <code>forRoot(..)</code>.</p> <p>Also note that Angular's <code>CommonModule</code> is also necessary to make Angular's directives work, so you probably need to import it too.</p>
58,796,490
tsc.ps1 cannot be loaded because running scripts is disabled on this system
<p>On PowerShell, I got the error message when executing <code>tsc</code>. This never happened before.</p> <p>I am not sure should I mingle with the PowerShell security settings to rectify this such as based on this one: <a href="https://stackoverflow.com/questions/4037939/powershell-says-execution-of-scripts-is-disabled-on-this-system">PowerShell says &quot;execution of scripts is disabled on this system.&quot;</a></p> <h2>Update</h2> <p>This is a new intended feature by npm to use ps1 scripts. A question has been raised in their repo: <a href="https://github.com/npm/cli/issues/470" rel="noreferrer">https://github.com/npm/cli/issues/470</a></p>
58,801,137
15
4
null
2019-11-11 06:27:10.693 UTC
27
2022-08-15 23:54:10.927 UTC
2019-11-29 04:53:08.797 UTC
null
9,319,588
null
9,319,588
null
1
65
typescript|powershell
73,279
<p>You can run this in PowerShell command. Be sure to run it as administrator:</p> <pre><code>Set-ExecutionPolicy -ExecutionPolicy RemoteSigned </code></pre>
62,824,043
Is Cloud Functions in Firebase Free or Not (Cloud Functions deployment requires the pay-as-you-go (Blaze) billing plan)
<p>When i make my first deploy function I can't deploying Because I have Error Asks me to make Upgrade to my account to Blaze I need to Know Can i deploy Function when i use free account??</p> <p>Output:</p> <pre><code>i deploying functions i functions: ensuring required API cloudfunctions.googleapis.com is enabled... i functions: ensuring required API cloudbuild.googleapis.com is enabled... ! functions: missing required API cloudbuild.googleapis.com. Enabling now... + functions: required API cloudfunctions.googleapis.com is enabled Error: Cloud Functions deployment requires the pay-as-you-go (Blaze) billing plan. To upgrade your project, visit the following URL: https://console.firebase.google.com/project/institute-for-admin/usage/details For additional information about this requirement, see Firebase FAQs: https://firebase.google.com/support/faq#functions-runtime </code></pre>
62,824,105
7
0
null
2020-07-09 21:33:07.233 UTC
12
2022-09-09 17:23:49.867 UTC
2022-01-16 00:17:44.407 UTC
null
8,172,439
null
13,084,725
null
1
69
firebase|google-cloud-functions|firebase-cli
45,211
<p>As the message says, you can't deploy functions on the Spark free tier, if you target nodejs 10. <a href="https://firebase.google.com/support/faq#functions-runtime" rel="noreferrer">Read the link to the FAQ</a>:</p> <blockquote> <p><strong>Why will I need a billing account to use the Node.js 10 runtime for Cloud Functions for Firebase?</strong></p> <p>Because of updates to its underlying architecture planned for August 17, 2020, Cloud Functions for Firebase will rely on some additional paid Google services: <a href="https://cloud.google.com/cloud-build" rel="noreferrer">Cloud Build</a>, <a href="https://cloud.google.com/container-registry/" rel="noreferrer">Container Registry</a>, and <a href="https://cloud.google.com/storage" rel="noreferrer">Cloud Storage</a>. These architecture updates will apply for functions deployed to the Node.js 10 runtime. Usage of these services will be billed in addition to existing pricing.</p> <p>In the new architecture, Cloud Build supports the deployment of functions. You'll be billed only for the computing time required to build a function's runtime container.</p> <p>Cloud Storage, interoperating with <a href="https://cloud.google.com/container-registry/" rel="noreferrer">Google Container Registry</a>, will provide storage space for the containers in which functions run. You'll be billed for each container required to deploy a function. If you're currently using Cloud Functions within free usage limits, you may notice new, small charges for each container stored— for example, 1GB of storage is <a href="https://cloud.google.com/container-registry/pricing#storage" rel="noreferrer">billed at $0.026 per month</a>.</p> <p>To understand more about how your bill might change, please review the following</p> <ul> <li><a href="https://cloud.google.com/functions/pricing" rel="noreferrer">Cloud Functions pricing</a>: existing free tier is unchanged.</li> <li><a href="https://cloud.google.com/cloud-build/pricing" rel="noreferrer">Cloud Build pricing</a>: Cloud Build provides for a free tier.</li> <li><a href="https://cloud.google.com/container-registry/pricing" rel="noreferrer">Container Registry pricing</a>.</li> </ul> </blockquote> <p>If you want to target node 8, that might still work. But it's been deprecated, and your functions will eventually stop working. You would still have to <a href="https://medium.com/firebase-developers/migrate-your-firebase-cloud-functions-to-node-js-10-d9c677933ee" rel="noreferrer">migrate them to node 10</a> in that case, and provide a billing account.</p> <p>Cloud Functions still has a monthly free allowance that's <a href="https://firebase.google.com/pricing" rel="noreferrer">documented in the pricing page</a>. But you will have to provide a credit card and be on a billing plan in order to use it. You will be responsible for paying for any monthly overage.</p>
45,786,717
How to implement HashMap with two keys?
<p><code>HashMap</code> implements the <code>get</code> and <code>insert</code> methods which take a single immutable borrow and a single move of a value respectively.</p> <p>I want a trait which is just like this but which takes two keys instead of one. It uses the map inside, but it's just a detail of implementation.</p> <pre><code>pub struct Table&lt;A: Eq + Hash, B: Eq + Hash&gt; { map: HashMap&lt;(A, B), f64&gt;, } impl&lt;A: Eq + Hash, B: Eq + Hash&gt; Memory&lt;A, B&gt; for Table&lt;A, B&gt; { fn get(&amp;self, a: &amp;A, b: &amp;B) -&gt; f64 { let key: &amp;(A, B) = ??; *self.map.get(key).unwrap() } fn set(&amp;mut self, a: A, b: B, v: f64) { self.map.insert((a, b), v); } } </code></pre>
45,795,699
2
5
null
2017-08-20 20:55:47.353 UTC
14
2021-08-07 10:41:04.147 UTC
2018-05-29 15:58:25.817 UTC
null
1,479,702
null
8,452,477
null
1
40
hashmap|rust
6,747
<p>This is certainly possible. The <a href="https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.get" rel="noreferrer">signature of <code>get</code></a> is</p> <pre><code>fn get&lt;Q: ?Sized&gt;(&amp;self, k: &amp;Q) -&gt; Option&lt;&amp;V&gt; where K: Borrow&lt;Q&gt;, Q: Hash + Eq, </code></pre> <p>The problem here is to implement a <code>&amp;Q</code> type such that</p> <ol> <li><code>(A, B): Borrow&lt;Q&gt;</code></li> <li><code>Q</code> implements <code>Hash + Eq</code></li> </ol> <p>To satisfy condition (1), we need to think of how to write</p> <pre><code>fn borrow(self: &amp;(A, B)) -&gt; &amp;Q </code></pre> <p>The trick is that <code>&amp;Q</code> <em>does not need to be a simple pointer</em>, it can be a <a href="https://stackoverflow.com/questions/27567849/what-makes-something-a-trait-object">trait object</a>! The idea is to create a trait <code>Q</code> which will have two implementations:</p> <pre><code>impl Q for (A, B) impl Q for (&amp;A, &amp;B) </code></pre> <p>The <code>Borrow</code> implementation will simply return <code>self</code> and we can construct a <code>&amp;dyn Q</code> trait object from the two elements separately.</p> <hr /> <p>The <a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=fa1d88a3f3255fa7a6ca39dee02da4d8" rel="noreferrer">full implementation</a> is like this:</p> <pre><code>use std::borrow::Borrow; use std::collections::HashMap; use std::hash::{Hash, Hasher}; // See explanation (1). trait KeyPair&lt;A, B&gt; { /// Obtains the first element of the pair. fn a(&amp;self) -&gt; &amp;A; /// Obtains the second element of the pair. fn b(&amp;self) -&gt; &amp;B; } // See explanation (2). impl&lt;'a, A, B&gt; Borrow&lt;dyn KeyPair&lt;A, B&gt; + 'a&gt; for (A, B) where A: Eq + Hash + 'a, B: Eq + Hash + 'a, { fn borrow(&amp;self) -&gt; &amp;(dyn KeyPair&lt;A, B&gt; + 'a) { self } } // See explanation (3). impl&lt;A: Hash, B: Hash&gt; Hash for dyn KeyPair&lt;A, B&gt; + '_ { fn hash&lt;H: Hasher&gt;(&amp;self, state: &amp;mut H) { self.a().hash(state); self.b().hash(state); } } impl&lt;A: Eq, B: Eq&gt; PartialEq for dyn KeyPair&lt;A, B&gt; + '_ { fn eq(&amp;self, other: &amp;Self) -&gt; bool { self.a() == other.a() &amp;&amp; self.b() == other.b() } } impl&lt;A: Eq, B: Eq&gt; Eq for dyn KeyPair&lt;A, B&gt; + '_ {} // OP's Table struct pub struct Table&lt;A: Eq + Hash, B: Eq + Hash&gt; { map: HashMap&lt;(A, B), f64&gt;, } impl&lt;A: Eq + Hash, B: Eq + Hash&gt; Table&lt;A, B&gt; { fn new() -&gt; Self { Table { map: HashMap::new(), } } fn get(&amp;self, a: &amp;A, b: &amp;B) -&gt; f64 { *self.map.get(&amp;(a, b) as &amp;dyn KeyPair&lt;A, B&gt;).unwrap() } fn set(&amp;mut self, a: A, b: B, v: f64) { self.map.insert((a, b), v); } } // Boring stuff below. impl&lt;A, B&gt; KeyPair&lt;A, B&gt; for (A, B) { fn a(&amp;self) -&gt; &amp;A { &amp;self.0 } fn b(&amp;self) -&gt; &amp;B { &amp;self.1 } } impl&lt;A, B&gt; KeyPair&lt;A, B&gt; for (&amp;A, &amp;B) { fn a(&amp;self) -&gt; &amp;A { self.0 } fn b(&amp;self) -&gt; &amp;B { self.1 } } //---------------------------------------------------------------- #[derive(Eq, PartialEq, Hash)] struct A(&amp;'static str); #[derive(Eq, PartialEq, Hash)] struct B(&amp;'static str); fn main() { let mut table = Table::new(); table.set(A(&quot;abc&quot;), B(&quot;def&quot;), 4.0); table.set(A(&quot;123&quot;), B(&quot;456&quot;), 45.0); println!(&quot;{:?} == 45.0?&quot;, table.get(&amp;A(&quot;123&quot;), &amp;B(&quot;456&quot;))); println!(&quot;{:?} == 4.0?&quot;, table.get(&amp;A(&quot;abc&quot;), &amp;B(&quot;def&quot;))); // Should panic below. println!(&quot;{:?} == NaN?&quot;, table.get(&amp;A(&quot;123&quot;), &amp;B(&quot;def&quot;))); } </code></pre> <p>Explanation:</p> <ol> <li><p>The <code>KeyPair</code> trait takes the role of <code>Q</code> we mentioned above. We'd need to <code>impl Eq + Hash for dyn KeyPair</code>, but <code>Eq</code> and <code>Hash</code> are both not <a href="https://stackoverflow.com/questions/44096235/understanding-traits-and-object-safety">object safe</a>. We add the <code>a()</code> and <code>b()</code> methods to help implementing them manually.</p> </li> <li><p>Now we implement the <code>Borrow</code> trait from <code>(A, B)</code> to <code>dyn KeyPair + 'a</code>. Note the <code>'a</code> — this is a subtle bit that is needed to make <code>Table::get</code> actually work. The arbitrary <code>'a</code> allows us to say that an <code>(A, B)</code> can be borrowed to the trait object for <em>any</em> lifetime. If we don't specify the <code>'a</code>, the unsized trait object will <a href="https://stackoverflow.com/questions/26212397/references-to-traits-in-structs">default to <code>'static</code></a>, meaning the <code>Borrow</code> trait can only be applied when the implementation like <code>(&amp;A, &amp;B)</code> outlives <code>'static</code>, which is certainly not the case.</p> </li> <li><p>Finally, we implement <code>Eq</code> and <code>Hash</code>. Same reason as point 2, we implement for <code>dyn KeyPair + '_</code> instead of <code>dyn KeyPair</code> (which means <code>dyn KeyPair + 'static</code> in this context). The <code>'_</code> here is a syntax sugar meaning arbitrary lifetime.</p> </li> </ol> <hr /> <p>Using trait objects will incur indirection cost when computing the hash and checking equality in <code>get()</code>. The cost can be eliminated if the optimizer is able to devirtualize that, but whether LLVM will do it is unknown.</p> <p>An alternative is to store the map as <code>HashMap&lt;(Cow&lt;A&gt;, Cow&lt;B&gt;), f64&gt;</code>. Using this requires less &quot;clever code&quot;, but there is now a memory cost to store the owned/borrowed flag as well as runtime cost in both <code>get()</code> and <code>set()</code>.</p> <p>Unless you fork the standard <code>HashMap</code> and add a method to look up an entry via <code>Hash + Eq</code> alone, there is no guaranteed-zero-cost solution.</p>
34,065,614
Is there a simple way to make Visual Studio 2015 use a specific ToolsVersion?
<p>When building a project or solution using a specific version of <code>msbuild</code> I can select an earlier .net toolchain by using the <code>/toolsversion</code> or <code>/tv</code> switch:</p> <pre><code>"C:\Program Files (x86)\MSBuild\14.0\bin\msbuild" /tv:12.0 amazing.sln </code></pre> <p>This Just Works for all versions of <code>msbuild</code>, and the version of <code>csc.exe</code> etc. is correctly chosen based on the above:</p> <pre><code>&gt; "C:\Program Files (x86)\MSBuild\14.0\bin\msbuild" /tv:4.0 amazing.sln ... CoreCompile: C:\Windows\Microsoft.NET\Framework\v4.0.30319\Csc.exe ... ... &gt; "C:\Program Files (x86)\MSBuild\14.0\bin\msbuild" /tv:12.0 amazing.sln ... CoreCompile: C:\Program Files (x86)\MSBuild\12.0\bin\Csc.exe ... ... </code></pre> <p>If I <em>don't</em> specify <code>/tv</code>, then depending on which version of msbuild I'm using and a number of environment variables, I may get any of:</p> <ul> <li>The ToolsVersion specified in the top-level element in the project file</li> <li>The ToolsVersion corresponding to the version of <code>msbuild.exe</code> I'm using</li> <li>A value from <code>msbuild.exe.config</code></li> <li>A value from the registry</li> </ul> <p>(See the <a href="https://msdn.microsoft.com/en-us/library/bb383985.aspx">different versions of the <em>Overriding ToolsVersion Settings</em> page on MSDN</a>).</p> <p>So, in order to have builds that have consistent results on the build server and on my local machine, I use <code>/tv</code> when running <code>msbuild.exe</code> (in fact, this is enforced in a <code>psake</code> script, which also ensures it uses the corresponding version of <code>msbuild.exe</code>).</p> <p><strong>However</strong> I cannot use the <code>/tv</code> switch when building with Visual Studio. Instead, Visual Studio 2013 and up will use the .net toolchain that shipped with that version of Visual Studio <em>unless</em>:</p> <ul> <li>The environment variable <code>MSBUILDLEGACYDEFAULTTOOLSVERSION</code> is set <em>and</em>...</li> <li>...all the project files have the ToolsVersion attribute set to the version I want to use.</li> </ul> <p>This is so baroque that I cannot believe anyone is actually doing it. My questions are thus:</p> <ul> <li><em>Is</em> anyone doing the <code>MSBUILDLEGACYDEFAULTTOOLSVERSION</code> thing?</li> <li>If not, is there another way to make Visual Studio use a specific ToolsVersion short of using the version of Visual Studio that shipped with that ToolsVersion? Something that could be stored in version control (so in a project or some other settings file) would be ideal.</li> </ul> <p>And lastly:</p> <ul> <li>Should I even care? Given that each successive version of the C# compiler should be able to handle previous versions' input, and I can set the target .net framework and C# language level in the project file, is this enough to ensure repeatable builds?</li> </ul> <p>(My prejudice is that I <em>should</em> care, since:</p> <ul> <li>I want builds in the IDE and on the build server to be the same (of course)</li> <li>I want to be able to use VS2015 (and future versions) because it's a better IDE than previous versions, but I don't want to be obliged to use the new toolchain until I decide to.</li> </ul> <p>Perhaps I want too much...)</p> <p>For a concrete example of the problem, please see my <a href="https://github.com/guyboltonking/msbuild-vs-vs2015-toolsversion">msbuild-vs-vs2015-toolsversion</a> repository on github.</p> <hr> <p>Some background: I'm asking this because we recently had a CI build error when one of my colleagues submitted C# 6.0 code that compiled fine with Roslyn on their copy of Visual Studio 2015, but failed in CI because <em>that</em> uses the previous release of the .net toolchain (they'd used an automatic property with no setter, which is fine in Roslyn but not in earlier versions). We will be updating the CI build to Roslyn, but I wanted to see if we could prevent this sort of thing happening in the future.</p>
38,898,525
4
4
null
2015-12-03 12:04:21.05 UTC
6
2017-02-10 11:03:23.263 UTC
2016-02-03 09:18:50.977 UTC
null
322,152
null
322,152
null
1
49
c#|.net|msbuild|visual-studio-2015
19,597
<p>I solved this by writing a Visual Studio extension that temporarily sets the environment variable <code>MSBUILDDEFAULTTOOLSVERSION</code> for the duration of a build; the value to be used is read from a file <code>.toolsversion</code> in the same directory as the <code>.sln</code> file. The psake script reads the same <code>.toolsversion</code> file and passes the value to the <code>/tv</code> switch.</p> <p>The code for the extension can be found here: <a href="https://github.com/guyboltonking/set-toolsversion-extension" rel="nofollow noreferrer">https://github.com/guyboltonking/set-toolsversion-extension</a>. Sadly, I'm not working with C++, or indeed with Visual Studio, at the moment, so I can't provide any support for it (but I can tell you I used it with no issues at all for several months).</p> <p>Kudos to @efaruk for reminding me about the existence of <code>MSBUILDDEFAULTTOOLSVERSION</code>.</p> <p>Edit: Thanks to @mbadawi23, it's now possible to use the extension with both VS2015 and VS2017.</p>
34,211,076
Destructuring deep properties
<p>I recently started using ES6's <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" rel="noreferrer">destructuring</a> assignment syntax and started to get familiar with the concept. I was wondering if it's possible to extract a nested property using the same syntax. </p> <p>For example, let's say I have the following code:</p> <pre><code>let cagingIt = { foo: { bar: 'Nick Cage' } }; </code></pre> <p>I know I am able to access extract <code>foo</code> into a variable by doing:</p> <pre><code>// where foo = { bar: "Nick Cage" } let { foo } = cagingIt; </code></pre> <p>However, is it possible to extract a deeply nested property, like <code>bar</code>. Perhaps something like this:</p> <pre><code>// where bar = "Nick Cage" let { foo[bar] } = cagingIt; </code></pre> <p>I've tried finding documentation on the matter but to no avail. Any help would be greatly appreciated. Thank you!</p>
34,211,272
4
5
null
2015-12-10 20:25:22.977 UTC
9
2022-06-28 19:18:02.16 UTC
null
null
null
null
1,558,171
null
1
68
javascript|ecmascript-6
19,823
<p>There is a way to handle nested objects and arrays using this syntax. Given the problem described above, a solution would be the following:</p> <pre><code>let cagingIt = { foo: { bar: 'Nick Cage' } }; let { foo: {bar: name} } = cagingIt; console.log(name); // "Nick Cage" </code></pre> <p>In this example, <code>foo</code> is referring to the property name "foo". Following the colon, we then use <code>bar</code> which refers to the property "bar". Finally, <code>name</code> acts as the variable storing the value. </p> <p>As for array destructuring, you would handle it like so:</p> <pre><code>let cagingIt = { foo: { bar: 'Nick Cage', counts: [1, 2, 3] } }; let { foo: {counts: [ ct1, ct2, ct3 ]} } = cagingIt; console.log(ct2); // prints 2 </code></pre> <p>It follows the same concept as the object, just you are able to use array destructuring and store those values as well.</p> <p>Hope this helps!</p>
24,647,400
What is the best stemming method in Python?
<p>I tried all the nltk methods for stemming but it gives me weird results with some words. </p> <p>Examples</p> <p>It often cut end of words when it shouldn't do it :</p> <ul> <li>poodle => poodl</li> <li>article articl</li> </ul> <p>or doesn't stem very good : </p> <ul> <li>easily and easy are not stemmed in the same word</li> <li>leaves, grows, fairly are not stemmed</li> </ul> <p>Do you know other stemming libs in python, or a good dictionary?</p> <p>Thank you</p>
24,648,116
7
3
null
2014-07-09 07:12:45.08 UTC
17
2022-03-19 23:36:47.197 UTC
2014-07-09 07:19:29.423 UTC
null
1,206,829
null
1,206,829
null
1
44
python|nltk|stemming
77,226
<p>Python implementations of the Porter, Porter2, Paice-Husk, and Lovins stemming algorithms for English are available in the <a href="https://pypi.python.org/pypi/stemming/1.0" rel="nofollow noreferrer">stemming package</a></p>
947,404
sed line range, all but the last line
<p>You can specify a range of lines to operate on. For example, to operate on all lines, (which is of course the default):</p> <pre><code>sed -e "1,$ s/a/b/" </code></pre> <p>But I need to operate on all but the last line. You apparently can't use arithmetic expressions:</p> <pre><code>sed -e "1,$-1 s/a/b/" </code></pre> <p>(I am using cygwin in this case, if it makes a difference)</p>
947,464
5
0
null
2009-06-03 21:38:11.987 UTC
11
2016-08-08 12:40:04.747 UTC
2015-08-03 19:09:57.153 UTC
null
14,749
null
14,749
null
1
40
sed
26,832
<pre><code>sed -e "$ ! s/a/b/" </code></pre> <p>This will match every line but the last. Confirmed with a quick test!</p>
31,871
WSACancelBlockingCall exception
<p>Ok, I have a strange exception thrown from my code that's been bothering me for ages.</p> <pre><code>System.Net.Sockets.SocketException: A blocking operation was interrupted by a call to WSACancelBlockingCall at System.Net.Sockets.Socket.Accept() at System.Net.Sockets.TcpListener.AcceptTcpClient() </code></pre> <p>MSDN isn't terribly helpful on this : <a href="http://msdn.microsoft.com/en-us/library/ms741547(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms741547(VS.85).aspx</a> and I don't even know how to begin troubleshooting this one. It's only thrown 4 or 5 times a day, and never in our test environment. Only in production sites, and on ALL production sites. </p> <p>I've found plenty of posts asking about this exception, but no actual definitive answers on what is causing it, and how to handle or prevent it.</p> <p>The code runs in a separate background thread, the method starts :</p> <pre><code>public virtual void Startup() { TcpListener serverSocket= new TcpListener(new IPEndPoint(bindAddress, port)); serverSocket.Start(); </code></pre> <p>then I run a loop putting all new connections as jobs in a separate thread pool. It gets more complicated because of the app architecture, but basically:</p> <pre><code> while (( socket = serverSocket.AcceptTcpClient()) !=null) //Funny exception here { connectionHandler = new ConnectionHandler(socket, mappingStrategy); pool.AddJob(connectionHandler); } } </code></pre> <p>From there, the <code>pool</code> has it's own threads that take care of each job in it's own thread, separately.</p> <p>My understanding is that AcceptTcpClient() is a blocking call, and that somehow winsock is telling the thread to stop blocking and continue execution.. but why? And what am I supposed to do? Just catch the exception and ignore it? </p> <hr> <p>Well, I do think some other thread is closing the socket, but it's certainly not from my code. What I would like to know is: is this socket closed by the connecting client (on the other side of the socket) or is it closed by my server. Because as it is at this moment, whenever this exception occurs, it shutsdown my listening port, effectively closing my service. If this is done from a remote location, then it's a major problem. </p> <p>Alternatively, could this be simply the IIS server shutting down my application, and thus cancelling all my background threads and blocking methods?</p>
34,373
5
0
null
2008-08-28 08:59:07.527 UTC
12
2020-11-04 13:19:54.67 UTC
2020-11-04 13:19:54.67 UTC
Radu094
297,823
Radu094
3,263
null
1
54
c#|multithreading|sockets|socketexception
99,563
<p>Is it possible that the serverSocket is being closed from another thread? That will cause this exception.</p>
227,101
Can I block search crawlers for every site on an Apache web server?
<p>I have somewhat of a staging server on the public internet running copies of the production code for a few websites. I'd really not like it if the staging sites get indexed. </p> <p>Is there a way I can modify my httpd.conf on the staging server to block search engine crawlers? </p> <p>Changing the robots.txt wouldn't really work since I use scripts to copy the same code base to both servers. Also, I would rather not change the virtual host conf files either as there is a bunch of sites and I don't want to have to remember to copy over a certain setting if I make a new site.</p>
7,364,999
6
0
null
2008-10-22 18:51:28.367 UTC
12
2011-09-09 16:58:26.67 UTC
null
null
null
Nick
24,988
null
1
20
apache|search|web-crawler|httpd.conf
24,523
<p>Create a robots.txt file with the following contents:</p> <pre><code>User-agent: * Disallow: / </code></pre> <p>Put that file somewhere on your staging server; your directory root is a great place for it (e.g. <code>/var/www/html/robots.txt</code>).</p> <p>Add the following to your httpd.conf file:</p> <pre><code># Exclude all robots &lt;Location "/robots.txt"&gt; SetHandler None &lt;/Location&gt; Alias /robots.txt /path/to/robots.txt </code></pre> <p>The <code>SetHandler</code> directive is probably not required, but it might be needed if you're using a handler like mod_python, for example.</p> <p>That robots.txt file will now be served for all virtual hosts on your server, overriding any robots.txt file you might have for individual hosts.</p> <p>(Note: My answer is essentially the same thing that ceejayoz's answer is suggesting you do, but I had to spend a few extra minutes figuring out all the specifics to get it to work. I decided to put this answer here for the sake of others who might stumble upon this question.)</p>