title
stringlengths
10
150
body
stringlengths
17
64.2k
label
int64
0
3
Fix Resharper intellisense
<p>Does anyone know how to fix this, besides pressing esc then typing the variable name again?</p> <p><img src="https://i.stack.imgur.com/buGX0.jpg" alt="enter image description here"></p> <pre><code>JetBrains ReSharper 6.1 C# Edition Build 6.1.37.86 on 2011-12-21T04:15:24 Plugins: none Visual Studio 10.0.30319.1. </code></pre>
0
create hidden input with thymeleaf data
<p>So basically I have this table in my html page and its almost work as it should</p> <pre><code>&lt;div th:each="good : ${goodList}"&gt; &lt;form action="#" th:action="@{/zamow}" th:object="${enterGoodAction}" method="post"&gt; &lt;tr&gt; &lt;input type="hidden" path="id" value="${good.id}"/&gt; //this input &lt;th&gt;&lt;span th:text="${good.name}"/&gt;&lt;/th&gt; &lt;th&gt;&lt;span th:text="${good.amount}"/&gt;&lt;/th&gt; &lt;th&gt;&lt;span th:text="${good.price}" /&gt;&lt;/th&gt; &lt;th&gt;&lt;span th:text="${good.tax}" /&gt;&lt;/th&gt; &lt;th&gt;&lt;input type="number" min="1" th:field="*{amount}"/&gt;&lt;/th&gt; &lt;th&gt;&lt;input type="submit" value="Zamów" /&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/form&gt; </code></pre> <p>Now what I want to do is create this hidden input which will pass me "good.id" data to my controller but whatever i do with him he is always null. How can i fix it? I think controller works well so the problem is with my input only. Actual imput might looks silly but its my 10th try or something and I was desperate ;/</p>
0
How to run Selenium Java tests with TestNG programmatically?
<p>I am using Selenium RC with Java using TestNG as Test Framework. I'm using Eclipse as IDE. I want to invoke TestNG from my own program very easily. How can I do that?</p>
0
How is geom_point removing rows containing missing values?
<p>I'm unsure why none of my data points show up on the map.</p> <pre><code> Store_ID visits CRIND_CC ISCC EBITDAR top_bottom Latitude Longitude (int) (int) (int) (int) (dbl) (chr) (fctr) (fctr) 1 92 348 14819 39013 76449.15 top 41.731373 -93.58184 2 2035 289 15584 35961 72454.42 top 41.589428 -93.80785 3 50 266 14117 27262 49775.02 top 41.559017 -93.77287 4 156 266 7797 25095 28645.95 top 41.6143 -93.834404 5 66 234 8314 18718 46325.12 top 41.6002 -93.779236 6 207 18 2159 17999 20097.99 bottom 41.636208 -93.531876 7 59 23 10547 28806 52168.07 bottom 41.56153 -93.88083 8 101 23 1469 11611 7325.45 bottom 41.20982 -93.84298 9 130 26 2670 13561 14348.98 bottom 41.614517 -93.65789 10 130 26 2670 13561 14348.98 bottom 41.6145172 -93.65789 11 24 27 17916 41721 69991.10 bottom 41.597134 -93.49263 &gt; dput(droplevels(top_bottom)) structure(list(Store_ID = c(92L, 2035L, 50L, 156L, 66L, 207L, 59L, 101L, 130L, 130L, 24L), visits = c(348L, 289L, 266L, 266L, 234L, 18L, 23L, 23L, 26L, 26L, 27L), CRIND_CC = c(14819L, 15584L, 14117L, 7797L, 8314L, 2159L, 10547L, 1469L, 2670L, 2670L, 17916L ), ISCC = c(39013L, 35961L, 27262L, 25095L, 18718L, 17999L, 28806L, 11611L, 13561L, 13561L, 41721L), EBITDAR = c(76449.15, 72454.42, 49775.02, 28645.95, 46325.12, 20097.99, 52168.07, 7325.45, 14348.98, 14348.98, 69991.1), top_bottom = c("top", "top", "top", "top", "top", "bottom", "bottom", "bottom", "bottom", "bottom", "bottom" ), Latitude = structure(c(11L, 4L, 2L, 7L, 6L, 10L, 3L, 1L, 8L, 9L, 5L), .Label = c("41.20982", "41.559017", "41.56153", "41.589428", "41.597134", "41.6002", "41.6143", "41.614517", "41.6145172", "41.636208", "41.731373"), class = "factor"), Longitude = structure(c(3L, 7L, 5L, 8L, 6L, 2L, 10L, 9L, 4L, 4L, 1L), .Label = c("-93.49263", "-93.531876", "-93.58184", "-93.65789", "-93.77287", "-93.779236", "-93.80785", "-93.834404", "-93.84298", "-93.88083"), class = "factor")), row.names = c(NA, -11L), .Names = c("Store_ID", "visits", "CRIND_CC", "ISCC", "EBITDAR", "top_bottom", "Latitude", "Longitude"), class = c("tbl_df", "tbl", "data.frame")) </code></pre> <p>Creating the plot:</p> <pre><code>map &lt;- qmap('Des Moines') + geom_point(data = top_bottom, aes(x = as.numeric(Longitude), y = as.numeric(Latitude)), colour = top_bottom, size = 3) </code></pre> <p>I get the warning message:</p> <pre><code>Removed 11 rows containing missing values (geom_point). </code></pre> <p>However, this works without the use of <code>ggmap()</code>:</p> <pre><code>ggplot(top_bottom) + geom_point(aes(x = as.numeric(Longitude), y = as.numeric(Latitude)), colour = top_bottom, size = 3) </code></pre> <p><a href="https://i.stack.imgur.com/AxuX4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AxuX4.png" alt="enter image description here"></a></p> <p>How do I get the points to overlay on ggmap??</p>
0
How to add a custom Ribbon tab using VBA?
<p>I am looking for a way to add a custom tab in the Excel ribbon which would carry a few buttons. I chanced on some resources addressing it via Google but all look dodgy and outrageously complicated. </p> <p>What is a quick and simple way to do that ? I'd like the new tab to get loaded when my VBA gets loaded into Excel..</p> <p><strong>UPDATE</strong> : I tried this example from <a href="http://msdn.microsoft.com/en-us/library/ee767705.aspx" rel="noreferrer">here</a> but get an "object required" error on the last instruction :</p> <pre><code>Public Sub AddHighlightRibbon() Dim ribbonXml As String ribbonXml = "&lt;mso:customUI xmlns:mso=""http://schemas.microsoft.com/office/2009/07/customui""&gt;" ribbonXml = ribbonXml + " &lt;mso:ribbon&gt;" ribbonXml = ribbonXml + " &lt;mso:qat/&gt;" ribbonXml = ribbonXml + " &lt;mso:tabs&gt;" ribbonXml = ribbonXml + " &lt;mso:tab id=""highlightTab"" label=""Highlight"" insertBeforeQ=""mso:TabFormat""&gt;" ribbonXml = ribbonXml + " &lt;mso:group id=""testGroup"" label=""Test"" autoScale=""true""&gt;" ribbonXml = ribbonXml + " &lt;mso:button id=""highlightManualTasks"" label=""Toggle Manual Task Color"" " ribbonXml = ribbonXml + "imageMso=""DiagramTargetInsertClassic"" onAction=""ToggleManualTasksColor""/&gt;" ribbonXml = ribbonXml + " &lt;/mso:group&gt;" ribbonXml = ribbonXml + " &lt;/mso:tab&gt;" ribbonXml = ribbonXml + " &lt;/mso:tabs&gt;" ribbonXml = ribbonXml + " &lt;/mso:ribbon&gt;" ribbonXml = ribbonXml + "&lt;/mso:customUI&gt;" ActiveProject.SetCustomUI (ribbonXml) End Sub </code></pre>
0
Change desktop wallpaper using code in .NET
<p>How can I change the desktop wallpaper using C# Code?</p>
0
How to find the length of unsigned char* in C
<p>I have a variable </p> <pre><code>unsigned char* data = MyFunction(); </code></pre> <p>how to find the length of data?</p>
0
Why can't PHP have a constant object?
<p>I have a key-value database table, where I store some settings.</p> <p>I would like to have these settings in a PHP constant object, since they shouldn't be editable.</p> <p>In PHP7 we can now do this:</p> <pre><code>define('MySettings', array( 'title' =&gt; 'My title' // etc )); // And call it with echo MySettings['title']; </code></pre> <p>And it works great.</p> <p>But why can't I do:</p> <pre><code>define('MySettings', (object) array('title' =&gt; 'My title')); </code></pre> <p>So I could call it like this instead:</p> <pre><code>echo MySettings-&gt;title; // or echo MySettings::title; </code></pre> <p>This is only because I think it's quicker and prettier to type it as an object property/constant (<code>$obj-&gt;key</code>, <code>$obj::key</code>), than as array (<code>$array['key']</code>)</p> <p>Is there any reason this is not possible?</p>
0
How to fix > No signature of method: build_dxc6m5s863o0nfrfjdg2bqjp.android() is applicable for argument types
<p>Problem: A problem occurred evaluating project ':app'.</p> <blockquote> <p>No signature of method: build_dxc6m5s863o0nfrfjdg2bqjp.android() is applicable for argument types: (build_dxc6m5s863o0nfrfjdg2bqjp$_run_closure1) values: [build_dxc6m5s863o0nfrfjdg2bqjp$_run_closure1@18112963]</p> </blockquote> <p>Gradle File:</p> <pre><code>apply plugin: 'com.android.application' android { compileSdkVersion 21 buildToolsVersion &quot;21.1.2&quot; defaultConfig { applicationId &quot;com.numix.calculator_pro&quot; testApplicationId &quot;com.numix.calculator_pro_pro.pro.tests&quot; testInstrumentationRunner &quot;android.test.InstrumentationTestRunner&quot; } lintOptions { checkReleaseBuilds false // Or, if you prefer, you can continue to check for errors in release builds, // but continue the build even when errors are found: abortOnError false } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } } dependencies { implementation 'com.android.support:support-v4:21.0.3' compile files('libs/achartengine.jar') compile files('libs/ejml-0.21.jar') compile files('libs/arity-2.1.6.jar') compile files('libs/slider.jar') compile files('libs/acra-4.5.0-sources.jar') compile files('libs/acra-4.5.0-javadoc.jar') } </code></pre>
0
How to simulate mouse click using C++?
<p>I need to simulate a mouse click that clicks on application windows. I'm using Windows.</p> <p>How can I send a left button mouse click to screen <code>x, y</code> coordinates where the window is located?</p>
0
Embed a JavaFX application in a HTML webpage
<p>I'd like to embed one ore more JavaFX applications on a webpage. How do you do that?</p> <p>There are several bits and pieces on the Oracle website, but there's no <strong>complete</strong> example.</p> <p>There's the <a href="http://docs.oracle.com/javafx/2/deployment/deployment_toolkit.htm" rel="noreferrer">Deployment in the Browser</a> tutorial, the <a href="http://docs.oracle.com/javafx/2/deployment/packaging.htm" rel="noreferrer">Packaging Basics</a> tutorial, etc. There's mentioning of Ant tasks and what not.</p> <p>So there were still a lot of questions after I read them. Like do I need Ant? Do I need to create an applet? etc</p> <p>All I'd like to see is a minimal and complete "Hello World" example in order to see how it works. Even here on StackOverflow are only bits and pieces to answers of the same question, so that don't really help.</p> <p><em>I had this question up yesterday, but deleted it and thought I'd try myself. Turned out that it is only easy when you know the pitfalls. So since this was already asked here I thought I'd share my minimal and complete example in the answer.</em></p> <p><em>Using the JavaFX samples it took only a few minutes to create the code for this html page:</em></p> <p><img src="https://i.stack.imgur.com/o6P7Y.png" alt="enter image description here"></p>
0
Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '10s'
<p>I'm no doubt missing something really obvious here but I can't figure it out. Any help would be appreciated. The mistake is coming from here:</p> <pre><code>package B00166353_Grades; public class Student{ String name,banner; public Student(String name,String banner){ this.name=name; this.banner=banner; } public String toString(){ String productDetails=new String(); productDetails+=String.format("%-20s%10.2s%10s",this.name,this.banner); return productDetails; } } </code></pre>
0
HTML2PDF in PHP - convert utilities & scripts - examples & demos
<p>I have a quite complicated HTML/CSS layout which I would like to convert to PDF on my server. I already have tryed DOMPDF, unfortunately it did not convert the HTML with correct layout. I have considered HTMLDOC but I have heard that it ignores CSS to a large extent, so I suppose the layout would break apart with that tool too.</p> <p>My question therefor is - are there any online demos for other tools (like wkhtmltopdf i.e.) that I could use to verify how my HTML is converted? Before spending the rest of my life installing &amp; testing one by one?</p> <p>Unfortunately, I can't change the HTML layout to fit those tools. Or better said - I could, if any of them would get close to an acceptable result...</p>
0
How can I load storyboard programmatically from class?
<p>My problem is that I was looking for way to use both <strong>storyboard</strong> and <strong>xib</strong>. But I can't find proper way to load and show storyboard programmatically. Project was started developing with xib, and now it's very hard to nest all xib files in storyboard. So I was looking a way to do it in code, like with <code>alloc, init, push</code> for viewControllers. In my case I have only one controller in storyboard: <code>UITableViewController</code>, which has static cells with some content I want to show. If anyone knows proper way to work both with xib and storyboard without huge refactoring, I will appreciate for any help.</p>
0
How to prompt the user to enter a integer within a certain amount of numbers
<p>I was trying to figure out what statement to use to get the user to enter a number between 1 and 10. </p> <p>here is what i have so far.</p> <pre><code>int a; printf("Enter a number between 1 and 10: \n); scanf("%d", &amp;a); </code></pre>
0
Renaming pandas data frame columns using a for loop
<p>I'm not sure if this is a dumb way to go about things, but I've got several data frames, all of which have identical columns. I need to rename the columns within each to reflect the names of each data frame (I'll be performing an outer merge of all of these afterwards). </p> <p>Let's say the data frames are called <code>df1</code>, <code>df2</code> and <code>df3</code>, and each contains the columns <code>name</code>, <code>date</code>, and <code>count</code>. </p> <p>I'd like to rename each of the columns in <code>df1</code> into <code>name_df1</code>, <code>date_df1</code>, and <code>count_df1</code>. </p> <p>I've written a function to rename the columns, thus: </p> <pre><code>df_list=[df1, df2, df3] def rename_cols(): col_name="name"+suffix col_count="count"+suffix col_date="date"+suffix for x in df_list: if x['name'].tail(1).item() == df1['name'].tail(1).item(): suffix="_"+"df1" rename_cols() continue elif x['name'].tail(1).item() == df2['name'].tail(1).item(): suffix="_"+"df2" rename_cols() continue else: suffix="_"+"df3" rename_cols() col_names=[col_name,col_date,col_count] x.columns=col_names </code></pre> <p>Unfortunately, I get the following error: <code>KeyError: 'name'</code></p> <p>I'm really struggling to figure out why that's going on. The columns for df1, the first data frame in the <code>df_list</code>, gets renamed. Everything else stays the same... Am I messing up basic syntax (probably), or is there a fundamental misunderstanding that I've got of how things should work? </p> <p>From what I can ascertain, the first data frame in the list is being iterated through more than once — but why would that be the case?</p>
0
Sending Commands through Telnet via Bash Script
<p>I am attempting to automate a telnet session in Debian, but I am having difficulty when it comes to sending commands.</p> <p>By looking <a href="https://stackoverflow.com/questions/7013137/automating-telnet-session-using-bash-scripts">here</a>, I had a good understanding of what I needed to do.</p> <pre><code>spawn telnet localhost expect "login:" send "test\n" expect "Password:" send "password\n" sleep 10 //Time for the connection to be established send "ls\n" </code></pre> <p>Running the script, it correctly inputed the username. It got to the password field and i'm assuming it entered it in (though I can't be for sure since passwords are left blank in Debian when entered). It stalled for the wait, then brought me back to my account (root). It did not ever connect to "test".</p> <p>Modifying my code to be more like my reference:</p> <pre><code>spawn telnet localhost expect "login:" send "test\n" expect "Password:" send "password\n" interact </code></pre> <p>This led to it immediately logging in and connecting in my "test" account. From here I tried adding commands after interact using send, echo, and just typing the command. Nothing would happen until I exited the telnet session, then I would get this error.</p> <p>For send:</p> <pre><code>send: spawn id exp6 not open while executing "send "ls\n"" (file ".telnet.sh" line 8) </code></pre> <p>For echo:</p> <pre><code>invalid command name "echo" while executing "echo "ls\n"" (file ".telnet.sh" line 8) </code></pre> <p>With just the command name "ls" invalid command name "ls" while executing "ls" (file ".telnet.sh" line 8)</p> <p>I realize interact gives control back to the user, but for some reason it is the only way it will actually have me connect into the account.</p> <p>Does anyone know why it is having trouble connecting without interact? If not, why I cannot send those commands until the telnet session has ended with interact?</p> <p><strong>EDIT</strong> After some research I found this <a href="http://forums.anandtech.com/showthread.php?t=2325260" rel="nofollow noreferrer">link</a>, which at the end comes to a resolve that an expect script ends immediately after everything is finished, closing the telnet session. They said they fixed the issue by adding a expect "$ " to let the script know more commands are being sent its way. I tried just using the '$' symbol like the site suggested, but it ended kicking me again. So I tried this.</p> <p>Here is my updated code:</p> <pre><code>#!/usr/bin/expect spawn telnet localhost expect "debian login" send "test\n" expect "Password:" send "password\n" expect "test@debian:~$" send "ls\n" </code></pre> <p>Now I am still in the telnet session for about 10 seconds, and then it kicks me off. If I try to enter in a command in that time, it pauses for that time, then runs the command I typed after the telnet session closes.</p> <p>Progress is being made. Slowly but surely.</p>
0
How to calculate the sentence similarity using word2vec model of gensim with python
<p>According to the <a href="http://radimrehurek.com/gensim/models/word2vec.html" rel="noreferrer">Gensim Word2Vec</a>, I can use the word2vec model in gensim package to calculate the similarity between 2 words.</p> <p>e.g.</p> <pre><code>trained_model.similarity('woman', 'man') 0.73723527 </code></pre> <p>However, the word2vec model fails to predict the sentence similarity. I find out the LSI model with sentence similarity in gensim, but, which doesn't seem that can be combined with word2vec model. The length of corpus of each sentence I have is not very long (shorter than 10 words). So, are there any simple ways to achieve the goal?</p>
0
How do i print out a number triangle in python?
<p>How do i print out a number triangle in python using a loop based program? It is not a homework assignment or anything its just an exercise from the book i have been trying to do but have not really come close. The triangle should print out looking like this: </p> <pre><code>1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 </code></pre>
0
Create a variable in a Pandas dataframe based on information in the dataframe
<p>I have a dataframe organized in the following way</p> <pre><code> var1 var2 var3 var4 0 A 23 B 7 1 B 13 C 4 2 C 12 A 11 3 A 5 C 15 </code></pre> <p>I now want to create a new variable (column), var5, which takes the value of var2 if var1 == A and the value of var4 if var3 == A. For simplicity, var1 and var3 can never both have the value A. If neither var1 or var3 takes value A, then I want NaN. That is, the outcome in this example would be:</p> <pre><code> var1 var2 var3 var4 var5 0 A 23 B 7 23 1 B 13 C 4 NaN 2 C 12 A 11 11 3 A 5 C 15 5 </code></pre> <p>How can this be achieved?</p>
0
How do the different enum variants work in TypeScript?
<p>TypeScript has a bunch of different ways to define an enum:</p> <pre><code>enum Alpha { X, Y, Z } const enum Beta { X, Y, Z } declare enum Gamma { X, Y, Z } declare const enum Delta { X, Y, Z } </code></pre> <p>If I try to use a value from <code>Gamma</code> at runtime, I get an error because <code>Gamma</code> is not defined, but that's not the case for <code>Delta</code> or <code>Alpha</code>? What does <code>const</code> or <code>declare</code> mean on the declarations here?</p> <p>There's also a <code>preserveConstEnums</code> compiler flag -- how does this interact with these?</p>
0
How to Learn Python on an Android Tablet
<p>My brother got excited about coding and would like to learn it. I recommended him Python as the first language. It will be ideal if he can experiment, make first programs on his andoid tablet.</p> <p>Online solutions like <a href="http://www.pythonanywhere.com/" rel="nofollow">Pythonanywhere</a> are not usable in the default browser: When pressing a key in python console, the screen jumps to the top of page.</p> <p>We looked for native apps and found only QPython which isn't very beginner friendly: it can't evaluate <code>print</code> statements, program fails when there is traceback (many times for a beginner who forgets about a ':' after for, if, and while)</p> <p>How to learn python on an android tablet? What app or which website to use?</p>
0
SQLite database in combination with fragments
<p>I'm changing my application from Activity's to Fragments, it's going great but I've one bug that won't let me open my database. Here's the error (from the logcat):</p> <pre><code>05-17 15:28:38.704 13025-13025/com.MJV.werktijden E/AndroidRuntime: FATAL EXCEPTION: main java.lang.NullPointerException at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224) at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164) at com.MJV.werktijden.DBAdapter.open(DBAdapter.java:71) at com.MJV.werktijden.OverviewFragment.onActivityCreated(OverviewFragment.java:38) at android.app.Fragment.performActivityCreated(Fragment.java:1703) at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:903) at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057) at android.app.BackStackRecord.run(BackStackRecord.java:682) at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435) at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441) at android.os.Handler.handleCallback(Handler.java:725) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5041) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>I tried to solve it myself, but I couldn't find the problem. Just because this database did work when I used it with Activity's. I'm opening the database with this method:</p> <pre><code> //---opens the database--- public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } </code></pre> <p>And that method is being called from my Fragment:</p> <pre><code>private final DBAdapter db = new DBAdapter(getActivity()); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.overview_layout, container, false); return rootView; } public void onActivityCreated (Bundle savedInstanceState){ listView = (ListView) getView().findViewById(R.id.listView1); db.open(); </code></pre> <p>Thanks for helping in advance.</p>
0
PyTorch DataLoader - "IndexError: too many indices for tensor of dimension 0"
<p>I am trying to implement a CNN to identify digits in the MNIST dataset and my code comes up with the error during the data loading process. I don't understand why this is happening.</p> <pre class="lang-py prettyprint-override"><code>import torch import torchvision import torchvision.transforms as transforms transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5), (0.5)) ]) trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=20, shuffle=True, num_workers=2) testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset, batch_size=20, shuffle=False, num_workers=2) for i, data in enumerate(trainloader, 0): inputs, labels = data[0], data[1] </code></pre> <p>Error:</p> <pre><code>--------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-6-b37c638b6114&gt; in &lt;module&gt; 2 ----&gt; 3 for i, data in enumerate(trainloader, 0): 4 inputs, labels = data[0], data[1] # ... IndexError: Traceback (most recent call last): File "/opt/conda/lib/python3.6/site-packages/torch/utils/data/_utils/worker.py", line 99, in _worker_loop samples = collate_fn([dataset[i] for i in batch_indices]) File "/opt/conda/lib/python3.6/site-packages/torch/utils/data/_utils/worker.py", line 99, in &lt;listcomp&gt; samples = collate_fn([dataset[i] for i in batch_indices]) File "/opt/conda/lib/python3.6/site-packages/torchvision/datasets/mnist.py", line 95, in __getitem__ img = self.transform(img) File "/opt/conda/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 61, in __call__ img = t(img) File "/opt/conda/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 164, in __call__ return F.normalize(tensor, self.mean, self.std, self.inplace) File "/opt/conda/lib/python3.6/site-packages/torchvision/transforms/functional.py", line 208, in normalize tensor.sub_(mean[:, None, None]).div_(std[:, None, None]) IndexError: too many indices for tensor of dimension 0 </code></pre>
0
Mocking Joda DateTime method using Mockito
<p>I want <code>millis</code> to return specified value.</p> <pre><code>public long myMethod(){ DateTime nowDateTime = new DateTime(DateTimeZone.UTC); long millis = nowDateTime.getMillis(); System.out.println(millis); } </code></pre> <p>I tried this with no luck.</p> <pre><code>@RunWith(PowerMockRunner.class) @PrepareForTest({ DateTime.class }) @PowerMockIgnore({ "javax.crypto.*", "javax.management*" }) ... ... public void testMyMethod(){ DateTime nowDateTime = PowerMockito.mock(DateTime.class); Mockito.when(nowDateTime.getMillis()).thenReturn(10L); } </code></pre> <p>How can I fix this?</p>
0
What's a Chocolatey "Install" package?
<p>On reviewing the <a href="https://chocolatey.org/packages">chocolatey packages</a> available, I came across a few that have two (or sometimes more) packages apparently for the same product. At first glance is not possible to tell the difference.</p> <p>For example, there is the <em>AutohotKey</em> package, and then there is also an <em>Autohotkey.<strong>install</em></strong> package.</p> <p>What is the difference between both types of packages?</p>
0
Unity UI RectTransform position does not make sense to me
<p>So, I'm using C# in unity to place some objects using Unity UI, and I have an object whose position in script is not the same as its position in the scene. I have the following code in a function:</p> <pre><code>using UnityEngine; using System.Collections; public class SeedChecker : MonoBehaviour { Vector3 lockedPos; RectTransform tran; // Use this for initialization void Awake () { tran = GetComponent&lt;RectTransform&gt;(); } public void LockPos(Vector3 pos) { tran.localPosition = pos; lockedPos = pos; print (tran.localPosition); } } </code></pre> <p>As an example, this code prints that its x position is -60 -- which is the correct number that I'm looking for -- 60 pixels to the left of the middle of the screen. But, when I look in the inspector and in the scene, the x position is 0 -- and the object is positioned exactly in the middle of the screen. This makes for a rather frustrating situation, which I've also <a href="http://answers.unity3d.com/questions/961638/ui-image-position-assignment-not-working-correctly.html" rel="noreferrer">talked about here</a>. It's frustrating because it says it's getting the proper position, but when I assign this correct position to the object, it goes to what I think is the incorrect place. Is this a misunderstanding of how localpositions work in RectTransforms? My object is the child of a few objects, but all of them are zeroed to the center of the screen, and have "1" for scale values.</p>
0
GridView elements changes their place dynamically when scroll screen
<p><strong>i have a gridview layout, and all items are insert very fine,</strong></p> <p>now if I check on big screen then all work done is fine, because no scrolling is required</p> <p>but if I check on small screen then items are changed their position dynamically,</p> <p>bereif example is given below:-</p> <p><strong>like I have 28 items and arranged in a grid view 7*4, now if upto 20 items are shown in first screen, now remaining 8 is shown while i scroll screen down, but now some elements of first or second row is aslo put in last row.</strong></p> <p>code is here</p> <pre><code>public class ImageAdapter extends BaseAdapter { Context mContext; //public static final int ACTIVITY_CREATE = 10; public ImageAdapter(Context c) { mContext = c; } @Override public int getCount() { // TODO Auto-generated method stub return providers.length; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View v; if(convertView==null) { LayoutInflater li = getLayoutInflater(); v = li.inflate(R.layout.icontext, null); TextView tv = (TextView)v.findViewById(R.id.icon_text); tv.setText(providers[position]); ImageView iv = (ImageView)v.findViewById(R.id.icon_image); iv.setImageResource(R.drawable.icon); } else { v = convertView; } return v; } </code></pre>
0
ASP.NET CLR Not Enabled
<p>I am getting the following error on my new installation of ASP.Net and SQL Server when I run my app:</p> <pre><code> Execution of user code in the .NET Framework is disabled. Enable "clr enabled" configuration option </code></pre> <p>I have tried to fix it by running this:</p> <pre><code> use dasolPSDev; sp_configure 'clr enabled', 1 go RECONFIGURE go sp_configure 'clr enabled' go </code></pre> <p>But then I get:</p> <pre><code> Msg 102, Level 15, State 1, Line 3 Incorrect syntax near 'sp_config </code></pre>
0
Feature/Variable importance after a PCA analysis
<p>I have performed a PCA analysis over my original dataset and from the compressed dataset transformed by the PCA I have also selected the number of PC I want to keep (they explain almost the 94% of the variance). Now I am struggling with the identification of the original features that are important in the reduced dataset. How do I find out which feature is important and which is not among the remaining Principal Components after the dimension reduction? Here is my code:</p> <pre><code>from sklearn.decomposition import PCA pca = PCA(n_components=8) pca.fit(scaledDataset) projection = pca.transform(scaledDataset) </code></pre> <p>Furthermore, I tried also to perform a clustering algorithm on the reduced dataset but surprisingly for me, the score is lower than on the original dataset. How is it possible? </p>
0
Select onchange reload the page and keep the selected option
<p>I have this <a href="https://jsfiddle.net/1zqgeq79/2/" rel="nofollow noreferrer">https://jsfiddle.net/1zqgeq79/2/</a></p> <p>This is the jquery I'm using to make the page refresh when a select has been changed and now I just need it to keep that selected option after the page loads.</p> <pre><code> $('.ProductDetails select').change(function () { location.reload(); }); </code></pre> <p>Since I have multiple items I know a (this) will have to be used, but I'm still learning jquery. Thanks for the help!</p>
0
Can't change font in Atom
<p>I've tried setting various fonts in Atom (Fedora 21, Atom 0.187) but none seem to work. I've tried setting Font Family to DejaVuSansMono and DroidSansMono but nothing changes (And yes they are installed)</p>
0
Redirect to a subfolder in Apache virtual host file
<p>I have Joomla installed on a webserver running Ubuntu Server 12.04. The Joomla folder is located at /var/www/cms/. </p> <p>My vhost file at /etc/apache2/sites-enabled/default has the following content:</p> <pre><code>&lt;VirtualHost *:80&gt; ServerName domain.com/ Redirect permanent / https://domain.com/ &lt;/VirtualHost&gt; &lt;VirtualHost *:443&gt; ServerAdmin webmaster@localhost ServerName domain.com:443 DocumentRoot /var/www/cms &lt;Directory /&gt; Options FollowSymLinks AllowOverride All &lt;/Directory&gt; &lt;Directory /var/www/cms&gt; Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all &lt;/Directory&gt; (...) &lt;/VirtualHost&gt; </code></pre> <p>At the moment, all the requests to domain.com and anything entered after that like domain.com/example gets directed and processed by Joomla which either redirects to a proper page or returns a custom 404 error. This all works. </p> <p>Now, I would like to filter all the requests that go to domain.com/subfolder before they get processed by Joomla and redirect them to /var/www/subfolder (instead of my root folder at /var/www/cms/).</p> <p>I believe the file in /etc/apache2/sites-enabled/default (seen above) is the right place to define such a redirect, however I have not been able to figure out at what position and how to achieve this.</p>
0
InternalsVisibleTo does not work
<p>I insert the line:</p> <p><code>[assembly: InternalsVisibleTo("MyTests")]</code> </p> <p>inside my project under test( <code>Properties/AssemblyInfo.cs</code>) where <code>MyTests</code> is the name of the Unit Test project. But for some reason I still cannot access the internal methods from the unit test project.</p> <p>Any ideas about what I am doing wrong ?</p>
0
How to resolve errors CS1003: Syntax error, '(' expected, and error CS1031: Type expected?
<p>I am creating a 2d platform game in the Unity Engine Version Num - 2018.4.9f1 with c# compiled with Visual Studio Version Num - 1.38.1.</p> <p>The console in Unity Engine is showing two errors listed below with the code I have in the Visual Studio.</p> <blockquote> <p>error CS1003: Syntax error, '(' expected</p> <p>error CS1031: Type expected</p> </blockquote> <p>My code:</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof)(Text))] public class CountdownText : MonoBehaviour { public delegate void CountdownFinished(); public static event CountdownFinished OnCountdownFinished; Text countdown; void OnEnable() { countdown = GetComponent&lt;Text&gt;(); countdown.text = "3"; StartCoroutine("Countdown"); } IEnumerator Countdown() { int count = 3; for (int i = 0; i &lt; count; i++) { countdown.text = (count - i).ToString(); yield return new WaitForSeconds(1); } OnCountdownFinished(); } } </code></pre>
0
milliseconds to days
<p>i did some research, but still can't find how to get the days... Here is what I got:</p> <pre><code>int seconds = (int) (milliseconds / 1000) % 60 ; int minutes = (int) ((milliseconds / (1000*60)) % 60); int hours = (int) ((milliseconds / (1000*60*60)) % 24); int days = ????? ; </code></pre> <p>Please help, I suck at math, thank's.</p>
0
How can I bulk rename files in PowerShell?
<p>I'm trying to do the following:</p> <pre><code>Rename-Item c:\misc\*.xml *.tmp </code></pre> <p>I basically want to change the extension on every files within a directory to <code>.tmp</code> instead of <code>.xml</code>. I can't seem to find a straight forward way to do this in PowerShell.</p>
0
Read Contents of txt file and display in Tkinter GUI Python
<p>Hey I have successfully created a <code>tkinter</code> GUI in python which saves the entered values in a text file. Here is the code:</p> <pre><code>from Tkinter import * root = Tk() def save(): open("text.txt","w").close() text = e.get() + "\n" + e1.get() + "\n" + e2.get() + "\n" with open("text.txt", "a") as f: f.write(text) w1 = Label(root, text="Controller value") w1.pack() e = Entry(root) e.pack() w2 = Label(root, text="Velocity") w2.pack() e1 = Entry(root) e1.pack() w3 = Label(root, text="Desired Heading") w3.pack() e2 = Entry(root) e2.pack() toolbar = Frame(root) b = Button(toolbar, text="save", width=9, command=save) b.pack(side=LEFT, padx=2, pady=2) toolbar.pack(side=TOP, fill=X) mainloop() </code></pre> <hr> <p>Now what I want to do is create 3 new textboxes in the GUI which will display the contents of the file. For example my <code>text.txt</code> file has the contents:</p> <pre><code>3 2 4 </code></pre> <p>Now I want each of these 3 values to be displayed in 3 textboxes in the GUI. Basically I want the first textbox in the GUI to display <code>3</code>, second textbox <code>2</code> and third textbox <code>4</code>. Help me out please.</p>
0
WebSockets on iOS
<p>I've read that WebSockets work on iOS 4.2 and above. And I can verify that there is indeed a WebSocket object. But I can't find a single working WebSocket example that works on the phone. </p> <p>For example <a href="http://yaws.hyber.org/websockets_example.yaws" rel="noreferrer">http://yaws.hyber.org/websockets_example.yaws</a> will crash the Mobile Safari app. Has anyone got WebSockets working successfully on the phone?</p>
0
How do I provide success messages asp.net mvc?
<p>How do I provide success messages in asp.net mvc?</p>
0
Show Dialog from ViewModel in Android MVVM Architecture
<p>About MVVM with new architecture components, I've a question, how should I implement if my app needs to display for example a Dialog with 3 options from some action that happened in my VM? Who is responsible for sending to Activity/Fragment the command to show dialog?</p>
0
Memory Efficient L2 norm using Python broadcasting
<p>I am trying to implement a way to cluster points in a test dataset based on their similarity to a sample dataset, using Euclidean distance. The test dataset has 500 points, each point is a N dimensional vector (N=1024). The training dataset has around 10000 points and each point is also a 1024- dim vector. The goal is to find the L2-distance between each test point and all the sample points to find the closest sample (without using any python distance functions). Since the test array and training array have different sizes, I tried using broadcasting:</p> <pre><code> import numpy as np dist = np.sqrt(np.sum( (test[:,np.newaxis] - train)**2, axis=2)) </code></pre> <p>where test is an array of shape (500,1024) and train is an array of shape (10000,1024). I am getting a MemoryError. However, the same code works for smaller arrays. For example:</p> <pre><code> test= np.array([[1,2],[3,4]]) train=np.array([[1,0],[0,1],[1,1]]) </code></pre> <p>Is there a more memory efficient way to do the above computation without loops? Based on the posts online, we can implement L2- norm using matrix multiplication sqrt(X * X-2*X * Y+Y * Y). So I tried the following:</p> <pre><code> x2 = np.dot(test, test.T) y2 = np.dot(train,train.T) xy = 2* np.dot(test,train.T) dist = np.sqrt(x2 - xy + y2) </code></pre> <p>Since the matrices have different shapes, when I tried to broadcast, there is a dimension mismatch and I am not sure what is the right way to broadcast (dont have much experience with Python broadcasting). I would like to know what is the right way to implement the L2 distance computation as a matrix multiplication in Python, where the matrices have different shapes. The resultant distance matrix should have dist[i,j] = Euclidean distance between test point i and sample point j.</p> <p>thanks</p>
0
Convert ES6 JavaScript to ES5 without transpiler
<p>I am not familiar with new JavaScript ES6 coding conventions and have been given some code where I need it to be plain old JavaScript ES5.</p> <p>I need to convert this JS code without the use of Babel or any other transpiler. I cannot use Babel as I am not allowed to use it at work. </p> <p>I realise that all the "const" can be converted to "var" but unsure of new arrow functions and other items. </p> <p>I have tried converting but getting:</p> <blockquote> <p>Uncaught ReferenceError: line is not defined</p> </blockquote> <p>The ES6 code that I would like converted to ES5 is:</p> <pre><code>const data = [{ "rec": "1", "region": "LEFT", "intrface": "Line-1" },{ "rec": "1", "region": "LEFT", "intrface": "Line-2" },{ "rec": "1", "region": "RIGHT", "intrface": "Line-3" },{ "rec": "1", "region": "RIGHT", "intrface": "Line-4" }]; const s = Snap("#svg"); const height = 40; const canvasWidth = 400; const lineWidth = 180; const rightOffset = canvasWidth/2 - lineWidth; const leftLines = data.filter((line) =&gt; !isRightLine(line)); const rightLines = data.filter(isRightLine); leftLines.forEach(drawLine); rightLines.forEach(drawLine); const numberOfLines = Math.max(leftLines.length, rightLines.length); const rectSize = 20; const rectangles = []; for (let i = 0; i &lt; numberOfLines; i++) { rectangles.push(drawRect(i)); } function drawLine(data, index) { const {intrface} = data; const isRight = isRightLine(data); const x = isRight ? canvasWidth/2 + rightOffset : 0; const y = height * (index + 1); const stroke = isRight ? 'red' : 'black'; const line = s.line(x, y, x + 180, y); line.attr({ stroke, strokeWidth: 1 }); const text = s.text(x + 10, y - 5, intrface); text.attr({ fill: stroke, cursor: 'pointer' }); text.click(() =&gt; { console.log('clicked', data); //window.location.href = "http://stackoverflow.com/"; }); } function isRightLine({region}) { return region === 'RIGHT'; } function drawRect(index) { const x = canvasWidth/2 - rectSize/2; const y = height * (index + 1) - rectSize/2; const rectangle = s.rect(x, y, rectSize, rectSize); rectangle.attr({ fill: 'black' }); console.log('rr', x, y); return rectangle; } </code></pre>
0
Configure Puppeteer executablePath chrome in your local Windows
<ul> <li>Puppeteer version : 1.11.0</li> <li>Platform / OS version: Windows 10 pro</li> <li>Node.js version: 12.6.6</li> </ul> <p>When I did a local development test in windows, happen was problem in executablePath. </p> <p>"Failed to launch chrome! spawn /usr/bin/chromium-browser ENOENT"</p> <p>I saw for windows needs to get complete path. Otherwise cannot find chrome.exe</p> <p>Default in code:</p> <pre><code>const browser = await puppeteer.launch({executablePath: '/path/to/Chrome'}); </code></pre> <p>In windows it worked thus:</p> <pre><code>const browser = await puppeteer.launch({executablePath: 'C:\\your_workspace\\node_modules\\puppeteer\\.local-chromium\\win64-(version)\\chrome-win\\chrome.exe'}); </code></pre> <p>In visual code suggest the path</p> <p><a href="https://i.stack.imgur.com/ocS1k.png" rel="nofollow noreferrer">Visual Code view explorer</a></p>
0
Where can I get the 10.6 SDK for XCode
<p>Where can I get the 10.6 SDK for XCode? I have the beta of Snow Leopard, and I installed XCode off of the DVD, but it only installed the 10.5 and 10.4 SDKs. I need to build against 10.6 to verify a bug for Apple.</p>
0
Converting a list of tuples into a dict
<p>I have a list of tuples like this:</p> <pre><code>[ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ] </code></pre> <p>I want to iterate through this keying by the first item, so, for example, I could print something like this:</p> <pre><code>a 1 2 3 b 1 2 c 1 </code></pre> <p>How would I go about doing this without keeping an item to track whether the first item is the same as I loop around the tuples? This feels rather messy (plus I have to sort the list to start with)...</p>
0
Fastest way to move files on a Windows System
<p>I want to <strong>move about 800gb of data from an NTFS storage device to a FAT32 device</strong> (both are external hard drives), on a Windows System.</p> <p>What is the best way to achieve this?</p> <ol> <li>Simply using cut-paste?</li> <li>Using the command prompt ? (<code>move</code>)</li> <li>Writing a batch file to copy a small chunks of data on a given interval ?</li> <li>Use some specific application that does the job for me?</li> <li>Or any better idea...?</li> </ol> <p>What is the most safe, efficient and fast way to achieve such a time consuming process?</p>
0
How do I find out if the GPS of an Android device is enabled
<p>On an Android Cupcake (1.5) enabled device, how do I check and activate the GPS?</p>
0
Calculating which tiles are lit in a tile-based game ("raytracing")
<p>I'm writing a little tile-based game, for which I'd like to support light sources. But my algorithm-fu is too weak, hence I come to you for help.</p> <p>The situation is like this: There is a tile-based map (held as a 2D array), containing a single light source and several items standing around. I want to calculate which tiles are lit up by the light source, and which are in shadow.</p> <p>A visual aid of what it would look like, approximately. The L is the light source, the Xs are items blocking the light, the 0s are lit tiles, and the -s are tiles in shadow.</p> <pre><code>0 0 0 0 0 0 - - 0 0 0 0 0 0 0 - 0 0 0 0 0 0 0 X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 L 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X X X X 0 0 0 0 0 - - - - - 0 0 0 - - - - - - - </code></pre> <p>A fractional system would be even better, of course, where a tile can be in half-shadow due to being partially obscured. The algorithm wouldn't have to be perfect - just not obviously wrong and reasonably fast.</p> <p>(Of course, there would be multiple light sources, but that's just a loop.)</p> <p>Any takers?</p>
0
Creating a byte array from a stream
<p>What is the prefered method for creating a byte array from an input stream? </p> <p>Here is my current solution with .NET 3.5. </p> <pre><code>Stream s; byte[] b; using (BinaryReader br = new BinaryReader(s)) { b = br.ReadBytes((int)s.Length); } </code></pre> <p>Is it still a better idea to read and write chunks of the stream?</p>
0
Accessing the index in 'for' loops
<p>How do I access the index while iterating over a sequence with a <code>for</code> loop?</p> <pre><code>xs = [8, 23, 45] for x in xs: print(&quot;item #{} = {}&quot;.format(index, x)) </code></pre> <p>Desired output:</p> <pre class="lang-none prettyprint-override"><code>item #1 = 8 item #2 = 23 item #3 = 45 </code></pre>
0
How to run tests in a playlist file from mstest command line
<p>Is there a way I can use the playlist file to run tests from commandline using MSTest.exe? I tried using following command line but it fails with and error -</p> <blockquote> <pre><code>mstest.exe /testmetadata:test.playlist </code></pre> </blockquote> <pre><code>The file 'test.playlist' has unknown format and cannot be converted to the current version. Note that mstest version is 11.0.50727.1 and I am using VS 2012 </code></pre> <p>my playlist file just contains couple of XML elements </p> <pre><code>&lt;Playlist Version="1.0"&gt; &lt;Add Test="MyTest" /&gt; &lt;Add Test="AnotherTest" /&gt; &lt;/Playlist&gt; </code></pre>
0
Convert UPPERCASE string to sentence case in Python
<p>How does one convert an uppercase string to proper sentence-case? Example string:</p> <pre><code>"OPERATOR FAIL TO PROPERLY REMOVE SOLID WASTE" </code></pre> <p>Using <code>titlecase(str)</code> gives me:</p> <pre><code>"Operator Fail to Properly Remove Solid Waste" </code></pre> <p>What I need is:</p> <pre><code>"Operator fail to properly remove solid waste" </code></pre> <p>Is there an easy way to do this?</p>
0
Segmentation fault in libcurl, multithreaded
<p>So I've got a bunch of worker threads doing simple curl class, each worker thread has his own curl easy handle. They are doing only HEAD lookups on random web sites. Also locking functions are present to enable multi threaded SSL as documented <a href="http://www.openssl.org/docs/crypto/threads.html" rel="noreferrer">here</a>. Everything is working except on 2 web pages ilsole24ore.com ( seen in example down ), and ninemsn.com.au/ , they sometimes produce seg fault as shown in trace output shown here</p> <pre><code> #0 *__GI___libc_res_nquery (statp=0xb4d12df4, name=0x849e9bd "ilsole24ore.com", class=1, type=1, answer=0xb4d0ca10 "", anslen=1024, answerp=0xb4d0d234, answerp2=0x0, nanswerp2=0x0, resplen2=0x0) at res_query.c:182 #1 0x00434e8b in __libc_res_nquerydomain (statp=0xb4d12df4, name=0xb4d0ca10 "", domain=0x0, class=1, type=1, answer=0xb4d0ca10 "", anslen=1024, answerp=0xb4d0d234, answerp2=0x0, nanswerp2=0x0, resplen2=0x0) at res_query.c:576 #2 0x004352b5 in *__GI___libc_res_nsearch (statp=0xb4d12df4, name=0x849e9bd "ilsole24ore.com", class=1, type=1, answer=0xb4d0ca10 "", anslen=1024, answerp=0xb4d0d234, answerp2=0x0, nanswerp2=0x0, resplen2=0x0) at res_query.c:377 #3 0x009c0bd6 in *__GI__nss_dns_gethostbyname3_r (name=0x849e9bd "ilsole24ore.com", af=2, result=0xb4d0d5fc, buffer=0xb4d0d300 "\177", buflen=512, errnop=0xb4d12b30, h_errnop=0xb4d0d614, ttlp=0x0, canonp=0x0) at nss_dns/dns-host.c:197 #4 0x009c0f2b in _nss_dns_gethostbyname2_r (name=0x849e9bd "ilsole24ore.com", af=2, result=0xb4d0d5fc, buffer=0xb4d0d300 "\177", buflen=512, errnop=0xb4d12b30, h_errnop=0xb4d0d614) at nss_dns/dns-host.c:251 #5 0x0079eacd in __gethostbyname2_r (name=0x849e9bd "ilsole24ore.com", af=2, resbuf=0xb4d0d5fc, buffer=0xb4d0d300 "\177", buflen=512, result=0xb4d0d618, h_errnop=0xb4d0d614) at ../nss/getXXbyYY_r.c:253 #6 0x00760010 in gaih_inet (name=&lt;value optimized out&gt;, service=&lt;value optimized out&gt;, req=0xb4d0f83c, pai=0xb4d0d764, naddrs=0xb4d0d754) at ../sysdeps/posix/getaddrinfo.c:531 #7 0x00761a65 in *__GI_getaddrinfo (name=0x849e9bd "ilsole24ore.com", service=0x0, hints=0xb4d0f83c, pai=0xb4d0f860) at ../sysdeps/posix/getaddrinfo.c:2160 #8 0x00917f9a in ?? () from /usr/lib/libkrb5support.so.0 #9 0x003b2f45 in krb5_sname_to_principal () from /usr/lib/libkrb5.so.3 #10 0x0028a278 in ?? () from /usr/lib/libgssapi_krb5.so.2 #11 0x0027eff2 in ?? () from /usr/lib/libgssapi_krb5.so.2 #12 0x0027fb00 in gss_init_sec_context () from /usr/lib/libgssapi_krb5.so.2 #13 0x00d8770e in ?? () from /usr/lib/libcurl.so.4 #14 0x00d62c27 in ?? () from /usr/lib/libcurl.so.4 #15 0x00d7e25b in ?? () from /usr/lib/libcurl.so.4 #16 0x00d7e597 in ?? () from /usr/lib/libcurl.so.4 #17 0x00d7f133 in curl_easy_perform () from /usr/lib/libcurl.so.4 </code></pre> <p>My function looks something like this</p> <pre><code>int do_http_check(taskinfo *info,standardResult *data) { standardResultInit(data); char errorBuffer[CURL_ERROR_SIZE]; CURL *curl; CURLcode result; curl = curl_easy_init(); if(curl) { //required options first curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer); curl_easy_setopt(curl, CURLOPT_URL, info-&gt;address.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &amp;data-&gt;body); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, writer); curl_easy_setopt(curl, CURLOPT_WRITEHEADER, &amp;data-&gt;head); curl_easy_setopt(curl, CURLOPT_DNS_USE_GLOBAL_CACHE,0); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30 ); curl_easy_setopt(curl, CURLOPT_NOSIGNAL,1); curl_easy_setopt(curl, CURLOPT_NOBODY,1); curl_easy_setopt(curl, CURLOPT_TIMEOUT ,240); //optional options if(info-&gt;options.follow) { curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_MAXREDIRS, info-&gt;options.redirects); } result = curl_easy_perform(curl); if (result == CURLE_OK) { data-&gt;success = true; curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE,&amp;data-&gt;httpMsg); curl_easy_getinfo(curl,CURLINFO_REDIRECT_COUNT,&amp;data-&gt;numRedirects); data-&gt;msg = "OK"; } else { ... handle error } return 1; } </code></pre> <p>Now, when i call function without any threads, just calling it from main it never breaks, so I was thinking its connected to threads, or maybe how data return structure is being returned, but from what I saw in trace it looks like fault is generated in easy_perform() call, and its confusing me. So if someone has any idea where should i look next it would be most helpful, thanks. </p>
0
What are Google Test, Death Tests
<p>I saw the documentation of that feature is seem pretty major since it's in Google Test overview features and detailed in:<br /> <a href="https://github.com/google/googletest/blob/master/docs/advanced.md#death-tests" rel="nofollow noreferrer">https://github.com/google/googletest/blob/master/docs/advanced.md#death-tests</a></p> <p>They look like standard <code>assert()</code> but they're part of Google Test, so a xUnit testing framework. Therefore, I wonder what the real usage <em>or advantage</em> of using those <strong>death tests</strong> are.</p>
0
Getting an Image object from a byte array
<p>I've got a byte array for an image (stored in the database). I want to create an Image object, create several Images of different sizes and store them back in the database (save it back to a byte array).</p> <p>I'm not worried about the database part, or the resizing. But is there an easy way to load an Image object without saving the file to the file system, and then put it back in a byte array when I'm done resizing it? I'd like to do it all in memory if I can.</p> <pre><code>Something like: Image myImage = new Image(byte[]); or myImage.Load(byte[]); </code></pre>
0
checked and unchecked exception in .NET
<p>a strange idea comes to me when I'm reading APUE(Advanced Programming in UNIX Environment).</p> <p>It seems that in UNIX's error handling, there are two types of errors (FATAL &amp; INFATAL). I feel like it's something related to checked and unchecked Exceptions in JAVA.</p> <p>So, to sum up, in a program, you have two kinds of errors, one of them is critical and will make system crash and you can do nothing about it. Another one is more like a signal that you can catch and do something to fix it. </p> <p>I heard that in C# there is no checked and unchecked exception, so does C# not have a concept of critical and uncritical errors? Just got very curious because i think this concept is very fundamental.</p> <p>Update: What is the exception design in other languages? Can anyone talk about this?</p>
0
Rails assign session variable
<p>Hi I'm hacking around Rails the last 8 months so don't truly understand a number of things. I've seen and used helper methods that set the current_user etc. and am now trying to replicate something similar. </p> <p>I'm trying to set a global value in the application controller for the current company the user is in. I know I'm doing it wrong but I can't quite figure out how to solve it or even if I'm approaching it correctly. I want it so that when the user clicks on a company, the global variable is set to the id of the company they are in. Then in any other sub-model, if I want info on the company, I use the global variable to retrieve the company object with that id.</p> <p>The code that's causing the problem is in my navbar in <strong>application.html.erb</strong></p> <pre><code>&lt;li&gt;&lt;%= link_to "Company", company_path, :method =&gt; :get %&gt;&lt;/li&gt; </code></pre> <p>This works when I'm using the companies controller etc. But when I try use any other controller I'm getting the error</p> <blockquote> <p>ActionController::UrlGenerationError in Employees#index</p> </blockquote> <pre><code>No route matches {:action=&gt;"show", :controller=&gt;"companies"} missing required keys: [:id] </code></pre> <p>which as I understand it means it can't render the url because no company id parameter is being passed?</p> <p>I was trying to hack a helper method I used in another project (for getting the current_user) but have realised that it uses the session to extract the user.id to return a user object. Here's my attempt at the helper method in <strong>application_controller.rb</strong></p> <pre><code>def current_company @company = Company.find_by_id(params[:id]) end </code></pre> <p>I'm not able to get the current company from the session so my method above is useless unless the company id is being passed as a parameter.</p> <p>I've thought about passing the company id on every sub-model method but </p> <ol> <li>I'm not 100% sure how to do this</li> <li>It doesn't sound very efficient</li> </ol> <p>So my question is am I approaching this correctly? What's the optimal way to do it? Can I create a helper method that stores a global company id variable that gets set once a user accesses a company and can then be retrieved by other models? </p> <p>I probably haven't explained it too well so let me know if you need clarification or more info. Thanks for looking. </p> <blockquote> <p><strong><em>Edit 1</em></strong></p> </blockquote> <p>Made the changes suggested by Ruby Racer and now I have:</p> <blockquote> <p><strong>application.html.erb</strong></p> </blockquote> <pre><code> &lt;%unless current_page?(root_path)||current_page?(companies_path)||current_company.nil? %&gt; &lt;li&gt;&lt;%= link_to "Company", company_path, :method =&gt; :get %&gt;&lt;/li&gt; </code></pre> <p>This is not displaying the link in the navbar, I presume because current_company is nil (the other two unless statements were fine before I added current_company.nil?</p> <p>I'm setting the current_company in </p> <blockquote> <p><strong>companies_controller.rb</strong></p> </blockquote> <pre><code>before_action :set_company, only: [:show, :edit, :update, :destroy, :company_home] def company_home current_company = @company respond_with(@company) end </code></pre> <blockquote> <p><strong>application_controller.rb</strong></p> </blockquote> <pre><code>def current_company=(company) session[:current_company] = company.id puts "The current_company has been assigned" puts params.inspect end def current_company @company = Company.find_by_id(session[:current_company]) puts "The current_company helper has been called" puts @company puts params.inspect end </code></pre> <p>Am I doing something wrong? </p> <blockquote> <p><strong><em>Edit 2</em></strong></p> </blockquote> <p>I have no idea why this isn't working. After the above edits, it appears as though the <code>session[:company_id]</code> is not being assigned so the <code>current_company</code> helper method is returning nil. I've tried printing the session paramaters <code>puts session.inspect</code> and can't find any company_id information. Anyone any idea why it isn't assigning the value? </p> <blockquote> <p><strong>Edit 3</strong></p> </blockquote> <p>Can't for the life of me figure out what's going wrong. I've tried multiple things including moving the <code>current_company = @company</code> into the <code>set_company</code> method in <strong><code>companies_controller.rb</code></strong> which now looks like this:</p> <pre><code>def company_home puts "Test the current company" puts "#{@company.id} #{@company.name}" puts params.inspect end private def set_company @company = Company.find_by_id(params[:id]) if @company.nil?||current_user.organisation_id != @company.organisation.id flash[:alert] = "Stop poking around you nosey parker" redirect_to root_path else current_company = @company end end </code></pre> <p>The <code>company_home</code> method is being given a company object (I can see this in the console output below) but the <code>current_company</code> assignment is just not happening. Here's the <strong>console output</strong> for reference</p> <pre><code>Started GET "/company_home/1" for 80.55.210.105 at 2014-12-19 10:26:49 +0000 Processing by CompaniesController#company_home as HTML Parameters: {"authenticity_token"=&gt;"gfdhjfgjhoFFHGHGFHJGhjkdgkhjgdjhHGLKJGJHpDQs6yNjONwSyTrdgjhgdjgjf=", "id"=&gt;"1"} User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = 6 ORDER BY "users"."id" ASC LIMIT 1 Company Load (0.3ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" = 1 LIMIT 1 Organisation Load (0.3ms) SELECT "organisations".* FROM "organisations" WHERE "organisations"."id" = $1 LIMIT 1 [["id", 6]] Test the current company 1 Cine {"_method"=&gt;"get", "authenticity_token"=&gt;"gfdhjfgjhoFFHGHGFHJGhjkdgkhjgdjhHGLKJGJHpDQs6yNjONwSyTrdgjhgdjgjf=", "controller"=&gt;"companies", "action"=&gt;"company_home", "id"=&gt;"1"} Rendered companies/company_home.html.erb within layouts/application (0.1ms) Company Load (0.6ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" IS NULL LIMIT 1 The current_company helper has been called {"_method"=&gt;"get", "authenticity_token"=&gt;"gfdhjfgjhoFFHGHGFHJGhjkdgkhjgdjhHGLKJGJHpDQs6yNjONwSyTrdgjhgdjgjf=", "controller"=&gt;"companies", "action"=&gt;"company_home", "id"=&gt;"1"} CACHE (0.0ms) SELECT "organisations".* FROM "organisations" WHERE "organisations"."id" = $1 LIMIT 1 [["id", 6]] Completed 200 OK in 280ms (Views: 274.0ms | ActiveRecord: 1.7ms) </code></pre> <p>As per above, under the line <code>The current_company helper has been called</code>, there's a blank line where <code>puts @company</code> should be outputting something. This means the current_company method is returning nothing.</p> <p>Also, in the <code>company_home</code> method in the companies_controller, if I change <code>puts "#{@company.id} #{@company.name}"</code> to <code>puts "#{current_company.id} #{current_company.name}"</code> an error gets thrown.</p> <p>Has anyone any idea why the <code>def current_company=(company)</code> isn't assigning a session parameter? Thanks</p> <blockquote> <p><strong>Final Edit</strong></p> </blockquote> <p>I've no idea why, but it appears the problem related to this:</p> <pre><code>def current_company=(company) session[:current_company] = company.id puts "The current_company has been assigned" puts params.inspect end </code></pre> <p>It looks as though this never gets called. I don't understand why as I've never used something like this before.</p> <p>I'll put my fix in an answer.</p>
0
R: find the number of common elements of two lists
<p>Let's say I have these two lists, and I want to figure out the number of column elements among these two lists:</p> <pre><code>&gt; xl [[1]] [1] 1 2 3 4 5 &gt; yl [[1]] [1] 4 3 5 6 7 </code></pre> <p>So, in this example, the answer would be 3. Any suggestions?</p>
0
eclipse android emulator not starting
<p>I have some problems with my emulator in eclipse. When I create an AVD and start it, the emulator is running and showing the "Android" logo/text, but never moves on from there.</p> <p>Should I set some specific settings when I create a new AVD to make it run faster? Any suggestions will be greatly appreciated</p>
0
Check whether an array exists in an array of arrays?
<p>I'm using JavaScript, and would like to check whether an array exists in an array of arrays. </p> <p>Here is my code, along with the return values: </p> <pre><code>var myArr = [1,3]; var prizes = [[1,3],[1,4]]; prizes.indexOf(myArr); -1 </code></pre> <p>Why? </p> <p>It's the same in jQuery: </p> <pre><code>$.inArray(myArr, prizes); -1 </code></pre> <p>Why is this returning -1 when the element is present in the array?</p>
0
How to detect when UINavigationController animation has finished?
<p>I hope this is a simple question. If I have a UINavigationController and I push a new view controller onto the stack with an animated transition, how can I detect when the animation has finished and the new view controller is on screen? </p> <p>I have a few scenarios where I need to push a new controller that then has to do a long-running operation. I'd like to push the new view first so there's something on screen before I start blocking the main thread for a long time. If I do the push immediately followed by my long-running task the view won't show up until after both are done of course and the main thread is able to process events again. </p> <p>So, what I'd like to do be able to detect in the new controller once the animation is done and the view is on screen, and then start the task. </p>
0
<--- and <-> in pseudocode
<p>I am not from cs background and I am trying to make sense of what is used for what. In pseudocode I see a lot of this:</p> <pre><code>for i &lt;--- 1 to n-1 do j &lt;--- find-Min(A,i,n) A[j] &lt;-&gt; A[i] end for </code></pre> <p>What are <code>&lt;---</code> and <code>&lt;-&gt;</code> used to refer to?</p>
0
HTTP HEAD request with HttpClient in .NET 4.5 and C#
<p>Is it possible to create a HTTP HEAD request with the new <code>HttpClient</code> in .NET 4.5? The only methods I can find are <code>GetAsync</code>, <code>DeleteAsync</code>, <code>PutAsync</code> and <code>PostAsync</code>. I know that the <code>HttpWebRequest</code>-class is able to do that, but I want to use the modern <code>HttpClient</code>.</p>
0
Cleanest way to convert a `Double` or `Single` to `Integer`, without rounding
<p>Converting a floating-point number to an integer using either <a href="https://msdn.microsoft.com/en-us/library/s2dy91zy.aspx" rel="nofollow noreferrer">CInt</a> or <code>CType</code> will cause the value of that number to be rounded. The <code>Int</code> function and <code>Math.Floor</code> may be used to convert a floating-point number to a whole number, rounding toward negative infinity, but both functions return floating-point values which cannot be implicitly used as <code>Integer</code> values without a cast.</p> <p>Is there a concise and idiomatic alternative to <code>IntVar = CInt(Int(FloatingPointVar));</code>? Pascal included <code>Round</code> and <code>Trunc</code> functions which returned <code>Integer</code>; is there some equivalent in either the VB.NET language or in the .NET framework?</p> <p>A similar question, <em><a href="https://stackoverflow.com/questions/7684176">CInt does not round Double value consistently - how can I remove the fractional part?</a></em> was asked in 2011, but it simply asked if there was a way to convert a floating-point number to an integer; the answers suggested a two-step process, but it didn't go into any depth about what does or does not exist in the framework. I would find it hard to believe that the Framework wouldn't have something analogous to the <a href="http://en.wikipedia.org/wiki/Pascal_%28programming_language%29" rel="nofollow noreferrer">Pascal</a> <code>Trunc</code> function, given that such a thing will frequently be needed when performing graphical operations using floating-point operands [such operations need to be rendered as discrete pixels, and should be rounded in such a way that round(x)-1 = round(x-1) for all x that fit within the range of +/- (2^31-1); even if such operations are rounded, they should use Floor(x+0.5), rather than round-to-nearest-even, so as to ensure the above property]</p> <p>Incidentally, in C# a typecast from <code>Double</code> to <code>Int</code> using <code>(type)expr</code> notation uses round-to-zero semantics; the fact that this differs from the VB.NET behavior suggests that one or both languages is using its own conversion routines rather an explicit conversion operator included in the Framework. It would seem likely that the Framework should define a conversion operator? Does such an operator exist within the framework? What does it do? Is there a way to invoke it from C# and/or VB.NET?</p>
0
How to extract phrases from corpus using gensim
<p>For preprocessing the corpus I was planing to extarct common phrases from the corpus, for this I tried using <strong>Phrases</strong> model in gensim, I tried below code but it's not giving me desired output.</p> <p><strong>My code</strong></p> <pre><code>from gensim.models import Phrases documents = ["the mayor of new york was there", "machine learning can be useful sometimes"] sentence_stream = [doc.split(" ") for doc in documents] bigram = Phrases(sentence_stream) sent = [u'the', u'mayor', u'of', u'new', u'york', u'was', u'there'] print(bigram[sent]) </code></pre> <p><strong>Output</strong></p> <pre><code>[u'the', u'mayor', u'of', u'new', u'york', u'was', u'there'] </code></pre> <p><strong>But it should come as</strong> </p> <pre><code>[u'the', u'mayor', u'of', u'new_york', u'was', u'there'] </code></pre> <p>But when I tried to print vocab of train data, I can see bigram, but its not working with test data, where I am going wrong?</p> <pre><code>print bigram.vocab defaultdict(&lt;type 'int'&gt;, {'useful': 1, 'was_there': 1, 'learning_can': 1, 'learning': 1, 'of_new': 1, 'can_be': 1, 'mayor': 1, 'there': 1, 'machine': 1, 'new': 1, 'was': 1, 'useful_sometimes': 1, 'be': 1, 'mayor_of': 1, 'york_was': 1, 'york': 1, 'machine_learning': 1, 'the_mayor': 1, 'new_york': 1, 'of': 1, 'sometimes': 1, 'can': 1, 'be_useful': 1, 'the': 1}) </code></pre>
0
Vue.js: Calling function on change
<p>I'm building a component in Vue.js. I have an input on the page where the user can request a certain credit amount. Currently, I'm trying to make a function that will log the input amount to the console, as I type it in. (Eventually, I'm going to show/hide the requested documents based on the user input. I don't want them to have to click a submit button.)</p> <p>The code below logs it when I tab/click out of the input field. Here's my component.vue:</p> <pre><code>&lt;template&gt; &lt;div class="col s12 m4"&gt; &lt;div class="card large"&gt; &lt;div class="card-content"&gt; &lt;span class="card-title"&gt;Credit Limit Request&lt;/span&gt; &lt;form action=""&gt; &lt;div class="input-field"&gt; &lt;input v-model="creditLimit" v-on:change="logCreditLimit" id="credit-limit-input" type="text"&gt; &lt;label for="credit-limit-input"&gt;Credit Limit Amount&lt;/label&gt; &lt;/div&gt; &lt;/form&gt; &lt;p&gt;1. If requesting $50,000 or more, please attach Current Balance Sheet (less than 1 yr old).&lt;/p&gt; &lt;p&gt;2. If requesting $250,000 or more, also attach Current Income Statement and Latest Income Tax Return.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { name: 'licenserow', data: () =&gt; ({ creditLimit: "" }), methods: { logCreditLimit: function (){ console.log(this.creditLimit) } } } &lt;/script&gt; </code></pre> <p>If I change <code>methods</code> to <code>computed</code>, it works - but I get an error saying <code>Invalid handler for event: change</code> every time it logs the value.</p>
0
Apple Mach-O-Linker Error CocoaPods
<p>I've been trying to get my app up and running. From what I could tell the app was missing Cocoapods as a dependency. So. I installed and added Cocoapods. But I'm still getting the same error for whatever reason. I'm an inexperienced developer trying to teach himself I must add. </p> <blockquote> <p>Ld /Users/bfarag/Library/Developer/Xcode/DerivedData/Umbrella-cspuzusfqmqgnwdqfhtiyivaqwke/Build/Products/Debug-iphonesimulator/Umbrella.app/Umbrella normal i386 cd "/Users/bfarag/Desktop/The Nerdery/BRAVO.iOS.CodeChallenge" export IPHONEOS_DEPLOYMENT_TARGET=7.0 export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin" /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch i386 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.1.sdk -L/Users/bfarag/Library/Developer/Xcode/DerivedData/Umbrella-cspuzusfqmqgnwdqfhtiyivaqwke/Build/Products/Debug-iphonesimulator -F/Users/bfarag/Library/Developer/Xcode/DerivedData/Umbrella-cspuzusfqmqgnwdqfhtiyivaqwke/Build/Products/Debug-iphonesimulator -filelist /Users/bfarag/Library/Developer/Xcode/DerivedData/Umbrella-cspuzusfqmqgnwdqfhtiyivaqwke/Build/Intermediates/Umbrella.build/Debug-iphonesimulator/Umbrella.build/Objects-normal/i386/Umbrella.LinkFileList -Xlinker -objc_abi_version -Xlinker 2 -ObjC -lPods-Umbrella-AFNetworking -framework CoreGraphics -framework MobileCoreServices -framework Security -framework SystemConfiguration -fobjc-arc -fobjc-link-runtime -Xlinker -no_implicit_dylibs -mios-simulator-version-min=7.0 -framework Accelerate -framework UIKit -framework Foundation -framework CoreGraphics -lPods -lPods-Umbrella -Xlinker -dependency_info -Xlinker /Users/bfarag/Library/Developer/Xcode/DerivedData/Umbrella-cspuzusfqmqgnwdqfhtiyivaqwke/Build/Intermediates/Umbrella.build/Debug-iphonesimulator/Umbrella.build/Objects-normal/i386/Umbrella_dependency_info.dat -o /Users/bfarag/Library/Developer/Xcode/DerivedData/Umbrella-cspuzusfqmqgnwdqfhtiyivaqwke/Build/Products/Debug-iphonesimulator/Umbrella.app/Umbrella</p> </blockquote> <pre><code>ld: library not found for -lPods clang: error: linker command failed with exit code 1 (use -v to see invocation) </code></pre> <p><img src="https://i.stack.imgur.com/BVzXg.jpg" alt="Linker Flags"></p>
0
How to delay KeyPress function when user is typing, so it doesn't fire a request for each keystroke?
<p><strong>background</strong></p> <p>I have a number of dropdowns on a page. If you change the first one, the rest of the dropdowns are updated according to what you've selected.</p> <p>In our case, we deal with fund data. So the first dropdown is "All Fund Types". You select "Hedge Funds", and the next dropdown is filtered by options that only apply to Hedge Funds.</p> <p>The client is now asking me to put a text field into the mix, which when the user starts typing, will effect those results.</p> <p>So if they type "USD", the second dropdown will only contain options that have funds with "USD" in the name.</p> <p><strong>problem</strong></p> <p>The specific problem that I'm having is that with the code I'm using:</p> <pre><code>$('#Search').keypress(function () { // trigger the updating process }); </code></pre> <p>It's triggering the search for each key press. So when I type "USD" I'm getting 3 requests immediately - one for "U", one for "US" and one for "USD".</p> <p>I've tried setting a timeout with this:</p> <pre><code>$('#Search').keypress(function () { // I figure 2 seconds is enough to type something meaningful setTimeout(getFilteredResultCount(), 2000); }); </code></pre> <p>but all that does is wait 2 seconds before doing what I've described.</p> <p>I'm sure this problem has been solved before. Could somebody suggest how to solve this issue? </p>
0
Why eslint consider JSX or some react @types undefined, since upgrade typescript-eslint/parser to version 4.0.0
<p>The context is pretty big project built with ReactJs, based on eslint rules, with this eslint configuration</p> <pre><code>const DONT_WARN_CI = process.env.NODE_ENV === 'production' ? 0 : 1 module.exports = { extends: [ 'eslint:recommended', 'plugin:jsx-a11y/recommended', 'plugin:react/recommended', 'prettier', 'prettier/@typescript-eslint' ], plugins: [ 'react', 'html', 'json', 'prettier', 'import', 'jsx-a11y', 'jest', '@typescript-eslint', 'cypress' ], settings: { 'html/indent': '0', es6: true, react: { version: '16.5' }, propWrapperFunctions: ['forbidExtraProps'], 'import/resolver': { node: { extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'] }, alias: { extensions: ['.js', '.jsx', '.json'] } } }, env: { browser: true, node: true, es6: true, jest: true, 'cypress/globals': true }, globals: { React: true, google: true, mount: true, mountWithRouter: true, shallow: true, shallowWithRouter: true, context: true, expect: true, jsdom: true }, parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 'es2020', ecmaFeatures: { globalReturn: true, jsx: true }, lib: ['ES2020'] }, rules: { 'arrow-parens': ['error', 'as-needed'], 'comma-dangle': ['error', 'never'], eqeqeq: ['error', 'smart'], 'import/first': 0, 'import/named': 'error', 'import/no-deprecated': process.env.NODE_ENV === 'production' ? 0 : 1, 'import/no-unresolved': ['error', { commonjs: true }], 'jsx-a11y/alt-text': DONT_WARN_CI, 'jsx-a11y/anchor-has-content': DONT_WARN_CI, 'jsx-a11y/anchor-is-valid': DONT_WARN_CI, 'jsx-a11y/click-events-have-key-events': DONT_WARN_CI, 'jsx-a11y/heading-has-content': DONT_WARN_CI, 'jsx-a11y/iframe-has-title': DONT_WARN_CI, 'jsx-a11y/label-has-associated-control': [ 'error', { controlComponents: ['select'] } ], 'jsx-a11y/label-has-for': [ 'error', { required: { some: ['nesting', 'id'] } } ], 'jsx-a11y/media-has-caption': DONT_WARN_CI, 'jsx-a11y/mouse-events-have-key-events': DONT_WARN_CI, 'jsx-a11y/no-autofocus': DONT_WARN_CI, 'jsx-a11y/no-onchange': 0, 'jsx-a11y/no-noninteractive-element-interactions': DONT_WARN_CI, 'jsx-a11y/no-static-element-interactions': DONT_WARN_CI, 'jsx-a11y/no-noninteractive-tabindex': DONT_WARN_CI, 'jsx-a11y/tabindex-no-positive': DONT_WARN_CI, 'no-console': 'warn', 'no-debugger': 'warn', 'no-mixed-operators': 0, 'no-redeclare': 'off', 'no-restricted-globals': [ 'error', 'addEventListener', 'blur', 'close', 'closed', 'confirm', 'defaultStatus', 'defaultstatus', 'event', 'external', 'find', 'focus', 'frameElement', 'frames', 'history', 'innerHeight', 'innerWidth', 'length', 'localStorage', 'location', 'locationbar', 'menubar', 'moveBy', 'moveTo', 'name', 'onblur', 'onerror', 'onfocus', 'onload', 'onresize', 'onunload', 'open', 'opener', 'opera', 'outerHeight', 'outerWidth', 'pageXOffset', 'pageYOffset', 'parent', 'print', 'removeEventListener', 'resizeBy', 'resizeTo', 'screen', 'screenLeft', 'screenTop', 'screenX', 'screenY', 'scroll', 'scrollbars', 'scrollBy', 'scrollTo', 'scrollX', 'scrollY', 'self', 'status', 'statusbar', 'stop', 'toolbar', 'top' ], 'no-restricted-modules': ['error', 'chai'], 'no-unused-vars': [ 'error', { varsIgnorePattern: '^_', argsIgnorePattern: '^_' } ], 'no-var': 'error', 'one-var': ['error', { initialized: 'never' }], 'prefer-const': [ 'error', { destructuring: 'any' } ], 'prettier/prettier': 'error', 'react/jsx-curly-brace-presence': [ 'error', { children: 'ignore', props: 'never' } ], 'react/jsx-no-bind': [ 'error', { allowArrowFunctions: true } ], 'react/jsx-no-literals': 1, 'react/jsx-no-target-blank': DONT_WARN_CI, 'react/jsx-no-undef': ['error', { allowGlobals: true }], 'react/no-deprecated': DONT_WARN_CI, 'react/prop-types': 0, 'require-await': 'error', 'space-before-function-paren': 0 }, overrides: [ { files: ['**/*.ts', '**/*.tsx'], rules: { 'no-unused-vars': 'off', 'import/no-unresolved': 'off' } } ] } </code></pre> <p>Since the upgrade of the library <code>&quot;@typescript-eslint/parser&quot;: &quot;^4.0.0&quot;</code> from <code>&quot;@typescript-eslint/parser&quot;: &quot;^3.10.1&quot;</code> this following command ...</p> <pre><code>eslint --fix --ext .js,.jsx,.json,.ts,.tsx . &amp;&amp; stylelint --fix '**/*.scss' </code></pre> <p>... brings these following errors</p> <pre><code> 9:45 error 'ScrollBehavior' is not defined no-undef 224:12 error 'KeyboardEventInit' is not defined no-undef 53:5 error 'JSX' is not defined no-undef </code></pre> <p>I know I could fix them adding to the prop <code>globals</code> also the keys <code>JSX: true</code> or <code>KeyboardEventInit: true</code> but it is not the way I want to go. Any ideas of what is going on here? Where is the configuration error? Thanks a lot</p>
0
How to center a width unknown button in a bootstrap's span?
<p>I have a button generated by backbone.js and jQuery.tmpl() and width of the button is variant. I want to put it in a span6 div. Code is shown below:</p> <pre><code>&lt;div class="row"&gt; &lt;div class="span6"&gt; &lt;button class="btn primary large"&gt; BLABLABLA &lt;/button&gt; &lt;/div&gt; &lt;div class="span10"&gt; ... &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I don't know how to make the button centered in the div.</p>
0
Calculate the difference between two dates in React Native
<p>I need to calculate the difference between two dates in days </p> <p>i bring today date: new Date().toJSON().slice(0, 10) = 2019-04-17 and the other date in the same form </p>
0
Angular2 - Parse JSON into an Object
<p>Example: I have a Entity-Class named "Person"</p> <pre><code>constructor(name:string,surname:string,birthdate:string) { this.name = name; this.surname = surname; this.birthdate = birthdate; } </code></pre> <p>And in a "Manager"-Class I get a string that looks like a JSON:</p> <pre><code>{ "name" : "testName", "surname" : "testSurrname", "birthdate" : "JJJJ:MM:DD hh:mm:ss" } </code></pre> <p>So how to parse the JSON into a "Person" </p> <pre><code>personData : Person; jsonData : JSON; public toPerson(data: string): Person { this.jsonData = JSON.parse(data); .? .? .? personData = new Person(....); return personData; } </code></pre>
0
View a file's history in Magit?
<p><a href="https://stackoverflow.com/questions/278192/view-the-change-history-of-a-file-using-git-versioning">View the change history of a file using Git versioning</a> talks about other ways of viewing history of a file in Git.</p> <p>Can it be done in Emacs Magit? </p>
0
C++ Inner class not able to access Outer class's members
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/486099/can-inner-classes-access-private-variables">Can inner classes access private variables?</a><br> <a href="https://stackoverflow.com/questions/11405069/inner-class-accessing-outer-class">Inner class accessing outer class</a> </p> </blockquote> <p>I have some simple classes nested so they can interact with a variable without extra inputs, yet my compiler gives me an error. How would I allow for them to interact without using &amp;time as function input or having the variable &amp;time inside of the Vect class?</p> <p>I tried using the same logic where you can have data accessed that is just in the code, at the same place as function prototypes, but is instead wrapped in a class. This works fine for anything I've used except other classes. Can anyone explain why?</p> <p>I have marked the places that use the problematic time variable with comment lines like the one before the define.</p> <pre><code>/*********/ #define MAX_POLY 3 class Container { public: Container(void); ~Container(void); float time;/*********/ class Vect { float P[MAX_POLY],iT; public: Vect(void){iT = 0.0f;P = {0,0,0};} ~Vect(void); float GetPoly(int n){return P[n];} float Render(void) { float t = time - iT;/*********/ float temp[2] = {0,0}; for(int n=0;n&lt;MAX_POLY;n++) { temp[0] = P[n]; for(int m=0;m&lt;n;m++) temp[0] *= t; temp[1] += temp[0]; } return temp[1]; } void SetPoly(int n,float f) { float t = time-iT;/*********/ P[0] = P[2]*t*t + P[1]*t + P[0]; P[1] = 2*P[2]*t + P[1]; //P[2] = P[2]; P[n] = f; iT = time;/*********/ } }X; }; int main() { Container Shell; Shell.X.SetPoly(0,5); Shell.X.SetPoly(1,10); Shell.X.SetPoly(2,-1); for(int n=0;n&lt;10;n++) { Shell.time = (float)n; cout &lt;&lt; n &lt;&lt; " " &lt;&lt; Shell.X.Render() &lt;&lt; endl; } system("pause"); return 0; } </code></pre>
0
PHP email encryption
<p>I have a website with an SSL.</p> <p>I would like to encrypt outgoing emails from my server. I've been digging around at this and I really don't know where to begin.</p> <p>Here is my PHP email script so you have an idea of what I'm using:</p> <pre><code>public function email($to, $title, $message){ $from = "[email protected]"; $headers = "From: {$from}\r\n"; $headers .= "X-Confirm-Reading-To: {$from}\r\n"; $headers .= "Reply-To: {$from}\r\n"; $headers .= "Organization: InfiniSys, inc.\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=ISO-8859-1\r\n"; $headers .= "X-Priority: 3\r\n"; $headers .= "X-Mailer: PHP". phpversion() ."\r\n"; $subject = $title; mail($to, $subject, $message, $headers); } </code></pre> <p>Ubuntu 14.04</p> <p>I'm not sure if this is a server setting or programming config.</p> <p>Very interesting post: (can't remember where I got it)</p> <pre><code>&lt;?php // Setup mail headers. $headers = array("From" =&gt; "[email protected]", "To" =&gt; "[email protected]", "Cc" =&gt; "[email protected]", "Subject" =&gt; "Encrypted mail readable with most clients", "X-Mailer" =&gt; "PHP/".phpversion() ); // Get the public key certificate. $pubkey = file_get_contents("C:\test.cer"); // Remove some double headers for mail() $headers_msg = $headers; unset($headers_msg['To'], $headers_msg['Subject']); $data = &lt;&lt; This email is Encrypted! You must have my certificate to view this email! Me EOD; //write msg to disk $fp = fopen("C:\msg.txt", "w"); fwrite($fp, $data); fclose($fp); // Encrypt message openssl_pkcs7_encrypt("C:\msg.txt","C:\enc.txt",$pubkey,$headers_msg,PKCS7_TEXT,1); // Seperate headers and body for mail() $data = file_get_contents("C:\enc.txt"); $parts = explode("\n\n", $data, 2); // Send mail mail($headers['To'], $headers['Subject'], $parts[1], $parts[0]); // Remove encrypted message (not fot debugging) //unlink("C:\msg.txt"); //unlink("C:\enc.txt"); ?&gt; </code></pre>
0
How do you get errors in the ModelState, for a particular property?
<p>I'm encountering the following issue: <a href="https://github.com/aspnet/Mvc/issues/4989" rel="noreferrer">https://github.com/aspnet/Mvc/issues/4989</a>, and based on 'rsheptolut' comment on Sep 12, 2016, he found this workaround (pasted for convenience):</p> <pre><code>&lt;form class="form-horizontal" asp-antiforgery="true"&gt; &lt;fieldset&gt; // All of this instead of @Html.ValidationSummary(false) due to a bug in ASP.NET Core 1.0 @if ([email protected]) { var errors = ViewData.ModelState.Values.Select(item =&gt; item.Errors.FirstOrDefault()?.ErrorMessage).Where(item =&gt; item != null); &lt;div class="alert alert-danger"&gt; &lt;span&gt;@Localizer["There are problems with your input:"]&lt;/span&gt; &lt;ul&gt; @foreach (var error in errors) { &lt;li&gt;@error&lt;/li&gt; } &lt;/ul&gt; &lt;/div&gt; } // Some actual fields. Don't forget validation messages for fields if you need them (@Html.ValidationMessage) &lt;/fieldset&gt; &lt;/form&gt; </code></pre> <p>My issue is with the LINQ to get the <code>errors</code> variable. I want to filter these by the name of the property, so the list of errors listed under my file uploads element will not contain errors from other elements on the page. I want to do something like this: </p> <pre><code>ViewData.ModelState.Values.Where(item =&gt; item.Key == "Images").Select...; </code></pre> <p>However, LINQ doesn't find Key as a valid property of the ModelStateEntry class. Fair enough. But why then, when add a quick watch to <code>ViewData.ModelState.Values</code>, does the Key property show up?</p>
0
How to propagate errors through catchError() properly?
<p>I wrote a function that is <code>pipe</code>-able:</p> <pre class="lang-ts prettyprint-override"><code>HandleHttpBasicError&lt;T&gt;() { return ((source:Observable&lt;T&gt;) =&gt; { return source.pipe( catchError((err:any) =&gt; { let msg = ''; if(err &amp;&amp; err instanceof HttpErrorResponse) { if(err.status == 0) msg += &quot;The server didn't respond&quot;; } throw { err, msg } as CustomError }) ) }) } </code></pre> <p>I can use this function this way in my <code>HttpService</code>:</p> <pre class="lang-ts prettyprint-override"><code>checkExist(id:string) { return this.http.head&lt;void&gt;(environment.apiUrl + 'some_url/' + id) .pipe( HandleHttpBasicError(), catchError((err:CustomError) =&gt; { if(err.msg) throw err.msg; if(err.err.status == HttpStatusCodes.NOT_FOUND) throw(&quot;It doesn't exist.&quot;); throw(err); }) ) } </code></pre> <p>It's working great. When I subscribe to <code>checkExist()</code>, I get a good error message, because <code>HandleHttpBasicError</code> first catches an error and throws it to the service's <code>catchError()</code>, which throwes the error message because it was not <code>null</code>.</p> <p>This way, it allows me to have a global <code>catchError()</code> which handles error messages that will always be the same. In the future, I will do it in a <code>HttpHandler</code>, but that's not the point here.</p> <p>Is it ok to chain the errors with the <code>throw</code> keyword?</p> <p>I tried to return <code>Observable.throwError()</code>, but the browser said</p> <blockquote> <p>Observable.throwError is not a function</p> </blockquote> <p>My imports are <code>import {Observable, of, throwError} from 'rxjs';</code>.</p> <p>Isn't it better to do this:</p> <pre class="lang-ts prettyprint-override"><code>return ((source:Observable&lt;T&gt;) =&gt; { return source.pipe( catchError((err:any) =&gt; { msg = ''; ... return of({err, msg} as CustomError) /* instead of throw(err) -or- return Observable.throwError(err) (which doesn't work) */ }) ) }) </code></pre> <p>?</p>
0
Debugging python in Atom?
<p>Any package or IDE for Atom that will allow me to watch variables when debugging?</p> <p>I tried <a href="https://github.com/webBoxio/atom-hashrocket" rel="noreferrer">https://github.com/webBoxio/atom-hashrocket</a> but this does not let me go step by step</p> <p>I tried <a href="https://atom.io/packages/python-debugger" rel="noreferrer">https://atom.io/packages/python-debugger</a> But it has no watched variables.</p> <p>Any suggestions?</p>
0
How can I make CalendarExtender StartDate attribute take the current date?
<p>I thought something like this </p> <pre><code>&lt;ajaxToolkit:CalendarExtender ID="TextBox1_CalendarExtender" runat="server" TargetControlID="txtDatumPoaganje" Format="MM/dd/yyyy" StartDate=&lt;%=DateTime.Now%&gt;&gt; </code></pre> <p>But it doesnt work. I can make something similar with JavaScript and alert message:</p> <p><a href="https://stackoverflow.com/questions/5608062/how-to-disable-previous-dates-in-calendarextender-control-through-its-render-eve">how to disable previous dates in CalendarExtender control through its render event?</a> </p> <p>but it's not the same.</p>
0
How to set XAML Width in percentage?
<p>I am trying to create a button in XAML with a 80% width, but I can't seem to figure out how. It's apparently not as easy as using Width="80%". I have been thinking this can be done by detecting the screen width somehow and multiply that by 0.8 and use that as the width, but I am not sure how I can do this in XAML. Perhaps this has to be done in the .cs file and then adjust the width from there. Does anyone have a solution for this?</p>
0
SQL Dynamic DatePart when using DateDiff
<p>Is there a way to pass the DatePart parameter of DateDiff as a variable? So that I can write code that is similar to this?</p> <pre><code>DECLARE @datePart VARCHAR(2) DECLARE @dateParameter INT SELECT @datePart = 'dd' SELECT @dateParameter = 28 SELECT * FROM MyTable WHERE DATEDIFF(@datePart, MyTable.MyDate, GETDATE()) &lt; @dateParameter </code></pre> <p>The only ways I can think of doing it are with a CASE statement checking the value of the parameter or by building the SQL as a string and running it in an EXEC.</p> <p>Does anyone have any "better" suggestions? The platform is MS SQL Server 2005</p>
0
Get the real width and height of an image with JavaScript? (in Safari/Chrome)
<p>I am creating a jQuery plugin.</p> <p>How do I get the real image width and height with Javascript in Safari?</p> <p>The following works with Firefox 3, IE7 and Opera 9:</p> <pre><code>var pic = $("img") // need to remove these in of case img-element has set width and height pic.removeAttr("width"); pic.removeAttr("height"); var pic_real_width = pic.width(); var pic_real_height = pic.height(); </code></pre> <p>But in Webkit browsers like Safari and Google Chrome values are 0.</p>
0
How can I calculate a CRC32 as a signed integer in C#?
<p>I'm a PHP developer and a little out of my element in C#. In PHP, there's a <a href="http://www.php.net/manual/en/function.crc32.php" rel="noreferrer">crc32() function</a> which returns a signed integer for any string that you pass in.</p> <p>So this is what I'm used to:</p> <pre><code>&lt;?php echo crc32("test"); // displays -662733300 </code></pre> <p>I would like to do the same thing in C#. I came across <a href="http://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net" rel="noreferrer">this C# class library</a> but understand little about it. According to his instructions, I'm supposed to do this:</p> <pre><code>// first convert string to byte-array String input = "test"; byte[] bytes = new byte[input.length * sizeof(char)]; System.Buffer.BlockCopy(input.ToCharArray(), 0, bytes, 0, bytes.Length); // then calculate the value Crc32 crc32 = new Crc32(); String output = ""; foreach (byte b in crc32.ComputeHash(bytes)) { output += b.ToString("x2").ToLower(); } </code></pre> <p>That gives me an output string of <code>27d86d6a</code>. What do I need to do instead to return a signed integer? (Which in this example should equal <code>-662733300</code>)</p>
0
How to get the java.security.PrivateKey object from RSA Privatekey.pem file?
<p>I have a RSA private key file (OCkey.pem). Using java i have to get the private key from this file. this key is generated using the below openssl command. Note : I can't change anything on this openssl command below.</p> <pre><code>openssl&gt; req -newkey rsa:1024 -sha1 -keyout OCkey.pem -out OCreq.pem -subj "/C=country/L=city/O=OC/OU=myLab/CN=OCserverName/" -config req.conf </code></pre> <p>The certificate looks like below.<BR></p> <blockquote> <p>/////////////////////////////////////////////////////////// <BR> bash-3.00$ less OCkey.pem <BR> -----BEGIN RSA PRIVATE KEY----- <BR> Proc-Type: 4,ENCRYPTED<BR> DEK-Info: DES-EDE3-CBC,EA1DBF8D142621BF<BR></p> <p>BYyZuqyqq9+L0UT8UxwkDHX7P7YxpKugTXE8NCLQWhdS3EksMsv4xNQsZSVrJxE3<BR> Ft9veWuk+PlFVQG2utZlWxTYsUVIJg4KF7EgCbyPbN1cyjsi9FMfmlPXQyCJ72rd<BR> ...<BR> ...<BR> cBlG80PT4t27h01gcCFRCBGHxiidh5LAATkApZMSfe6BBv4hYjkCmg== <BR> -----END RSA PRIVATE KEY-----<BR> //////////////////////////////////////////////////////////////</p> </blockquote> <p>Following is what I tried </p> <pre><code>byte[] privKeyBytes = new byte[(int)new File("C:/OCkey.pem").length()]; PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(privKeyBytes)); </code></pre> <p>but getting </p> <blockquote> <p>"java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format"</p> </blockquote> <p>Please help.</p>
0
No service for type 'Microsoft.AspNetCore.Mvc.Localization.IHtmlLocalizer' has been registered
<p>I try with ASP.Core to have a multilanguages website. So, I have in my StartUp.cs:</p> <pre><code>public void ConfigureServices(IServiceCollection services) { services.AddLocalization(); services.Configure&lt;RequestLocalizationOptions&gt;( opts =&gt; { var supportedCultures = new[] { new CultureInfo("de-DE"), new CultureInfo("de"), new CultureInfo("fr-FR"), new CultureInfo("fr"), }; opts.DefaultRequestCulture = new RequestCulture("fr-FR"); // Formatting numbers, dates, etc. opts.SupportedCultures = supportedCultures; // UI strings that we have localized. opts.SupportedUICultures = supportedCultures; }); // Add framework services. services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt; options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;() .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;() .AddDefaultTokenProviders(); services.AddMvc(); // Add application services. services.AddTransient&lt;IEmailSender, AuthMessageSender&gt;(); services.AddTransient&lt;ISmsSender, AuthMessageSender&gt;(); } </code></pre> <p>In my _ViewImports.cs I have:</p> <pre><code>@using System.Threading.Tasks @using Microsoft.AspNetCore.Builder @using Microsoft.AspNetCore.Localization @using Microsoft.AspNetCore.Mvc.Localization @using Microsoft.Extensions.Options @inject IHtmlLocalizer Localizer @inject IOptions&lt;RequestLocalizationOptions&gt; LocOptions @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers </code></pre> <p>The errors:</p> <pre><code>An unhandled exception occurred while processing the request. InvalidOperationException: No service for type 'Microsoft.AspNetCore.Mvc.Localization.IHtmlLocalizer' has been registered. </code></pre>
0
how to make the text size of the x and y axis labels and the title on matplotlib and prettyplotlib graphs bigger
<p>I set the figure size of a matplotlib or prettyplotlib graph to be large. As an example lets say the size is 80 height by 80 width. </p> <p>The text size for the plot title, x and y axis labels (i.e. point label 2014-12-03 and axis label [month of year] become very small to the point they are unreadable.</p> <p>How do I increase the size of these text labels? Right now I have to zoom in with the web browser to see them.</p> <p><img src="https://i.stack.imgur.com/NjDDe.png" alt="enter image description here"></p>
0
Speed up VIM cursor moving through j/k
<p>On my friend new Mac, he scrolls from line #1 to line #100 using <code>k</code> in around 4 seconds. On my Mac, it takes 10 seconds. Neither of us know what causes his MacVim scrolls that fast.</p> <p>Any way that I can improve the speed of scrolling on my MacVim? I already enabled <code>ttyfast</code> and <code>lazyredraw</code></p>
0
Difference between <?php and <?
<p>I am new to php and would like to know if there are any differences between these server tags :</p> <pre><code>&lt;?php ?&gt; </code></pre> <p>and </p> <pre><code>&lt;? ?&gt; </code></pre>
0
How can I find the current Windows language from cmd?
<p>I would like to run a script for each language. I need a way to find which os language is being used, using batch files. Both on windows XP, and on Windows 7.</p>
0
SAPUI5 - complex model binding
<p>I have this json model:</p> <p><strong>model/data.json</strong></p> <pre><code>{ "orders" : [ { "header" : { "id" : "00001", "description" : "This is the first order" }, "items" : [ { "name" : "Red Book","id" : "XXYYZZ" }, { "name" : "Yellow Book", "id" : "AACCXX" }, { "name" : "Black Book", "id" : "UUEEAA" }, ] }, { // another order with header + items }, ..... ] } </code></pre> <p>and I'm assigning it <code>onInit</code> to the view, like this:</p> <pre><code>var model = new sap.ui.model.json.JSONModel("model/data.json"); sap.ui.getCore().setModel(reqModel); </code></pre> <p>I'm trying to display a list of orders in the first view (showing the id), like this:</p> <pre><code>var list = new sap.m.List({ id: "mainList", items: [] }); var items = new sap.m.ActionListItem({ text : "{id}", press : [ //click handler, onclick load the order details page ] }); list.bindItems("/orders", items); .... // add list to the page etc etc </code></pre> <p>What I cannot do, is connect each <strong>order</strong> to its <strong>header->id</strong>.. I tried</p> <pre><code>text: "/header/{id}" text: "{/header/id}" </code></pre> <p>in the items declaration, and </p> <pre><code>list.bindItems("/orders/header", items) </code></pre> <p>in the list binding, but none of them works.. The <strong>id</strong> value is not displayed, even though a "blank" list item is shown..</p> <p>Any idea? What am I doing wrong?</p> <p>Thank you </p>
0
Partial results using speech recognition
<p>I created a simple application inspired by <a href="http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/VoiceRecognition.html" rel="nofollow">this example</a> in order to test all the available options (ie extra). I read about the <a href="http://developer.android.com/reference/android/speech/RecognizerIntent.html#EXTRA_PARTIAL_RESULTS" rel="nofollow"><code>EXTRA_PARTIAL_RESULTS</code> extra</a> and if I enable this option I should receive from the server any partial results related to a speech recognition. However, when I add this extra to the <code>ACTION_RECOGNIZE_SPEECH</code> intent, the voice recognition does not work anymore: the list does not display any results.</p> <pre><code>protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_RECOGNITION_REQUEST_CODE) { switch(resultCode) { case RESULT_OK: Log.i(TAG, "RESULT_OK"); processResults(data); break; case RESULT_CANCELED: Log.i(TAG, "RESULT_CANCELED"); break; case RecognizerIntent.RESULT_AUDIO_ERROR: Log.i(TAG, "RESULT_AUDIO_ERROR"); break; case RecognizerIntent.RESULT_CLIENT_ERROR: Log.i(TAG, "RESULT_CLIENT_ERROR"); break; case RecognizerIntent.RESULT_NETWORK_ERROR: Log.i(TAG, "RESULT_NETWORK_ERROR"); break; case RecognizerIntent.RESULT_NO_MATCH: Log.i(TAG, "RESULT_NO_MATCH"); break; case RecognizerIntent.RESULT_SERVER_ERROR: Log.i(TAG, "RESULT_SERVER_ERROR"); break; default: Log.i(TAG, "RESULT_UNKNOWN"); break; } } Log.i(TAG, "Intent data: " + data); super.onActivityResult(requestCode, resultCode, data); } private void processResults(Intent data) { Log.i(TAG, "processResults()"); ArrayList&lt;String&gt; matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); // list of results ListView listOfResults = (ListView)(findViewById(R.id.list_of_results)); listOfResults.setAdapter(new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_list_item_1, matches)); // number of elements of above list TextView resultsCount = (TextView)(findViewById(R.id.results_count)); resultsCount.setText(getString(R.string.results_count_label) + ": " + matches.size()); } </code></pre> <p>When this option is enabled, the number of elements in the list of results is equal to 1 and this one result is an empty string. What is the reason for this behavior?</p> <p><strong>ADDED DETAILS</strong> I used the following code in order to enable <code>EXTRA_PARTIAL_RESULTS</code> option (on Android 2.3.5).</p> <pre><code>Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, ...); intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true); intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, ...); startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE); // where VOICE_RECOGNITION_REQUEST_CODE is a "global variable" </code></pre> <p>However, enabling this option, the <code>ArrayList&lt;String&gt; matches</code> in <code>processResults</code> method has only one empty element.</p>
0
Column has a data type that cannot participate in a columnstore index
<p>I want to create a clustered columnstore index in a table using the following query:</p> <pre><code>CREATE CLUSTERED COLUMNSTORE INDEX cci ON agl_20180319_bck </code></pre> <p>And I am getting this error:</p> <blockquote> <p>Msg 35343, Level 16, State 1, Line 6<br /> The statement failed. Column 'memberOf' has a data type that cannot participate in a columnstore index. Omit column 'memberOf'.</p> </blockquote> <p>The 'memberOf' is in this type: <code>memberOf nvarchar(max)</code>.</p> <p>How to overcome/ignore this error and what does it mean?</p>
0
Using Google Analytics without Javascript?
<p>Is it possible to use the Google Analytics code on a website which does not support javascript or any server side scripting? (<em>For example a profile page on a website which allows to use only HTML</em>).</p> <p>I have found out that analytics code can be used without using the javascript by calling the tracking image directly and send some data with it. I also found a couple of links but they use server side code also.</p>
0
Javascript Absolute Positioning
<p>I am trying to create a new div layer using JavaScript that can be absolutely positioned on the page after page load.</p> <p>My code is as follows:</p> <pre><code>&lt;html&gt;&lt;head&gt; &lt;script type="text/javascript"&gt; function showLayer() { var myLayer = document.createElement('div'); myLayer.id = 'bookingLayer'; myLayer.style.position = 'absolute'; myLayer.style.x = 10; myLayer.style.y = 10; myLayer.style.width = 300; myLayer.style.height = 300; myLayer.style.padding = '10px'; myLayer.style.background = '#00ff00'; myLayer.style.display = 'block'; myLayer.style.zIndex = 99; myLayer.innerHTML = 'This is the layer created by the JavaScript.'; document.body.appendChild(myLayer); } &lt;/script&gt; &lt;/head&gt;&lt;body bgcolor=red&gt;This is the normal HTML content. &lt;script type="text/javascript"&gt; showLayer(); &lt;/script&gt; &lt;/body&gt;&lt;/html&gt; </code></pre> <p>The page can be seen <a href="http://js.yachting.org/test.asp" rel="noreferrer">here</a>.</p> <p>The problem I am having is that the div is sitting after the original body content rather than over it on a new layer. How can I remedy this?</p>
0
how to bring live magento site to localhost without effecting live site
<p>i want a live site to be on local host and without effecting any functionality of live magento site. i have tried many way of doing that but have not get any result from it.</p> <p>steps i tried are : 1. taken database from magento live site by entering into cpanel(by ftp access) > phpmyadmin > exported all the files to my local machine and i imported all the data to my local phpmyadmin.</p> <p>2.taken all neccessary files from cpanel > file manager > all files (for example p_html, .htpassword, .trash, access log, etc file and many more) and put it on my local machine and then i put the file in folder and kept it into C:\xampp\htdocs\ all file ( in folder ).</p> <p>3 Replaced the path of live site with localhost:1234 in the all sql files where applicable taken in step one.</p> <p>but still not working . Any help will be appreciated....</p>
0
pymongo - "dnspython" module must be installed to use mongodb+srv:// URIs
<p>I am trying to connect MongoDB from Atlas.</p> <p>My <strong>mongo uri</strong> is: <code>mongodb+srv://abc:[email protected]/admin?retryWrites=True</code></p> <p>My <strong>pymongo version</strong> is <code>3.6.1</code></p> <p>I have installed <code>dnspython</code> and done <code>import dns</code></p> <p>But i still get this error:</p> <blockquote> <p>dnspython module must be installed to use mongodb+srv:// URI</p> </blockquote>
0
Android support Toolbar + ActionBarDrawerToggle not changing to arrow
<p>I'm struggling with the toolbar and drawer. I'm trying to make the burger switch to arrow when I'm adding a new fragment to the backstack but there is no way to do it.</p> <p>Maybe I'm missing something but I could not find a way. Anyone had the same problem?</p> <p>This is the declaration:</p> <pre><code>mDrawerToggle = new ActionBarDrawerToggle( getActivityCompat(), /* host Activity */ mDrawerLayout, /* DrawerLayout object */ ((BaseActivity) getActivityCompat()).getToolbar(), R.string.navigation_drawer_open, /* "open drawer" description for accessibility */ R.string.navigation_drawer_close /* "close drawer" description for accessibility */ ) </code></pre> <p>This is the function I call when a fragment is added to the back stack</p> <pre><code>public void setToggleState(boolean isEnabled) { if (mDrawerLayout == null) return; if (isEnabled) { mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); mDrawerToggle.onDrawerStateChanged(DrawerLayout.LOCK_MODE_UNLOCKED); } else { mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); mDrawerToggle.onDrawerStateChanged(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); } mDrawerToggle.syncState(); } </code></pre>
0
What do I need for development for an ARM processor?
<p>I'm familiar with X86[-64] architecture &amp; assembly. I want to start develop for an ARM processor. But unlike desktop processors, I don't have an actual ARM processor. I think I need an ARM simulator.</p> <p><a href="http://www.armtutorial.com/" rel="nofollow noreferrer">http://www.armtutorial.com/</a> say</p> <blockquote> <p>An ARM assembly compiler will be required, the most accessible is the ARMulator.</p> </blockquote> <p>I thought of downloading Armulator but found from <a href="http://forums.arm.com/index.php?showtopic=13744" rel="nofollow noreferrer">http://forums.arm.com/index.php?showtopic=13744</a> that</p> <blockquote> <p>Its not sold seperately. But you can download an eval of RVDS - which includes RVISS/ARMulator</p> </blockquote> <p>I've downloaded &amp; installed RVDS but It looks very complex. I'm unable to figure out what do I need to do <strong>to write ARM assembly &amp; run it</strong>.</p> <ul> <li>I want to write in assembly not in C/C++. I don't have an ARM processor. What is a good simulator?</li> <li>Can any one please mention in short. How to write assembly &amp; assemble &amp; simulate using RVDS. Please be clear?</li> <li>Are there any other alternative ways. I can't afford buying any kind of boards.</li> <li><p>I always learn from books rather than tutorials. I'm following these two books:</p> <ol> <li><a href="https://rads.stackoverflow.com/amzn/click/com/1558608745" rel="nofollow noreferrer" rel="nofollow noreferrer">ARM System Developer's Guide: Designing and Optimizing System Software (The Morgan Kaufmann Series in Computer Architecture and Design)</a> </li> <li><a href="https://rads.stackoverflow.com/amzn/click/com/0201675196" rel="nofollow noreferrer" rel="nofollow noreferrer">ARM System-on-Chip Architecture (2nd Edition)</a> </li> </ol></li> </ul> <p>Do you have any better suggestions?</p>
0
How to determine the end of an integer array when manipulating with integer pointer?
<p>Here is the code:</p> <pre><code>int myInt[] ={ 1, 2, 3, 4, 5 }; int *myIntPtr = &amp;myInt[0]; while( *myIntPtr != NULL ) { cout&lt;&lt;*myIntPtr&lt;&lt;endl; myIntPtr++; } Output: 12345....&lt;junks&gt;.......... </code></pre> <p>For Character array: (Since we have a NULL character at the end, no problem while iterating)</p> <pre><code>char myChar[] ={ 'A', 'B', 'C', 'D', 'E', '\0' }; char *myCharPtr = &amp;myChar[0]; while( *myCharPtr != NULL ) { cout&lt;&lt;*myCharPtr&lt;&lt;endl; myCharPtr++; } Output: ABCDE </code></pre> <p>My question is since we say to add NULL character as end of the strings, we rule out such issues! If in case, it is rule to add 0 to the end of integer array, we could have avoided this problem. What say?</p>
0