input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
How to get the return value of the start rule <p>How to get the 'return' value (<code>$$</code> variable) of the start rule of a grammar with Yacc/Bison?</p>
<p><code>yyparse</code> return the error code of the parser.</p>
| <p>The easiest solution is to store the value in an additional argument to <code>yyparse</code>. Normally you will store this value in the action for your start rule; sometimes it is useful to define an extra start non-terminal with a unit production to hold the action.</p>
<p>If you're using bison, you can use the <a href="https://www.gnu.org/software/bison/manual/bison.html#index-_0025parse_002dparam" rel="nofollow"><code>%parse-param</code></a> directive to define the extra argument, and then you just need to call <code>yyparse</code> with the address of the variable into which the result should be stored.</p>
<p>You still need to check the return value from <code>yyparse</code>; if it doesn't indicate success, then the value returned through the out parameter will not be correct.</p>
|
Moving a Team Project from one Collection to another - TFS 2015 Update 3 <p>I'm trying to move a Team Project from one Team Collection to another, including check-in history, user stories and source code. </p>
<p>I'm running a TFS 2015 Update 3 setup, but the tools I found do not support this version.</p>
<p>Tools:</p>
<ul>
<li><a href="http://tfsintegration.codeplex.com/" rel="nofollow">http://tfsintegration.codeplex.com/</a></li>
<li><a href="https://visualstudiogallery.msdn.microsoft.com/eb77e739-c98c-4e36-9ead-fa115b27fefe" rel="nofollow">https://visualstudiogallery.msdn.microsoft.com/eb77e739-c98c-4e36-9ead-fa115b27fefe</a></li>
</ul>
| <p>As @Daniel mentioned in comment, there's no way to move team projects between collections other than by using third party tools. But this feature is under planned, you can track this <a href="https://visualstudio.uservoice.com/forums/330519-team-services/suggestions/2037613-make-it-possible-to-move-a-team-project-between-te" rel="nofollow">UserVoice</a>:</p>
<blockquote>
<p>We are committed to allow you to move team projects between
collections, although itâs currently not in scope for the 2016
calendar year. Weâll provide an updated timeline as we get closer to
2017.</p>
</blockquote>
|
SignalR performance counters in Azure Web App <p>I've been trying to load test SignalR on my Azure Web App service (E.g. how many connections it can handle before subscribe calls to the hub start failing). I found that SignalR perfomance counters (<a href="https://www.asp.net/signalr/overview/performance/signalr-performance" rel="nofollow">https://www.asp.net/signalr/overview/performance/signalr-performance</a> ) can provide me such info. However, I cannot install those performance counters on Web App service, buy running </p>
<blockquote>
<p>SignalR.exe ipc</p>
</blockquote>
<p>Is there a way to install those performance counters on WebApp or retrieve them somehow from code? </p>
| <p>Performance Counters <a href="http://stackify.com/top-3-azure-web-app-limitations/" rel="nofollow">can't be installed on Azure Web App</a>, as it is provided as a managed container and <strong>not</strong> a full fledged IIS on which you can do everything.</p>
<p>To be able to use these performance counters you can redeploy your solution on an Azure VM or to a Cloud Service, keeping in mind you will l<strong>oose the flexibility</strong> that Azure Web App offers.</p>
|
An application says Microsoft.jet.Oledb 4.0 provider is not registered on the local machine <p>I'm.not the developer of that application. I'm the user , I downloaded an application 64bit as they directed . When I try to open the application it says the error Microsoft.Jet.OLEDB4.0 provider not registered on the local machine. I googled and searched in stacks. All the solutions are to the developers.as a user how can I run this application , how do enable/register that provider</p>
| <p>Try downloading Microsoft Access Database Engine.</p>
|
Perfect Square function that doesn't return <p>I'm a beginner working with Python and I was given this task: <em>write a function which returns the highest perfect square which is less or equal to its parameter (a positive integer).</em></p>
<pre><code>def perfsq(n):
x = 0
xy = x * x
if n >= 0:
while xy < n:
x += 1
if xy != n:
print (("%s is not a perfect square.") % (n))
x -= 1
print (("%s is the next highest perfect square.") % (xy))
else:
return(print(("%s is a perfect square of %s.") % (n, x)))
</code></pre>
<p>When I run the code to execute the function it doesn't output anything. I'll admit, I'm struggling and if you could give me some advice on how to fix this, I would be grateful.</p>
| <p>Like Patrick Haugh says, try examining when the while loop exits. It can be helpful to put print() statements throughout your method to figure out how your method executes. In order to figure out when your loop exits, look at the exit condition of your while loop: xy < n. </p>
<p>Remember, a variable isn't updated until you update it.</p>
<pre><code>def perfsq(n):
x = 0
xy = x * x
print("xy: {}".format(xy))
if n >= 0:
while xy < n:
x += 1
print("xy in loop: {}".format(xy))
if xy != n:
print (("%s is not a perfect square.") % (n))
x -= 1
print (("%s is the next highest perfect square.") % (xy))
else:
return(print(("%s is a perfect square of %s.") % (n, x)))
</code></pre>
|
Javascript .onclick function to redirect to other page <p>Hi i'm trying to validate user typing some data and then redirect the user to other web page, the alerts works nice but the location.href is doing nothing, please help.</p>
<pre><code>window.onload = function(){
var send = document.getElementById('send');
var email = document.getElementById('email');
var pass = document.getElementById('pass');
send.onclick = function(){
var data1 = email.value;
var data2 = pass.value;
if(data1==''){
alert('Please enter an email address');
}
else if(data2==''){
alert('Please enter your password');
}
else{
window.location.href = 'myotherpage.html';
}
}
}
</code></pre>
<p>Thanks.</p>
<p>Solution:</p>
<p>All I needed was to add a <code>return false;</code> after the location to stop the script and continue to the redirection instruction, thanks all for the replies.</p>
| <p>I changed your code to this and got it working just fine:</p>
<pre><code>window.onload = function(){
var send = document.getElementById('send');
var email = document.getElementById('email');
var pass = document.getElementById('pass');
send.onclick = function(){
var data1 = email.value;
var data2 = pass.value;
if(data1==''){
alert('Please enter an email address');
}
else if(data2==''){
alert('Please enter your password');
}
else{
window.location = 'myotherpage.html';
}
}
}
</code></pre>
<p>I changed your <code>valor</code> variables to <code>data</code>, <code>envia</code> to <code>send</code>, and <code>window.location.href</code> to <code>window.location</code>.</p>
|
Windows10 .exe ICON is missing <p>I'm trying to fix Windows context menu slow issue, right click menu is very slow.</p>
<p>I've done below steps:</p>
<ol>
<li><p>Using ShellExView to disable some external items, no Microsoft item is disabled.</p></li>
<li><p>Remove HKEY_CLASSES_ROOT\Directory\Background\shellex\ContextMenuHandlers\NvCplDesktopContext</p></li>
<li><p>Reboot PC</p></li>
</ol>
<p>Now context menu speed issue is fixed, but lots of exe icon are missing after this, like notepad++ or IE shortcuts are shown as blank file icon.</p>
<p><a href="https://i.stack.imgur.com/dql9H.png" rel="nofollow">[Please click here] for IE icon screenshot example</a></p>
<p>Uninstall and re-install tool still can NOT fix this issue.</p>
<p>Thanks!</p>
| <p>Manually fixed the issue by extracting icon from exe file then use extracted icon.
Seems like icon cache is broken.</p>
|
How does wpf raise mouseDown event? <p>How does wpf raise mouseDown event? As I understand, wpf should perform some kind of hit test method, which should call specified mouse down handler. Unfortunately, I cannot find this piece of code in source of WPF. Can anybody point me to right place? </p>
<p>As I understood, Visual class should define such logic</p>
| <p>Start here: <a href="https://msdn.microsoft.com/en-us/library/ms752097(v=vs.110).aspx" rel="nofollow">Hit Testing in the Visual Layer</a>.
And in particular check this: <a href="https://msdn.microsoft.com/en-us/library/system.windows.uielement.inputhittest(v=vs.110).aspx" rel="nofollow">UIElement.InputHitTest</a>.</p>
|
Convert character dates with NA into date format - Something Strange? <p>As I can not share my data due to restriction . Please try to provide solution using the information below
I have a dataframe called data. There are variable which I want to convert into date and time format.</p>
<p>[![enter image description here][1]][1]</p>
<pre><code>data$Call_TimeStamp = as.POSIXct(paste(data$Local_call_Date, data$Local_call_Time.y), format= "%Y-%m-%d% %H:%M:%S", tz = 'GMT')
str(data$Call_TimeStamp)
POSIXct[1:66288], format: NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
</code></pre>
<p>But When I run query on another variables of the same dataset having the same date and time format it run perfectly , the only difference is those variables don't have NA in it as a character.</p>
<pre><code> data$Sent_TimeStamp=as.POSIXct(paste(data$Local_Sent_Date.x, data$Local_Sent_Time.x), format="%Y-%m-%d %H:%M:%S", tz = 'GMT')
</code></pre>
| <p>Two things, one good, one (likely) bad:</p>
<ul>
<li><p>your data is in a sane format as far as the time string goes: <a href="https://en.wikipedia.org/wiki/ISO_8601" rel="nofollow">ISO 8601</a> -- this makes parsing easier</p></li>
<li><p>your data is very likely in factor form and you forgot the required <code>as.character()</code>.</p></li>
</ul>
<p>Now, the recently-release <a href="http://dirk.eddelbuettel.com/code/anytime.html" rel="nofollow">anytime</a> package helps with both. Here is one example from the webpage / <a href="https://github.com/eddelbuettel/anytime" rel="nofollow">GH README.md</a>: </p>
<pre><code>R> ## factor
R> anytime(as.factor(20160101 + 0:2))
[1] "2016-01-01 CST" "2016-01-02 CST" "2016-01-03 CST"
</code></pre>
<p>It will also parse with dates and time, with or without factor representation and still not require a format:</p>
<pre><code>R> anytime("2016-01-02 03:04:05.678")
[1] "2016-01-02 03:04:05.677 CST"
R> anytime(as.factor("2016-01-02 03:04:05.678"))
[1] "2016-01-02 03:04:05.677 CST"
R>
</code></pre>
<p>You can install <a href="http://dirk.eddelbuettel.com/code/anytime.html" rel="nofollow">anytime</a> directly from CRAN.</p>
|
Datagrip added value compared to IntelliJ <p>So, I was wondering if there is really some new features coming from Jetbrains Datagrip software.</p>
<p>So far, I didn't find anything that is not already there in IntelliJ Idea (Ultimate). I didn't spend much time using it though.</p>
| <p>From FAQ part from this <a href="https://blog.jetbrains.com/datagrip/2015/12/16/datagrip-1-0-formerly-0xdbe-a-new-ide-for-dbs-and-sql/" rel="nofollow">blog</a>.</p>
<blockquote>
<p><em>Does DataGrip repeat the functionality of the database tools in other JetBrains IDEs?</em></p>
<p>Yes, the first version focuses on that core functionality.</p>
</blockquote>
<p>Further dialog from comments:</p>
<blockquote>
<p><code>Graham says</code>:</p>
<p>December 16, 2015 at 10:01 pm</p>
<p><em>This repeats the functionality in Intellij, but does it add any more features over and above Intellij? If they are equal right now, will that always be the case? Would be nice to see a feature comparison chart.</em></p>
<hr>
<p>Reply</p>
<p><code>Andrey Cheptsov says</code>:</p>
<p>December 17, 2015 at 8:03 am</p>
<p><em>The latest version of IntelliJ IDEA Ultimate includes the functionality of DataGrip 1.0. Still, DataGrip is focused on working with databases and SQL and thus may provide better user experience as a standalone IDE.</em></p>
</blockquote>
<p>So it is has the same functionally for <a href="https://en.wikipedia.org/wiki/Database_administrator" rel="nofollow">DBA</a>. People who have deal with programing languages quite seldom.</p>
|
Spring: Apache POI Excel file download "Current policy properties" error in build log <p>I have a very simple Controller method that downloads an excel file using Apache POI library which is generated in a Service class like so:</p>
<pre><code>XSSFWorkbook workbook = new XSSFWorkbook();
// Excel sheet populated and added to workbook
FileOutputStream out = new FileOutputStream(new File("file.xlsx"));
workbook.write(out);
out.close();
</code></pre>
<p>And the following Controller method triggers a download.</p>
<pre><code>@ResponseBody
@RequestMapping(value = "/fileDownload")
public String downloadMatchingExcel(HttpServletRequest request, HttpServletResponse response) throws IOException{
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename = file.xlsx");
response.setHeader("Content-Length", String.valueOf(file.length()));
FileInputStream is = new FileInputStream(new File("file.xlsx"));
IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
response.getOutputStream().close();
}
</code></pre>
<p>The file is generated and downloaded without any problems. But I get the following error in the build log.</p>
<pre><code>[ERROR] Current policy properties:
[ERROR] mmc.sess_pe_act.block_unsigned: false
[ERROR] window.num_max: 5
[ERROR] jscan.sess_applet_act.sig_trusted: pass
[ERROR] jscan.sess_applet_act.block_all: false
[ERROR] file.destructive.state: disabled
[ERROR] window.num_limited: true
[ERROR] jscan.sess_applet_act.unsigned: instrument
[ERROR] mmc.sess_pe_act.action: validate
[ERROR] jscan.session.daemon_protocol: http
[ERROR] file.read.state: disabled
[ERROR] mmc.sess_pe_act.block_invalid: true
[ERROR] mmc.sess_pe_act.block_blacklisted: false
[ERROR] jscan.session.policyname: QXBwbGV0L0FjdGl2ZVggU2VjdXJpdHkgR2xvYmFsIFBvbGljeSA=
[ERROR] net.bind_enable: false
[ERROR] mmc.sess_cab_act.block_unsigned: false
[ERROR] file.nondestructive.state: disabled
[ERROR] jscan.session.origin_uri: http://repo.spring.io/libs-release/org/apache/poi/poi-ooxml/3.11/poi-ooxml-3.11.jar
[ERROR] mmc.sess_cab_act.action: validate
[ERROR] net.connect_other: false
[ERROR] jscan.session.user_ipaddr: 172.24.8.56
[ERROR] jscan.sess_applet_act.sig_invalid: block
[ERROR] thread.thread_num_max: 8
[ERROR] mmc.sess_cab_act.block_invalid: true
[ERROR] jscan.sess_applet_act.sig_blacklisted: block
[ERROR] net.connect_src: true
[ERROR] thread.thread_num_limited: true
[ERROR] jscan.sess_applet_act.stub_out_blocked_applet: true
[ERROR] mmc.sess_cab_act.block_blacklisted: true
[ERROR] jscan.session.user_name: MTcyLjI0LjguNTY=
[ERROR] thread.threadgroup_create: false
[ERROR] file.write.state: disabled
</code></pre>
<p>What does it mean? And is it something to worry about?</p>
| <p>There is lots of relative question in here, such as <a href="http://stackoverflow.com/questions/4667357/java-policy-error-applet-alert">this</a> and <a href="http://stackoverflow.com/questions/15609836/maven-getting-a-popup-asking-for-permission-while-building">that</a>
It seems it cause by some firewall/proxy/antivirus modify the jar you download.</p>
|
What's the difference between EDI, AS2 and GS1 and how do they work together? <p>I'm learning about EDI and there are many acronyms and standards that seem to overlap.
What is the difference between EDI (and a EDI translator) and AS2 (which seem to be EDI over HTTP)? Then there is GS1, whith it's own subsets (GS1 EANCOM GS1 XML
GS1 UN/CEFACT XML) and EDIFACT.</p>
<p>Why would one use an EDI translator like BOTS together with an AS2 server ? Are they complementary?</p>
<p>Is there a map, a guide or explanation of how do all theese standars work together in the context of supply chain ? (i.e: a warehouse which ships to client's own warehouses or stores).</p>
<p>Thanks</p>
| <p>From Walmart Getting Started with EDI
Implementation Guide ( <a href="http://cdn.corporate.walmart.com/5d/8d/897b4bb84a95bb05214bf897cee3/edi-getting-started-guide.pdf" rel="nofollow">http://cdn.corporate.walmart.com/5d/8d/897b4bb84a95bb05214bf897cee3/edi-getting-started-guide.pdf</a> )</p>
<ol>
<li><p>What is EDI?</p>
<p>a. Simply stated, EDI (Electronic Data Interchange) is the
electronic exchange of business documents between suppliers and retailers.</p>
<p>b. EDI is comprised of two components: translation and communication.
i. During translation, a business document is changedâor âtranslatedââinto
a standardized EDI format.</p>
<p>c. There are various EDI standards (or formats) that a company may use.
i. Please view âHow is EDI data formatted?â for more information about the
EDI standards that we support.</p>
<p>d. Once a business document is translated into an EDI format it is communicatedâ
or electronically sentâto the intended recipient.</p>
<p>e. There are several methods of EDI communications available, but the method
utilized by Walmart and our suppliers is AS2.</p></li>
<li><p>What is EDIINT AS2?</p>
<p>a. EDIINT (EDI over the Internet) is a set of communication protocols, introduced by
the IETF (Internet Engineering Task Force) in 1995, used to securely transmit data
over the Internet.</p>
<p>i. Although EDIINT was initially designed to transport EDI data, it may also be
used to transfer non-EDI data.</p>
<p>b. One version of EDIINT is AS2 or Applicability Statement 2.</p>
<p>i. The UCC (Uniform Code Council) has facilitated the development and
interoperability testing of the AS2 standard.</p>
<p>ii. AS2 supports EDI or other data file transmissions over the Internet using
HTTP/HTTPS.</p>
<p>c. AS2 is a specification about how to transport data, not how to validate or process
the content of the data.</p>
<p>d. AS2 specifies the means to connect, deliver and receive data in a secure and
reliable way.</p>
<p>e. AS2 is not an asynchronous or FTP solution; it is an Internet Protocol based solution
that uses standard HTTP/HTTPS communications to transmit data.</p>
<p>f. For more information on EDIINT AS2, or for a list of interoperable-tested AS2
software providers, visit <a href="http://www.drummondgroup.com" rel="nofollow">http://www.drummondgroup.com</a>.
Getting Started with EDI â Implementation Guide
Last Modified On: 4/14/2014 Wal-Mart Confidential 5</p>
<p>g. For additional information see the EDIINT FAQâs within Retail Link⢠on the ECommerce/EDI
page.</p></li>
<li><p>How is EDI data formatted?</p>
<p>a. The information is formatted using EDI standards.</p>
<p>b. Walmart currently supports:</p>
<p>i. ANSI X12 (American National Standards Institute)</p>
<ol>
<li><p>UCS (Uniform Communications Standards)</p></li>
<li><p>VICS (Voluntary Inter-industry Commerce Standard)
ii. EDIFACT (Electronic Data Interchange For Administration, Commerce and
T+ransport)</p></li>
</ol>
<p>c. Walmart stays within the VICS and UCS guidelines for our major documents within
the United States and Canada. EDIFACT is only used for suppliers outside of the
U+S and Canada and those that will be directly importing merchandise for our
company.</p></li>
</ol>
|
Firing event on disabled button <p>I want to fire a event on a disabled button</p>
<pre><code> <button ion-button icon-only [disabled]="!isConnected" (click)="openModal()" (disabledClick)="showErrMsg()" shortVibrateOnTap>
<ion-icon ios="ios-swap" md="ios-swap"></ion-icon>
</button>
</code></pre>
<p>and if this is not possible, how do I style a button like it is disabled ?</p>
| <p>The disabled class of ionic sets <code>opacity: 0.4;</code> on the disabled buttons that gives the visual effect and <code>pointer-events: none;</code> that prevents any events from firing.</p>
<p>So if you want to make a button to look like disabled you should create a class </p>
<pre><code>.disabled {opacity: 0.4;}
</code></pre>
<p>Or else you can wrap the button with a div and attach a click event on it:</p>
<pre><code> <div (click)="showErrMsg()">
<button ion-button icon-only [disabled]="!isConnected" (click)="openModal()" shortVibrateOnTap>
<ion-icon ios="ios-swap" md="ios-swap"></ion-icon>
</button>
</div>
</code></pre>
<p>In your <code>showErrMsg</code> function make your code to run only when <code>!isConnected</code></p>
|
Google Fonts looks different at google.com and at my web site <p>I just tried to use Google Fonts and have noticed the following disturbing effect:<br> The result of using the font at my custom html file is different from what's present on Google site.<br> At least the font size is definitely different (color is also different, but it doesn't matter).</p>
<p>Font: Slabo 27px, size: 112px<br>
Link to the Google Fonts: <a href="https://fonts.google.com/specimen/Slabo+27px" rel="nofollow">https://fonts.google.com/specimen/Slabo+27px</a><br>
The browser is the same: Firefox. <br></p>
<p>At google:<br>
<a href="https://i.stack.imgur.com/EA9SA.png" rel="nofollow"><img src="https://i.stack.imgur.com/EA9SA.png" alt="At google.com/fonts"></a><br>
At my site<br>
<a href="https://i.stack.imgur.com/TN0na.png" rel="nofollow"><img src="https://i.stack.imgur.com/TN0na.png" alt="On my site"></a></p>
<p>HTLM code that I used:</p>
<pre><code><link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Slabo+27px">
<div class="end">
<p>Regular</p>
</div>
</code></pre>
<p>main.css:</p>
<pre><code>.end {
font-family: 'Slabo 27px';
font-weight: 400;
font-style: normal;
font-size: 112px;
color: #212121;
}
</code></pre>
<p>Any ideas what cause such effect??</p>
<p>Update:
Arrgh, it was just me being inattentive.<br>
Google page turned out to be zoomed the whole time.<br>
I compared them after zoom reset and confirmed that they are identical. </p>
| <p>I honestly don't see a difference. Apart from the color and size.</p>
<p>Yours looks a bit sharper. But I wouldn't complain about that.</p>
|
How to convert between a C# String and C Char pointer <p>I have a large library written in C that I would like to use as a DLL in a C# program. Most of the C code will be used by the libraries own functions, but I do need one function to be able to be called from the C# project.</p>
<p>So there's an example C function below</p>
<pre><code>__declspec(dllexport) char* test(char* a){
char* b = "World";
char* result = malloc(strlen(a) + strlen(b) + 1);
strcpy(result, a);
strcpy(result, b);
return result;
}
</code></pre>
<p>Now in the C# code I have got <code>using System.Running.InteropServices;</code>
and also <code>[DllImport("mydll.dll")]</code> but I'm not sure how to declared the function.</p>
<p><code>public static extern char* test(char* a);</code> obviously doesn't work because C# doesn't support pointers like C does. </p>
<p>So how should I pass a string to this C function and have it return a string as well?</p>
| <p>You're looking for a MarshalAs attribute:</p>
<pre><code> [DllImport("mydll.dll")]
static public int test([MarshalAs(UnmanagedType.LPStr)]String a);
</code></pre>
<p>As for returning a dynamically allocated C string, bad idea. How will you reliably de-allocate the string? It's a recipe for a memory leak. Allocate a byte array in C#, pin it and pass it to the C code along with its size so the C code can copy the result into it. Then convert to a string using <code>System.Text.Encoding.ASCII.GetString()</code>.</p>
|
Do I have to include third party frameworks separately with my app? <p>I am building an iOS cocoa touch static library. It depends on a third party framework. Would I have to ship the framework with my app or not? </p>
<p>I am guessing that the definition of static library means that the output .a file should already have the necessary parts of the included framework and therefore I should not have to supply the framework separately. Is that true ?</p>
| <p>Are you making something like a cocoapod? Because then, you can specify it as a proper dependency in the podspec. Otherwise, you can include instructions on including the third party framework or bundle it in yourself.</p>
|
DynamoDB Geo Object Mapper Class Not Found <p>I have been trying to use the <a href="https://github.com/awslabs/dynamodb-geo" rel="nofollow">dynamodb-geo</a> library in my project (Android). After reading everything possible around the interent I noticed that the lib jars are not included in the classpath, I did it and got to the codehaus Object Mapper class not found exception. Then I sustitute the dependencies in the pom to add fasterxml and change the corresponging imports. After that I have packaged it (mvn clean package) and put the corresponding jar in the libs folder of my android project, set it up in gradle and "play".</p>
<p>However, I still get the annoying "Class not found".</p>
<p>The pom of the dynamodb geo contains:</p>
<pre><code> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.3</version>
</dependency>
</code></pre>
<p>And my gradle file in android contains:</p>
<pre><code>compile files('libs/dynamodb-geo-1.1.0.jar')
</code></pre>
<p>But I am still getting:</p>
<pre><code>10-17 17:27:33.134 5139-5363/com.fivesigmagames.sdghunter E/AndroidRuntime: FATAL EXCEPTION: Thread-32098
Process: com.fivesigmagames.sdghunter, PID: 5139
java.lang.NoClassDefFoundError: Failed resolution of: Lcom/fasterxml/jackson/databind/ObjectMapper;
at com.amazonaws.geo.util.GeoJsonMapper.<clinit>(GeoJsonMapper.java:26)
at com.amazonaws.geo.dynamodb.internal.DynamoDBManager.putPoint(DynamoDBManager.java:125)
at com.amazonaws.geo.GeoDataManager.putPoint(GeoDataManager.java:132)
at com.fivesigmagames.sdghunter.repository.aws.AWSShareItemRepository$1.run(AWSShareItemRepository.java:58)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.fasterxml.jackson.databind.ObjectMapper" on path: DexPathList[[dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-unity-classes_bf479e7b8b71b5703bea6af2dcab41a7dfc4e91a-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-support-annotations-24.2.1_7a5f3f7e74247119444f4d43b2c522de9eab70fb-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-slice_9-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-slice_8-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-slice_7-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-slice_6-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-slice_5-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-slice_4-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-slice_3-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-slice_2-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-slice_1-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-slice_0-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-s2-geometry-java_4a01ca5c6a6c529340eae8f7f80c06b632fdefb5-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-retrofit-2.1.0_95833411f91cbb8e9410129091d258a780b3748c-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-okio-1.8.0_0cb7cee6746d84f62570817f36b8feb9fcf01356-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-okhttp-3.3.1_f8edaf579e8e4a295d221f114889d70d3e62eb9f-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-mapbox-java-services-1.3.1_a50eb5179d7320fcdc538c586ebd2f231b152887-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-logging-interceptor-3.3.1_699d973b2d0ba8bcd453fd52df4c55554a3d27f5-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-internal_impl-24.2.1_f38e546d683a020056b2318e9388188d85136c2f-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-internal_impl-24.2.1_8f4ea427bad833b1812bc9e939084c687a54e0d0-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-internal_impl-24.2.1_3609d9e6e631ae1ef0b5261e8250a3cf6f1193cf-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-internal_impl-24.2.1_280e40067a7d8e7f7f2bc98507cf0b17f26db6bf-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-internal_impl-24.2.1_008f1eca59ba22cef5240a40ab0f74834de26c4c-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-guava-r09_4880220368cf85c4cfb2f46fdedb8912a6629e2a-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-guava-18.0_e11ced1631feb7c9800790c98fd765d3bed1b86c-classes.dex", dex file "/data/data/com.fivesigmagames.sdghunter/files/instant-run/dex/slice-gson-2.7_792e0
</code></pre>
<p>If I manually (thourgh gradle) add the three jackson dependencies I get a "duplicate" entry error and it does not compile.</p>
<p>Thanks for the help!</p>
| <p>I've been struggling with this about 7 months ago. The dynamodb-geo jar has a dependency with an old version of the java aws-sdk (1.5.5). This 1.5.5 version uses org.codehaus package names for the Jackson libs. </p>
<p>Later Jackson has modified it's packages names from org.codehaus to com.fasterxml. More recent versions of the java aws-sdk have been updated to use these new package names, but dynamodb-geo still depends on 1.5.5 . So you can not deploy this old jar in a newer java aws-sdk environment.</p>
<p>Best solution is to create a new jar for dynamodb-geo yourself, as you are already trying. But you do not need to add dependencies with Jackson yourself, because these are provided by the aws sdk. You can fork the aws dynamodb-geo repository on github, update the aws-java-sdk.version property in the pom.xml, fix the compile errors and build your own jar with Maven.</p>
<p>I have created a <a href="https://github.com/peterfennema/dynamodb-geo/tree/topic-update-to-aws-java-sdk-1.10.61" rel="nofollow">fork on Github</a> that does exactly this. Using this fork you can easily create your own jar.</p>
<p>I have reported this issue to AWS and provided a <a href="https://github.com/awslabs/dynamodb-geo/pull/15" rel="nofollow">pull request on Github</a>. Unfortunately the library is not maintained at all, which made me decide not to use it.</p>
|
convert different string types in dates R data frame <p>I have a messy data frame with two columns:</p>
<pre><code>DF<-data.frame(x=seq(100,105,1),y=c("3/25/2014 12:56","3/25/2014 14:18","3/25/2014 14:18","3/25/2014 14:18","3/25/2014 14:18","2014-03-25 14:19:08.043"))
x y
1 100 3/25/2014 12:56
2 101 3/25/2014 14:18
3 102 3/25/2014 14:18
4 103 3/25/2014 14:18
5 104 3/25/2014 14:18
6 105 2014-03-25 14:19:08.043
</code></pre>
<p>I want to convert the y columns into R dates so to have:</p>
<pre><code> x y
1 100 2014-03-25
2 101 2014-03-25
3 102 2014-03-25
4 103 2014-03-25
5 104 2014-03-25
6 105 2014-03-25
</code></pre>
<p>In order to do so, I can use the function parse_date_time from Lubridate for the first 5 elements </p>
<pre><code>as.Date(parse_date_time(DF$y[1:5], orders="mdy hm"))
</code></pre>
<p>and directly the function as.Date for the last one:</p>
<pre><code>as.Date(DF$y[6], orders="mdy hm")
</code></pre>
<p>I could do that by making a for and if loop, however, I'm looking for a more elegant vectorised solution. </p>
<p>Do you have an idea?</p>
<p>Thanks</p>
| <p>I'd use package anytime:</p>
<pre><code>library(anytime)
anydate(DF$y)
#[1] "2014-03-25" "2014-03-25" "2014-03-25" "2014-03-25" "2014-03-25" "2014-03-25"
</code></pre>
|
Write php code inside a html string <p>im trying to insert some php that controll my session inside a html, the thing is that i cant concat the php with the html and i have no idea how to do it basicly i have the session <code>$_SESSION["nome"]</code> and want to put it <strong>here:</strong></p>
<pre><code><?php
return
"
<div class='container-fluid'>
<div class='row imageBlock sky'>
<div class='col-md-3'><img class='img-responsive house' src=
'Imagens/pr%C3%A9dios.png'></div>
<div class='col-md-3'><img class='img-responsive house' src=
'Imagens/pr%C3%A9dios2.png'></div>
<div class='col-md-3'><img class='img-responsive house' src=
'Imagens/pr%C3%A9dios3.png'></div>
<div class='col-md-3'><img class='img-responsive house' src=
'Imagens/pr%C3%A9dios4.png'></div>
</div>
<div class='row'>
<h3 class='text-center' id='titulo'>OSeuCondomÃnio</h3>
</div>
<div class='row enter-block myBox'>
<div class='col-md-offset-3 col-md-9'>
<p class='okText'><span class='glyphicon glyphicon-ok'></span> Quer Gerir o
condomÃnio, tendo a possibilidade de marcar reuniões, registar
intervenções e guardar ficheiros?</p>
</div>
<div class='col-md-offset-3 col-md-9'>
<p class='okText'><span class='glyphicon glyphicon-ok'></span> Quer ter acesso
a tudo o que se passa no seu apartamento sem saÃr do lugar?</p>
</div>
<div class='col-md-offset-3 col-md-9'>
<p class='okText'><span class='glyphicon glyphicon-ok'></span> Quer efetuar o
pagamento das quotas através da plataforma?</p>
</div>
<div class='col-md-offset-3 col-md-9'>
<p class='okText'><span class='glyphicon glyphicon-ok'></span> Pretende
conversar aqui com os moradores?</p>
</div>
</div>
<div class='row main-text'>
<header>
<h5 class='text-center main-text-content'>Se respondeu que sim
a pelo menos uma das questões esta é a plataforma ideal para
si !!</h5>
</header>
</div>
<div class='row responsive nowrap'>
<a href='index.php?page=LoginFormCont'><button class='btn btn-lg center-block EntreJa'>Entre Já</span></button></a>
</div>
</div>";
?>
</code></pre>
<p>i want to write the loged users name in a div inside this html and i need to write the php session variable inside any tips?</p>
| <p>Your example was not very specific. You said you want to insert the name "here", but then included about 44 lines of code.</p>
<p>Being that you're in a code-block, you can concatenate your HTML and sessions like so:</p>
<pre><code><?php
return "<div>" . $_SESSION["nome"] . "</div>";
?>
</code></pre>
|
Determine whether eigen has optimized code for SSE instructions or not <p>I am having a code which is using Eigen::vectors, I want to confirm that Eigen has optimized this code for SSE or not.</p>
<p>I am using Visual Studio 2012 Express, in which i can set the command line option <em>"/Qvec-report:2"</em> which gives the optimization details of C++ code. Is there any option in visual studio or Eigen which can tell me that code has been optimized or not?</p>
<p>My code is as below:</p>
<pre><code>#include <iostream>
#include <vector>
#include <time.h>
#include<Eigen/StdVector>
int main(char *argv[], int argc)
{
int tempSize=100;
/** I am aligning these vectors as specfied on http://eigen.tuxfamily.org/dox/group__TopicStlContainers.html */
std::vector<Eigen::Vector3d,Eigen::aligned_allocator<Eigen::Vector3d>> eiVec(tempSize);
std::vector<Eigen::Vector3d,Eigen::aligned_allocator<Eigen::Vector3d>> eiVec1(tempSize);
std::vector<Eigen::Vector3d,Eigen::aligned_allocator<Eigen::Vector3d>> eiVec2(tempSize);
for(int i=0;i<100;i++)
{
eiVec1[i] = Eigen::Vector3d::Zero();
eiVec2[i] = Eigen::Vector3d::Zero();
}
Eigen::Vector3d *eV = &eiVec.front();
const Eigen::Vector3d *eV1 = &eiVec1.front();
const Eigen::Vector3d *eV2 = &eiVec2.front();
/** Below loop is not vectorized by visual studio due to code 1304:
Because here comes the operations at level of Eigen, I want to
know here whether Eigen has optimized this operation or not? */
for(int i=0;i<100;i++)
{
eV[i] = eV1[i] - eV2[i];
}
return 0;
}
</code></pre>
| <p>Look at the asm output.</p>
<p>If you see SUBPD (packed double) inside the inner loop, it vectorized. If you only see SUBSD (scalar double) and no SUBPD anywhere, it didn't.</p>
|
Spring + Angular Http Cache Not Clearing <p>From what I've researched, both Spring and Angular do not enable http caching by default. ie, you have to explicitly add in the option if you need that functionality. However, for some reason my http requests just pile up as I navigate from page to page, whereas on a normal web page they would disappear after leaving a page (unless you cached them). I've searched quite a bit but I cannot find a similar situation/problem. One idea I had is that it might be a browser setting within Chrome but I haven't found anything on that.</p>
<p>Here is an example. The first picture is on a secondary page, and the second picture is after navigating back to the home page. You can see that the requests do not leave the queue after doing so. Third picture is an example of a response I'm getting. Any help is appreciated.</p>
<p><a href="https://i.stack.imgur.com/xba7E.png" rel="nofollow"><img src="https://i.stack.imgur.com/xba7E.png" alt="Secondary Page"></a></p>
<p><a href="https://i.stack.imgur.com/MhW5u.png" rel="nofollow"><img src="https://i.stack.imgur.com/MhW5u.png" alt="Back to Home page"></a></p>
<p><a href="https://i.stack.imgur.com/Ngvzm.png" rel="nofollow"><img src="https://i.stack.imgur.com/Ngvzm.png" alt="Headers"></a></p>
<p>I'm also wondering if there is something on my classpath that could be causing this, because both Spring and Angular have caching disabled by default.</p>
| <p>You need to configure your server to disable caching of files. For development, you can just select the <em>Disable Cache</em> option and keep the development console open to disable caching.</p>
<p><a href="https://i.stack.imgur.com/e5uLf.png" rel="nofollow"><img src="https://i.stack.imgur.com/e5uLf.png" alt="enter image description here"></a></p>
|
JavaFX: display text instead of boolean value (true/false) <p>I'm using tableview in <code>JavaFX</code> to display <code>List<Contact></code>.</p>
<p>For initialize function of the controller, the tableview columns are binded to <code>List<Contact></code> as follow:</p>
<pre><code>sprintName.setCellValueFactory(new PropertyValueFactory<Contact, String>("name"));
importStatus.setCellValueFactory(new PropertyValueFactory<Contact, Boolean>("imported"));
enddate.setCellValueFactory(new PropertyValueFactory<Contact, String>("endDate"));
</code></pre>
<p>However, I want to display for column <code>imported</code> instead <code>true/false</code> the text <code>imported/new</code></p>
<p>Is it possible in <code>JavaFX</code> or do I have to change the type of <code>imported</code> to <code>String</code>?</p>
| <p>Use a cell factory (in addition to the cell value factory):</p>
<pre><code>importStatus.setCellFactory(tc -> new TableCell<Contact, Boolean>() {
@Override
protected void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty);
setText(empty ? null :
item.booleanValue() ? "imported" : "new");
}
});
</code></pre>
<p>See the <a href="http://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Cell.html" rel="nofollow"><code>Cell</code> class documentation</a> for general information about the cell rendering mechanism.</p>
|
Java lambda filter and map, can I avoid these repetitive calls? <p>I'm learning lambdas and I am wondering about the following code:</p>
<pre><code> ArrayList<String> lines = new ArrayList<>();
lines.add("#ignored");
lines.add(" #ignored2");
lines.add("Not Ignored");
lines.add("also not ignored");
lines.add(" also Not Ignored but lower CASE");
lines.stream()
.filter(line -> !line.trim().startsWith("#"))
.map(line -> line.trim().toLowerCase())
.forEach(System.out::println);
</code></pre>
<p>output:</p>
<pre><code>not ignored
also not ignored
also not ignored but lower case
</code></pre>
<p>For both the filter and map lines, I'm calling trim() to strip any leading or tailing whitespace.</p>
<p>Is it possible here to trim the line once, store the result, and then use that result in the map?</p>
| <p>You can use the <code>map</code> method at the beginning to trim the lines:</p>
<pre><code>lines.stream()
.map(String::trim) // Trim the spaces
.filter(line -> !line.startsWith("#"))
.map(String::toLowerCase)
.forEach(System.out::println);
</code></pre>
|
Python type checking not working as expected <p>I'm sure I'm missing something obvious here, but why does the following script actually work?</p>
<pre><code>import enum
import typing
class States(enum.Enum):
a = 1
b = 2
states = typing.NewType('states', States)
def f(x: states) -> states:
return x
print(
f(States.b),
f(3)
)
</code></pre>
<p>As far I understand it, it should fail on the call <code>f(3)</code>, however it doesn't. Can someone shed some light on this behaviour?</p>
| <p>No checking is performed by Python itself. This is specified in the <a href="https://www.python.org/dev/peps/pep-0484/#non-goals" rel="nofollow">"Non- Goals" section</a> of PEP 484. When executed (i.e during run-time), Python completely ignores the annotations you provided and evaluates your statements as it usually does, dynamically.</p>
<p>If you need type checking, you should perform it yourself. This can currently be performed by static type checking tools like <a href="http://mypy.readthedocs.io/en/latest/" rel="nofollow"><code>mypy</code></a>.</p>
|
AngularJS UI Router and search <p>I've built a small search app using AngularJS, UI Router and Elasticsearch. I have 2 templates that share 1 controller. Everything works correctly ... except for for when I try to implement query parameters.</p>
<p>The one template is a simple hp to enter search query or select from autocomplete (UI Bootstrap Typeahead). The other template is for search results and more searching (search box and area to display search results).</p>
<p>My states look like this:</p>
<pre><code>.state('query', {//home
url: '/',
templateUrl: 'search/query.html',
controller: 'searchCtrl as vm'
})
.state('search', {//results
url: '/search?q',
templateUrl: 'search/search.html',
controller: 'searchCtrl as vm'
});
</code></pre>
<p>I'm using $state.go (in searchCtrl) from UI Router to transition between states.</p>
<pre><code>vm.search = function() {
$state.go('search', {q: vm.searchTerms});
...
</code></pre>
<p>What's happening is that after you enter your query/select autocomplete it goes to the 'search' state but I see this is in the url </p>
<pre><code>http://localhost:8000/app/#/search?q=%5Bobject%20Object%5D
</code></pre>
<p>Then I have to enter the query again and the url changes to</p>
<pre><code>http://localhost:8000/app/#/search?q=userinput
</code></pre>
<p>Finally I have to enter the query yet again for search to execute. Obviously I want all this to happen with ONE search submission. What am I doing wrong?</p>
<p>Any suggestions or ideas?</p>
<p><strong>UPDATE</strong>
I have this in a separate run.js file</p>
<pre><code>.run(['$rootScope', '$state', '$stateParams', function($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
</code></pre>
<hr>
<p><strong>UPDATE 2</strong>
I'm getting the same error whether I use my code or your code. It seems to be that when I go from 'state' to 'state', that searchTerms is being reset due to the way <a href="http://stackoverflow.com/questions/27696612/how-do-i-share-scope-data-between-states-in-angularjs-ui-router">$scope works in Angular</a>. I'm not sure how to resolve that yet because I'm not sure if the solution provided there will work with <code>controllerAs</code> syntax. Would it be wiser to just have an <code>autocompleteCtrl</code> for the hp/query page and have a queryService injected into each controller for <code>searchTerms</code>? Pls give a bit more time to fork the codepen, will send you comment when done.</p>
| <p>You should use a $stateParams as follows:</p>
<pre><code>.state('search', {//results
url: '/search/:q',
templateUrl: 'search/search.html',
controller: 'searchCtrl as vm'
});
</code></pre>
<p>Then in your controller you can inject <code>$stateParams</code> and access the value of that parameter with <code>$stateParams.q</code>.</p>
<p>Hope this helps.</p>
|
Using d3-tip with npm: "Uncaught TypeError: Cannot read property 'node' of undefined"? <p>I've installed <code>d3": "^3.5.17"</code> and <code>"d3-tip": "^0.7.1"</code> using npm (<a href="https://www.npmjs.com/package/d3-tip" rel="nofollow">d3-tip documentation</a>). Then in my <code>index.js</code> file I have this code:</p>
<pre><code>var d3 = require('d3');
var d3tip = require('d3-tip')(d3);
console.log('d3 version', d3.version);
var tip = d3tip().attr('class', 'd3-tip').html(function(d) { return "hello world"; })
</code></pre>
<p>But when I build the index file with browserify and load it in the browser, I see an error from the <code>var tip</code> line:</p>
<pre><code>index.js:247 Uncaught TypeError: Cannot read property 'node' of undefined
</code></pre>
<p>This is coming from this function in the d3-tip source code:</p>
<pre><code>function getSVGNode(el) {
el = el.node()
if(el.tagName.toLowerCase() === 'svg')
return el
return el.ownerSVGElement
}
</code></pre>
<p>It looks like this function is expecting a node to be passed to it? But where would this come from? </p>
<p>The build itself does not throw any errors, and I think I'm requiring d3-tip correctly, <a href="http://stackoverflow.com/questions/35067167/d3-tip-npm-module-not-working-with-browserify">as per this question</a>. The console statement shows d3 version 3.5.17, as expected.</p>
<p>UPDATE: Here's my <code>package.json</code> file:</p>
<pre><code>{
"name": "myapp",
"version": "1.0.0",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "watchify index.js -o main.js --debug --verbose",
"build": "browserify index.js | uglifyjs > main.min.js"
},
"dependencies": {
"d3": "^3.5.17",
"d3-tip": "^0.7.1",
"datatables.net": "^1.10.12",
"datatables.net-bs": "^1.10.12"
},
"devDependencies": {
"uglifyjs": "^2.4.10",
"watchify": "^3.2.1"
}
}
</code></pre>
<p>And I installed the files with <code>npm install</code>. </p>
| <p>Your line</p>
<pre><code>var tip = d3tip().attr('class', 'd3-tip').html(function(d) { return "hello world"; })
</code></pre>
<p>must be</p>
<pre><code>var tip = d3.tip().attr('class', 'd3-tip').html(function(d) { return "hello world"; })
</code></pre>
<p>You can check my implementation @:</p>
<p><a href="https://github.com/davcs86/d3-polytree-graph/blob/master/lib/SimpleNetwork.js#L333" rel="nofollow">Source</a> (Lines: 17, 91, 333-339, 685-692)</p>
<p><a href="https://jsfiddle.net/davcs86/yywby23u/3/" rel="nofollow">Demo</a></p>
|
How to remove file while installation/uninstallation? <p>I have created a MSI installer using InstallShield. I want to remove some files while upgrade/installation/uninstallation. How can I achieve this ?</p>
| <p>There is one in-built CustomAction in InstallShield, RemoveFiles. This CA removes all files while uninstallation. But if we want to remove some files while fresh installation or while upgrade installation then we can use FileRemove table. <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa371201(v=vs.85).aspx" rel="nofollow">RemoveFile table</a> can explain all the fields of it. </p>
<p>In InstallShield, you can access this table from Additional Tools->Direct Editor->RemoveFile. In this table you need to add entry of a file that we want to be remove.</p>
|
Node http.request () : the relationship with var ClientRequest and callbackFn <p>I am a newbie to Node.js . </p>
<p>And I am trying to further explore Node.js API .</p>
<p>I referred and wrote a crawler and the code works. </p>
<p>I have successfully post the comment to the website.</p>
<p>But I am confused with the execution order with return class - clientRequest and </p>
<p>callbackFn .</p>
<pre><code>var req = http.request(urlRequest,function(res){
console.log("Status: "+res.statusCode);
console.log("headers: "+JSON.stringify(res.headers));
res.on("data",function(chunk){
console.log(Buffer.isBuffer(chunk));
console.log(typeof chunk);
});
res.on("end",function(){
console.log("comment successï¼");
});
});
req.on('error',function(e) {
console.log("Error :"+e.message);
});
req.write(postData);
req.end();
</code></pre>
<p>My original understanding for the steps are as below :</p>
<p>1) <code>http.request(urlRequest</code></p>
<p>2) <code>function(res)</code> </p>
<p>3) And last return the clientRequest-class <code>var req</code></p>
<p>But from the code , it seems my understanding is wrong . </p>
<p>It should be clientRequest-class-object <code>var req</code> 'write' the comments and </p>
<p>take it 'end' and then trigger the callbackFn <code>function(res)</code> .</p>
<p>Pls sharing your opinions and tell me more about this API.</p>
<p>Thanks & Best regard.</p>
| <p>It seems the asynchronous nature of http.request may be causing your confusion. </p>
<p>Basically, the request call will be made - this takes some time. Meanwhile JS will move onto req.write() etc.</p>
<p>You should look into EventEmitters, you are already using them technically inside of the request callback (eg. <code>res.on("data",function(chunk)</code>). </p>
<p>Perhaps a better move would be to put the calls outside of the request into another callback function which you then call inside of the request. This will cause it to be called at the end of the request - as signaled by the "end" emitter:</p>
<pre><code>res.on("end",function(){
console.log("comment successï¼");
requestWrite();
});
function requestWrite(){
req.write(postData);
req.end();
}
</code></pre>
|
How can i read and modify a json file in scala spark play <p>I want to read a JSON file and create a class/object that saved all label and value from every JSON's vector/record. Then I want to modify some values (or the JSON structure) and get this modified JSON file to Http request with play/spark/scala.</p>
<p>So how can I fill my class's variables with the json's values? </p>
<p>For example, I have this JSON file </p>
<pre><code> [
{
"ser": 345,
"City": "New York",
"Gen": 1
},
{
"ser": 55,
"City": "New York",
"Gen": 2
},
{
"ser": 19,
"City": "New York",
"Gen": 3
}
]
</code></pre>
<p>My goal is create a class like this </p>
<pre><code>class Book(ser:Integer, city:String, Gen:Integer)
{
//TODO
}
</code></pre>
<p>That takes every value of ser, city and gen, from the json for all the records in the file.
Than I want to modify the structure or values of the json, save and answer with the new file to a Http request.</p>
| <p>Assuming you have this class</p>
<pre><code>case class Book(ser: Int, city: String, gen: Int)
</code></pre>
<p>you can perform the JSON conversion using Play's JSON serialization/deserialization by implementing a formatter: </p>
<pre><code>implicit val bookFormat: Format[Book] = {
((JsPath \ "ser").format[Int] and
(JsPath \ "City").format[String] and
(JsPath \ "Gen").format[Int]
) (Book.apply, unlift(Book.unapply))
}
// returns a sequence of Book objects
val books = Json.parse(bookJson).as[Seq[Book]]
// modify your books...
(...)
// convert back to Json
val json = Json.toJson(books)
</code></pre>
|
How to Store Array Data Using Laravel foreach with ORM <p>create_team_social_icons_table.php</p>
<pre><code> $table->increments('id');
$table->integer('order_id');
$table->integer('team_id');
$table->integer('social_class');
$table->string('link');
</code></pre>
<p>Hello,
I have two different array from create form social_class[] and link[]. Trying to record values from a form using the form at one time.</p>
<pre><code><select name="social_class[]">
<select name="social_class[]">
<select name="social_class[]">
<select name="link[]">
<select name="link[]">
<select name="link[]">
</code></pre>
<p>I received an error message:</p>
<p>preg_replace(): Parameter mismatch, pattern is a string while replacement is an array.</p>
<pre><code> $social_class = Input::get('social_class');
$link = Input::get('link');
foreach ($social_class as $socialClass) {
$tsi = new TeamSocialIcon();
$tsi->order_id = 0;
$tsi->team_id = $insertedId;
$tsi->social_class = $socialClass;
$tsi->link = $link;
$tsi->save();
}
</code></pre>
| <p>Try converting the array into string using explode method. You should also change the column data type to string or varchar for the data to be successfully saved. While retrieving the data you can convert the string back into array using implode method.</p>
|
VS2015 indentation inside line <p>I am using Visual Studio 2015 and develop in C++.<br>
I need VS2015 autoformatting so I can not turn it off, but there is a problem.<br>
I usually write like this:</p>
<pre><code> LPSTR lpszOneLongLine = NULL;
DWORD dwShort = 0;
</code></pre>
<p>But VS2015 does not like this style and corrects it to:</p>
<pre><code> LPSTR lpszOneLongLine = NULL;
DWORD dwShort = 0;
</code></pre>
<p>How can I disable this behaviour?</p>
| <p>You can disable this behavior from settings:</p>
<p>Tools >> Options >> Text Editor >> C/C++ >> Formatting >> Spacing >> Assignment Operator >> Check Don't change spacing around assignment operators</p>
<p><a href="https://i.stack.imgur.com/MKTIb.png" rel="nofollow"><img src="https://i.stack.imgur.com/MKTIb.png" alt="enter image description here"></a></p>
|
Query filter object only working once - extbase 6.2 <p>In my extbase repository I've built a similar query function as described in this tutorial: <a href="https://docs.typo3.org/typo3cms/ExtbaseFluidBook/6-Persistence/3-implement-individual-database-queries.html" rel="nofollow">this</a> and it was using a filter object, <code>$demand</code>.<br>
So I created a class for my filter as well in order to work with an object in fluid. </p>
<p>It works, but only once - I can change something, click on "Filter" and it works.<br>
But if I change something again and click on "Filter" it jumps back to the previous values and nothing changes.</p>
<p>I feel like this might have something to do with caching, but I'm not sure.<br>
When I debug the filter object it doesn't show my the debug code after the second click on "Filter" because that's what it does when nothing has changed I noticed.</p>
<p><strong>What can I do to change my filter settings as many times as I want?</strong></p>
<p>My filter class:</p>
<pre><code>class AppointmentFilter extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity {
/**
* future
*
* @var int
*/
protected $future = 1;
/**
* booked
*
* @var int
*/
protected $booked = 2;
/**
* student
*
* @var \vendor\extension\Domain\Model\Student
*/
protected $student = NULL;
/**
* expertise
*
* @var \vendor\extension\Domain\Model\Expertise
*/
protected $expertise = NULL;
function getFuture() {
return $this->future;
}
function getBooked() {
return $this->booked;
}
function getStudent() {
return $this->student;
}
function getExpertise() {
return $this->expertise;
}
function setFuture($future) {
$this->future = $future;
}
function setBooked($booked = NULL) {
$this->booked = $booked;
}
function setStudent(\vendor\extension\Domain\Model\Student $student = NULL) {
$this->student = $student;
}
function setExpertise(\vendor\extension\Domain\Model\Expertise $expertise = NULL) {
$this->expertise = $expertise;
}
}
</code></pre>
<p>And the corresponding fluid form:</p>
<pre><code><f:form action="list" name="appointmentFilter"
class="filter-form"
object="{appointmentFilter}"
arguments="{students:students,expertises:expertises}">
Termine:
<label>
<f:form.radio property="future" value="1"/> Bevorstehende
<f:form.radio property="future" value="0"/> Vergangene
</label>
<label>
<f:form.radio property="booked" value="2"/> Alle
<f:form.radio property="booked" value="1"/> Gebuchte
<f:form.radio property="booked" value="0"/> Freie
</label>
<label>
Studenten:
<f:form.select property="student" options="{students}" optionLabelField="fullName" prependOptionLabel="Alle Studenten" class="filterSelect" />
</label>
<label>
Expertise:
<f:form.select property="expertise" options="{expertises}" optionLabelField="name" prependOptionLabel="Alle" class="filterSelect" />
</label>
<f:form.submit value="Filter anwenden" class="rm-with-js" />
</f:form>
</code></pre>
| <p>According to your description this is a caching problem. You can set your action to be noncachable by adding it in the second array in the plugin configuration in the localconf.php. Example:</p>
<pre><code>\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
$_EXTKEY,
'Pi1',
array(
'Controller' => 'list, cachedAction',
),
// this is the array for noncachable actions
array(
'Controller' => 'list',
)
);
</code></pre>
|
Simulate click event on react element <p>I'm trying to simulate a <code>.click()</code> <code>event</code> on a <a href="https://facebook.github.io/react/" rel="nofollow">React</a> element but I can't figure out why it is not working (It's not reacting when I'm firing the <code>event</code>).</p>
<p>I would like to post a Facebook comment using only JavaScript but I'm stuck at the first step (do a <code>.click()</code> on <code>div[class="UFIInputContainer"]</code> element).</p>
<p>My code is:</p>
<pre><code>document.querySelector('div[class="UFIInputContainer"]').click();
</code></pre>
<p>And here's the URL where I'm trying to do it: <a href="https://www.facebook.com/plugins/feedback.php?api_key=516792821822250&channel_url=https%3A%2F%2Fstaticxx.facebook.com%2Fconnect%2Fxd_arbiter%2Fr%2FP5DLcu0KGJB.js%3Fversion%3D42%23cb%3Df32e78989ee3c64%26domain%3Dproductodelasemana.top%26origin%3Dhttps%253A%252F%252Fproductodelasemana.top%252Ff21b47c88d96f0c%26relation%3Dparent.parent&colorscheme=light&href=https%3A%2F%2Fproductodelasemana.top&locale=en_US&numposts=5&sdk=joey&skin=light&version=v2.8&width=100%25#" rel="nofollow"><strong>https://www.facebook.com/plugins/feedback.php...</strong></a></p>
<p>P.S. I'm not experienced with React and I don't know really if this is technically possible. It's possible?</p>
<p>EDIT: I'm trying to do this from <code>Chrome DevTools Console</code>.</p>
| <p>Use <code>refs</code> to get the element in the callback function and trigger a click using <code>click()</code> function.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Example extends React.Component{
simulateClick(e) {
e.click()
}
render(){
return <div className="UFIInputContainer"
ref={this.simulateClick} onClick={()=> console.log('clicked')}>
hello
</div>
}
}
ReactDOM.render(<Example/>, document.getElementById('app'))</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div></code></pre>
</div>
</div>
</p>
|
IdentityServer4 Password Grant <p>I've stood up an instance of identityserver4, an API project, and a UI. </p>
<p>The workflow is as follows: </p>
<ol>
<li>User visits the UI.</li>
<li>User provides user name and password to UI.</li>
<li>UI sends credentials to back of web app, which uses a password grant to authenticate the user with IdentityServer4.</li>
<li>IdentityServer4 returns a token.</li>
<li>Token is used to identify who the user is to the UI and that the user has access to certain sections of the site.</li>
<li>When the user needs to do something within the site, the token is passed to the API via bearer auth. </li>
</ol>
<p>The password grant isn't negotiable, as this is a first party app and it makes no sense to redirect the user away from the main site. </p>
<p>What's the proper set of middleware to use for this? Should I just use a CookieAuthenticationMiddleware and attach the token as a claim? I'll need to access the claims from HttpContext.User claims. Do I need to use IdentityMiddleware?</p>
| <p>You can request identity scopes using the password grant type and use the userinfo endpoint to resolve them to claims - like in this sample:</p>
<p><a href="https://github.com/IdentityServer/IdentityServer4.Samples/tree/dev/Clients/src/ConsoleResourceOwnerFlowUserInfo" rel="nofollow">https://github.com/IdentityServer/IdentityServer4.Samples/tree/dev/Clients/src/ConsoleResourceOwnerFlowUserInfo</a></p>
<p>And yes - you can use the cookie middleware to persist those claims and the access token for later usage.</p>
|
Need help restricting a js function(that restricts invalid chars) to a particular input type <p>Hi i would like to restrict a function that allows only, numbers, back space and left & right arrow keys to inputs with number type, because when i implement it, it also affects my text inputs.</p>
<pre><code><script>
function chars(evt){
var key = window.event ? event.keyCode : event.which;
if (event.keyCode == 8 || event.keyCode == 46
|| event.keyCode == 37 || event.keyCode == 39) {
return true;
}
else if ( key < 48 || key > 57 ) {
return false;
}
else return true;
}
</script>
</code></pre>
| <p>Assign an <strong>id</strong> to your <code><input></code>. Add an <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener" rel="nofollow">event listener</a> to it, like :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function getKeyCode() {
var key = window.event ? event.keyCode : event.which;
if(event.keyCode == 8 || event.keyCode == 46
|| event.keyCode == 37 || event.keyCode == 39) {
console.log(true);
//return true;
} else if (key < 48 || key > 57) {
console.log(false);
// return false;
} else {
console.log(true);
// return true;
}
}
var el = document.getElementById("myInput");
el.addEventListener("keypress", getKeyCode);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="myInput"></code></pre>
</div>
</div>
</p>
|
How can I extend an abstract class with an optional member in Scala? <p>I have an abstract base class, Foo, whose constructor I'd like to have an optional parameter. If none is provided, I'll just give it a <code>None</code> value.</p>
<p>A source Foo will not have parents, so I'd just like to construct them without a list of parents (leave default value for parent list)</p>
<p>A derived Foo might have provided parents, so I'd like to mimic the signature of the Foo base class.</p>
<p>Below is my attempt:</p>
<pre><code>abstract class Foo(val id: String, var parentIds: Option[List[String]]=None) { }
case class SourceFoo(override val id: String)
extends Foo(id, parentIds=None) { }
case class DerivedFoo(override val id: String,
override var parentIds: Option[List[String]])
extends Foo(id, parentIds) { }
</code></pre>
<p>I'm getting a compiler error that a mutable variable cannot be overridden (referencing the <code>parentIds</code> in the <code>DerivedFoo</code> constructor.</p>
<p>This list is subject to change, so I don't want to make it a <code>val</code> (which removes my compiler issues).</p>
<p>This is a very basic OO issue, so it must be simpler than I seem to be making it. How can I achieve my desired behavior idiomatically?</p>
| <p>I managed to fix this after reading the <a href="http://docs.scala-lang.org/tutorials/tour/case-classes.html" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>The constructor parameters of case classes are treated as public values and can be accessed directly.</p>
</blockquote>
<p>Since my base class is abstract, I can simply extend it with default, <code>val</code> construction.</p>
<p>I simply need to specify that <code>parentIds</code> is a var in the DerivedFoo constructor.</p>
<pre><code>abstract class Foo(id: String, parentIds: Option[List[String]]=None) { }
case class SourceFoo(id: String) extends Foo(id) { }
case class DerivedFoo(id: String, var parentIds: Option[List[String]]=None)
extends Foo(id, parentIds) { }
</code></pre>
|
Custom JFR Java mission control events <p>I would like to emit custom events in jmc -I've came across the blog post about jfr custom events - <a href="http://hirt.se/blog/?p=444" rel="nofollow">http://hirt.se/blog/?p=444</a> . The author however stressed that this feature may be depracted in the future. Since the jmc is not open source I am unable to check it.
Is the information in the blogpost still up to date?</p>
| <p>At JavaOne September 2016, the blog poster mentioned that there will be a supported Flight Recorder API in JDK 9, and that the unsupported API now available in JDK 8 will be removed. He also showed a slide with this text before his presentation:</p>
<p>"The following is intended to outline our general product direction. It is intended for informational purposes only, and may not be included in any contract. It is not a commitment to deliver any material code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle's products remains at the sole discretion of Oracle."</p>
|
Return Label Text From Form Field <p>I've been trying to have my eventLabel value equal my Gravity Form label. Currently my code is pulling the 'name' attribute from the input field of my form. However, I'm looking to pull the label text prior to the span element.</p>
<pre><code><li id="field_38_1" class="gfield gfield_contains_required field_sublabel_below field_description_below">
<label class="gfield_label" for="input_38_1">
"Name"
<span class="gfield_required">*</span>
</label>
<div class="ginput_container">
<input name="input_1" id="input_38_1" type="text" value="" class="medium" tabindex="1002">
</div>
</li>
</code></pre>
<p>I've tried this and it hasn't worked. It only returns [object Object]. Thoughts?</p>
<pre><code>dataLayer.push({'eventCategory': 'Form - ' +
$(this).closest('form').attr('action'),
'eventAction': 'completed',
'eventLabel': $(this).parents('li').find('label'),
'event': 'gaEvent'});
</code></pre>
| <p>Modify </p>
<pre><code>$(this).parents('li').find('label')
</code></pre>
<p>to</p>
<pre><code>$(this).parents('li').find('label').text()
</code></pre>
|
resolve NLog instance with unity container <p>I have the following class:</p>
<pre><code> public class TestInjection
{
private ILogger logger;
public TestInjection(ILogger logger)
{
this.logger = logger;
}
public void Process()
{
try
{
int zero = 0;
int result = 5 / zero;
}
catch (DivideByZeroException ex)
{
logger.Log(LogLevel.Error, "test message", ex);
Console.WriteLine("logged message from class");
}
}
}
</code></pre>
<p>And in my <code>Program.cs</code> I have the code:</p>
<pre><code> IUnityContainer container = new UnityContainer();
container.RegisterType<TestInjection>();
var myTestClass = container.Resolve<TestInjection>(new ResolverOverride[] { new ParameterOverride("logger", LogManager.GetCurrentClassLogger()) });
myTestClass.Process();
</code></pre>
<p>How to resolve <code>LogManager.GetCurrentClassLogger()</code> with the unity container, if the default constructor of the <code>Logger</code> class it's not accessible? </p>
<p>Thanks.</p>
<p>PS: This is my first experience with DI and Unity.</p>
| <p>Here is how I've done:</p>
<pre><code> IUnityContainer container = new UnityContainer();
container.RegisterType<ILogger>( new InjectionFactory(l => LogManager.GetCurrentClassLogger()));
container.RegisterType<TestInjection>();
var myTestClass = container.Resolve<TestInjection>(new ResolverOverride[] { new ParameterOverride("logger", container.Resolve<ILogger>()) });
myTestClass.Process();
</code></pre>
|
joining two tables and avoid duplicate rows <p>I am stuck with below logic in sql server.</p>
<p>Table 1:</p>
<pre><code>ID Requestid
1 0001
2 0004
3 0004
1 0005
</code></pre>
<p>Table 2 </p>
<pre><code>parentID Requestid Age
1 0001 29
2 0004 30
3 0004 34
1 0005 27
</code></pre>
<p>query:</p>
<pre><code>select * from table1 t1
join table t2
on t2.parentid =t1.id
</code></pre>
<p>When I join these tables, I am getting below result</p>
<pre><code>ID requestid age
1 0001 29
1 0005 29
2 0004 30
3 0004 34
1 0001 27
1 0005 27
</code></pre>
<p>I want below result:</p>
<pre><code>ID requestid age
1 0001 29
1 0005 27
2 0004 30
3 0004 34
</code></pre>
<p>I know it is simple and i am missing something.
Any help is appreciated!</p>
| <pre><code>select ID, requestid, age from table1 t1
inner join table t2
on t2.parentid =t1.id AND t2.requestId = t1.requestId
ORDER BY ID
</code></pre>
<p>OR</p>
<pre><code>select ID, requestid, age from table1 t1,table t2
where t2.parentid =t1.id AND t2.requestId = t1.requestId
ORDER BY ID
</code></pre>
|
Docusign api php add signer on the fly to template <p>when i add new recepient and sent the document in template using below code</p>
<pre><code>$templateRole = new \DocuSign\eSign\Model\TemplateRole();
$templateRole->setEmail("user@email.com");
$templateRole->setName("User Name");
$templateRole->setRoleName("Admin");
</code></pre>
<p>I use <a href="https://github.com/docusign/docusign-php-client" rel="nofollow">Docusign Php Client</a>, you can find the whole code below I used for this on that page.</p>
<p>Here it send the email containing document to user@email.com, but user@email.com's user is not able to sign that document.</p>
<p>I've also added the dynamic text to the document in the template.Added one signer recipient to template (because i was not able to add the dynamic labels without it), <strong>this user get all the emails</strong> even i don't specify him on the above code.</p>
<p>I want something like to send a document in template to different recepients (like user1@gmail.com, user2@gmail.com etc) one at a time (they may or may not have docusign account, though is it possible if they have docusign account?)</p>
<p>I am doing this since 4 days, not finding anything about proceeding furthur, please help.</p>
| <p>I have read some of the documentation. As far as I can see you should do the following:</p>
<pre><code>//first signer
$templateRole1 = new \DocuSign\eSign\Model\TemplateRole();
$templateRole1->setEmail("user1@email.com");
$templateRole1->setName("User1 Name");
$templateRole1->setRoleName("Admin");
//second singer
$templateRole2 = new \DocuSign\eSign\Model\TemplateRole();
$templateRole2->setEmail("user2@email.com");
$templateRole2->setName("User2 Name");
$templateRole2->setRoleName("Admin");
</code></pre>
<p>And then in the envelop:</p>
<pre><code>$envelop_definition->setTemplateRoles(array($templateRole1, $templateRole2));
</code></pre>
|
Cannot debug tensorflow using gdb on macOS <p>I am trying to debug TensorFlow using GDB on macOS Sierra. I followed the instructions on the <a href="https://gist.github.com/Mistobaan/738e76c3a5bb1f9bcc52e2809a23a7a1#run-python-test" rel="nofollow">post</a>.After I installed developer version of tensorflow for debug I tried to use gdb to attach a python session.</p>
<p>When I run <code>gdb -p <pid></code>:</p>
<pre><code>GNU gdb (GDB) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin16.0.0".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word".
Attaching to process 18822
Reading symbols from /Users/dtong/.virtualenvs/tensorflow/bin/python3.5...(no debugging symbols found)...done.
warning: unhandled dyld version (15)
0x00007fffc4d83f4e in ?? ()
(gdb)
</code></pre>
<p>When I set the breakpoint:</p>
<pre><code>(gdb) break TF_NewSession
Function "TF_NewSession" not defined.
Make breakpoint pending on future shared library load? (y or [n]) y
Breakpoint 1 (TF_NewSession) pending.
</code></pre>
<p>Then even I run <code>sess = tf.Session()</code> as the post says. GDB will never enter into breakpoint.</p>
| <p>Well, after I change to use <code>lldb</code> on macOS, everything works fine. So I guess the solution to this problem is "USING LLDB INSTEAD OF GDB".</p>
|
Show current location in google map programmatically android <p>I can get current location manually but I want to get it programmatically in android app. I am using <code>LocationListener</code> and <code>LocationManager</code> but I am not getting current location on map. My code is given below, anybody can guide me how can I do that?</p>
<pre><code>package com.example.nabia.myapplication;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
public class FindNearbyMosque extends AppCompatActivity implements LocationListener, OnMapReadyCallback {
MapView gMapView;
GoogleMap gMap = null;
double latitude;
double longitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_nearby_mosque);
LocationManager myManager;
myManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
myManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
gMapView = (MapView)findViewById(R.id.map);
gMapView.getMapAsync(this);
gMapView.onCreate(savedInstanceState);
gMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(this.getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onMapReady(GoogleMap map) {
gMap = map;
gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
@Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
gMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude) , 14.0f) );
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
</code></pre>
| <p>I have solved my problem by connecting <code>LocationServices</code>through <code>GoogleApiClient()</code> as you can see in below code.</p>
<pre><code>public class FindNearbyMosque extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
GoogleMap mMap;
double lat;
double lng;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (servicesOK()) {
setContentView(R.layout.activity_map);
if (initMap()) {
Toast.makeText(this, "Ready to map!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Map not available!", Toast.LENGTH_SHORT).show();
}
} else {
setContentView(R.layout.activity_find_nearby_mosque);
}
}
private boolean servicesOK() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int isAvailable = googleAPI.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
} else if (googleAPI.isUserResolvableError(isAvailable)) {
Dialog dialog = googleAPI.getErrorDialog(this, isAvailable, GPS_ERRORDIALOG_REQUEST);
dialog.show();
} else {
Toast.makeText(this, "Can't connect to google play services", Toast.LENGTH_SHORT).show();
}
return false;
}
private boolean initMap() {
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return (true);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = mLastLocation.getLatitude();
lng = mLastLocation.getLongitude();
LatLng loc = new LatLng(lat, lng);
CameraUpdate center=
CameraUpdateFactory.newLatLng(loc);
CameraUpdate zoom=CameraUpdateFactory.newLatLngZoom(loc,14);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}
</code></pre>
|
Enhancements for text classification using word vectors <p>I am using word vectors for text classification solution. I am using word vectors mainly to address the case of synonyms which are not there in the training set but will be present in the actual use-cases. By simply using word vectors, I am not getting a good enough accuracy in prediction. Can anyone please suggest some enhancements I can do over word vectors in order to improve accuracy?</p>
| <ul>
<li><p>Debug your bad prediction cases. Will good quality of embedding of synonyms (of those in the training dataset) help at all?</p></li>
<li><p>Use a different embedding that is trained with larger vocabulary, with similar content as your application, etc.</p></li>
<li><p>Get more training data (labeled dataset). This should help a lot. Text classification usually have a very large space of features.</p></li>
<li><p>Allow "trainable" of your embedding layer when training your text classifier. Don't be confused with the word2vec training, which is to get a pre-learned embedding for your embedding layer and it could use a large amount of unlabeled data. Here you are using a relatively smaller dataset containing only labeled data. Allow the embedding layer to be "trainable" means that gradient could be back-propagated from the output layer to the embedding layer to fine-tune the embedding vectors.</p></li>
</ul>
|
VBA userform to execute selections only after hitting command button <p>I am having a hard time to make vba to execute my selection only after pressing the command button (The GO button in this case). Attached are the picture of the userform, which is not made by activeX control, and the code I am working on. Thanks!</p>
<p><a href="https://i.stack.imgur.com/puzQD.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/puzQD.jpg" alt="Picture of Userform"></a></p>
<pre><code>Private Sub MR_Click()
If MR.Value = True Then
Rows(6).Delete
End If
End Sub
Private Sub PMS_Click()
If PMS.Value = True Then
Rows(7).Delete
End If
End Sub
Private Sub VOIDMR_Click()
If VOIDMR.Value = True Then
Rows(13).Delete
End If
End Sub
Private Sub VOIDPMS_Click()
If VOIDPMS.Value = True Then
Rows(14).Delete
End If
End Sub
</code></pre>
| <p>Like this, using a "Go" button's <code>_Click</code> event procedure (presumably <code>GO_Click()</code>, but modify if needed) to check against each of the checkboxes and do the deletion accordingly.</p>
<pre><code>Private Sub GO_Click()
If MR.Value = True Then
Rows(6).Delete
End If
If PMS.Value = True Then
Rows(7).Delete
End If
If VOIDMR.Value = True Then
Rows(13).Delete
End If
If VOIDPMS.Value = True Then
Rows(14).Delete
End If
End Sub
'These event procedures won't do anything, and can be removed:
Private Sub MR_Click()
End Sub
Private Sub PMS_Click()
End Sub
Private Sub VOIDMR_Click()
End Sub
Private Sub VOIDPMS_Click()
End Sub
</code></pre>
<p>The checkboxes' <code>_Click</code> event procedures are no longer needed. </p>
<p>To note about the event procedures, they will fire whenever the event occurs. So for an checkbox with a <code>_Click</code> event, any time the user checks (or unchecks) <code>_Click</code> handler will execute. </p>
<p>As noted, exercise caution when deleting elements from a collection, as this typically needs to be done in reverse order (when you delete row 6, row 7 becomes row 6, so if both MR and PMS are checked, what's in Row 7 initially will not be deleted). This may require some additional code change, but very simply it seems by just re-ordering the commands within <code>GO_Click</code>, should handle this:</p>
<pre><code>Private Sub GO_Click()
If VOIDPMS.Value = True Then
Rows(14).Delete
End If
If VOIDMR.Value = True Then
Rows(13).Delete
End If
If PMS.Value = True Then
Rows(7).Delete
End If
If MR.Value = True Then
Rows(6).Delete
End If
End Sub
</code></pre>
|
Login with twitter in android studio using Fragment activity <p>I have not found any tutorials or links for login with twitter in the android studio. Please give me any reference to for the twitter login using the fragment.</p>
| <p>Integrate <a href="http://fabric.io" rel="nofollow">Fabric</a> in your Android Studio and twitter kit which will help you login via Twitter in your app</p>
|
SQL Query to get a substring between [ ] in a string with multiple parentheses <p>I have a column with text string named "Formula", where variables are coded with IDs and set into parentheses, text in parentheses can vary in length, the number of such parentheses is virtually unlimited. Data examples:</p>
<ul>
<li><code>[a=5;b=1;c=15]</code></li>
<li><code>[x=1;a=5;b=1;c=15]*[a=4;c=2]</code></li>
<li><code>=IF([a=10232937;c=227634]=1;[a=2;b=51;d=14]*[a=1;b=51;d=14];0)</code></li>
</ul>
<p>I look for a specific combination of <code>a</code> and <code>b</code>, say:</p>
<pre><code>Select Formula FROM Table WHERE Formula LIKE "%a=5%c=2%"
</code></pre>
<p>Result will be <code>[x=1;a=5;b=1;c=15]*[a=4;c=2]</code>although <code>a=5</code> and <code>c=2</code> are located in different parentheses in this case and the desired result is actually a null.</p>
<p>Any ideas on how to look within any given parentheses?</p>
<p>UPD: It's SQL Server 2014</p>
| <p>A simple Parse/Split function can help here</p>
<pre><code>Declare @YourTable table (ID int, Formula varchar(max))
Insert Into @YourTable values
(1,'[a=5;b=1;c=15]'),
(2,'[x=1;a=5;b=1;c=15]*[a=4;c=2]'),
(3,'=IF([a=10232937;c=227634]=1;[a=2;b=51;d=14]*[a=1;b=51;d=14];0')
Select Distinct A.*
From @YourTable A
Cross Apply [dbo].[udf-Str-Parse](A.Formula,']') B
Where RetVal Like '%a=5%c=2%'
</code></pre>
<p><strong>Returns NO DATA</strong></p>
<p><strong>While</strong> <code>Where RetVal Like '%a=1%c=2%'</code></p>
<p><strong>Returns</strong></p>
<pre><code>ID Formula
3 =IF([a=10232937;c=227634]=1;[a=2;b=51;d=14]*[a=1;b=51;d=14];0
</code></pre>
<p>The UDF if needed (logic can also be ported into the Cross Apply if you can't use a UDF)</p>
<pre><code>CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table
As
Return (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>'+ Replace(@String,@Delimiter,'</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
);
</code></pre>
|
Adding Image to Sqlite -android- <p><strong>How can i add image to sqlite database and then retrieve ? using Content Provider</strong>
<a href="https://i.stack.imgur.com/3HItU.png" rel="nofollow"><img src="https://i.stack.imgur.com/3HItU.png" alt="enter image description here"></a></p>
<p>*i want to get this image that i loaded from gallery of taken by camera to be stored in the database to use it in another activities *</p>
| <p>You could save the path to the image in the databse. Then in next activity, retrieve it and if the file exists display it...</p>
<p>When user selected image from gallery, i guess you get the URI from <code>onActivityResult()</code>. You just need to get the path to it using a code like this one : </p>
<pre><code>private String getRealPathFromURI(Uri contentUri) {
String[] store = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, store, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
if (cursor != null ) {
cursor.close();
}
return result;
}
</code></pre>
<p>Just save the path in your database the way you want. </p>
<p>Later on, try to get the file. If file exists, update your <code>ImageView</code> </p>
<pre><code>File file = new File(savedPath);
if(file.exists){
// load image in your imageView
Bitmap mBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
yourImageView.setImageBitmap(mBitmap);
}
</code></pre>
|
php.net manual not make sense of class Scope Resolution Operator :: <p>trying to learn php and caught on another snagg</p>
<p><strong>Ok this is what they are saying on php.net below about the ::</strong></p>
<p>The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.</p>
<p>As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static). </p>
<p>When referencing these items from outside the class definition, use the name of the class. </p>
<pre><code>class MyClass {
const CONST_VALUE = 'A constant value';
}
$classname = 'MyClass';
echo $classname::CONST_VALUE;
echo MyClass::CONST_VALUE;
?>
</code></pre>
<p><strong>now back to the above code</strong></p>
<pre><code>$classname = 'MyClass';
</code></pre>
<p>THAT IS A VARIABLE ! BEING GIVEN A 'STRING' VALUE OF 'MyClass'!</p>
<pre><code>echo $classname::CONST_VALUE;
</code></pre>
<p>SO HOW IS THIS LINE EVEN POSSIBLE! IT HAS NOTHING TO DO WITH THAT CLASS!</p>
<p>THAT IS BASICALLY A SIMPLE VARIABLE WITH A STRING VARIABLE!
SO HOW DOES IT MAGICALLY GET THE POWER TO ACCESS THAT CLASS CONSTANT WITH ::?
ONLY THING SIMILAR I SEE IS THE STRING 'MyClass' buts in theory has no power to let that happen its just a string.</p>
<p>can someone explain because im having 100 snags a day im starting to think php was just made up as they went along its too many contradictory things in it.</p>
| <p>In this case these two lines are basically the same. </p>
<pre><code>echo $classname::CONST_VALUE;
echo MyClass::CONST_VALUE;
</code></pre>
<p>PHP tries to "cast" the string <code>"MyClass"</code> to a Class. If the class exists everything works like a charm.</p>
<p>Other example could be:</p>
<pre><code>$instance = new $classname;
</code></pre>
<p>where <code>$instance</code> is a valid instance of <code>MyClass</code>.</p>
<p>In other words you can replace class name with its string representation.</p>
|
Python HTML source code <p>I would like to write a script that picks a special point from the source code and returns it. (print it)</p>
<pre><code>import urllib.request
Webseite = "http://myip.is/"
html_code = urllib.request.urlopen(Webseite)
print(html_code.read().decode('ISO-8859-1'))
</code></pre>
<p>This is my current code.
I would like to print only the IP address that the website gives.
The input of this I will print in python (title="copy ip address").</p>
| <p>You could use <a href="http://jsonip.com" rel="nofollow">jsonip</a> which returns a JSON object that you can easily parse using standard Python library</p>
<pre><code>import json
from urllib2 import urlopen
my_ip = json.load(urlopen('http://jsonip.com'))['ip']
</code></pre>
|
Overwrite VS Code snippet with user defined snippet <p>I have configured the following TypeScript snippet in Visual Studio Code</p>
<p><code>
"console.log": {
"prefix": "cl",
"body": [
"console.log();"
],
"description": "console.log()"
}
</code></p>
<p>It doesn't work however, because there is already a snippet defined for <code>cl</code> (class). How can I overwrite that snippet with mine? I'd like to use <code>cl</code>, because I have other IDEs configured the same way and would prefer not change my convention.</p>
| <p>When you type <code>cl</code> a list of all the possible expansions of the cl snippet is shown and your snippet is probably around the bottom of the list. In order to access the snippet at the top of the list you can added the following to your <code>settings.json</code></p>
<pre><code>// Place your settings in this file to overwrite the default settings
{
"typescript.useCodeSnippetsOnMethodSuggest": true,
"editor.snippetSuggestions": "top",
"editor.tabCompletion": true
}
</code></pre>
<p>Here notice the <code>editor.snippetSuggestions</code>. This is the setting which defines the sorting of the autocomplete list which appears when you type your snippet's abbreviation. By default it is <code>bottom</code> which is why your snippet appears at the end of the list. </p>
|
TCP Server doesn't receive data correctly <p>The below code has a TCP client in C and TCP Server in Qt C++. My problem is that I am using TCP for reliability, but it has data losses (not packet). In my main code, if I run tcp client to send data, TCP server receives only one packet. if I add <code>sleep(1);</code> to the client between each packet transfer, then TCP server receives data. Both client and server runs on the same computer.</p>
<p>To simplify the question and can't put too huge code here, I have the below code that performs faster, but it losses last 10-15 bytes of the packet.</p>
<p><strong>TCP C client</strong></p>
<p><strong>main.c</strong></p>
<pre><code>#include "socket_handler.h" //I didn't put the all includes here
#define PORT 22208
//tcp server
int main(void)
{
int sockfd;
uint32_t senderAddress = 2130706433; //127.0.0.1
if( connect_to_server_w_uint( &sockfd, senderAddress, PORT ) < 0 ){
printf("error at line 454\n");
exit(1);
}
char data[] = "124b00068c158f$321$52712304$13.212779$0$O$0$0$b4$1$0$3$0$0$0$0$11$0$7$0$1$fe$f1$aaa9fffffffffd80$2132b00$eb460b5e$1$1$2016-02-22 03:01:00$0000-00-00 00:00:00$321$24754$321$13132$1$98$0$5.1$0$3c$64$1$96$4d$3e8$38$2$46$dc$4$3$f6$e6$17$0$e6$d3$1$0$e6$d3$2$0£";
char buffer[512];
int i=0;
for(i=0; i<1000; i++){
bzero(buffer, 512);
sprintf(buffer, "%d***%s -----",i,data);
send_data_to_server(&sockfd, buffer, strlen(data) +1 );
printf("[%d]: data is sent\n", i);
}
close_connection(&sockfd);
return 0;
}
</code></pre>
<p><strong>socket_handler.c</strong></p>
<pre><code>int connect_to_server(int *sockfd , struct in_addr senderAddress, uint16_t destPort){
struct sockaddr_in serv_addr;
*sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (*sockfd < 0)
//error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr = senderAddress;
serv_addr.sin_port = htons(destPort);
if (connect( *sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0){
printf("connection error line 1413\n");
close( *sockfd );
return -1;
}
return 0;
}
int connect_to_server_w_uint(int *sockfd, uint32_t senderAddress, uint16_t destPort){
struct sockaddr_in serv_addr;
*sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (*sockfd < 0){
printf("ERROR opening socket");
close(*sockfd);
return -1;
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(senderAddress);
serv_addr.sin_port = htons(destPort);
if (connect(*sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
{
printf("ERROR connecting");
close(*sockfd);
return -1;
}
return 0;
}
int send_data_to_server(int *sockfd, char *message, uint16_t msgLength){
int n = write(*sockfd, message, msgLength);
if (n < 0){
printf("ERROR writing to socket");
return -1;
}
return 0;
}
int close_connection(int *sockfd){
close( *sockfd );
return 0;
}
</code></pre>
<p><strong>Qt C++ TCP Server</strong></p>
<p><strong>MainWindow.cpp</strong></p>
<pre><code>class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void ParseThePacket(QByteArray data);
private:
Ui::MainWindow *ui;
Server *server;
};
</code></pre>
<p><strong>Client.h</strong></p>
<pre><code>class Client : public QObject
{
Q_OBJECT
public:
explicit Client(QObject *parent = 0);
public slots:
bool connectToHost(QString host);
bool writeData(QByteArray data);
private:
QTcpSocket *socket;
};
</code></pre>
<p><strong>Server.cpp</strong></p>
<pre><code>Server::Server(QObject *parent) : QObject(parent)
{
server = new QTcpServer(this);
connect(server, SIGNAL(newConnection()), this, SLOT(newConnection()));
if( server->listen(QHostAddress::Any, PORT) ){
qDebug() << "tcp server started!";
}else{
qDebug() << "tcp server couldn't start listening";
}
}
void Server::newConnection()
{
qDebug() << "new connection";
while (server->hasPendingConnections())
{
socket = server->nextPendingConnection();
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
}
}
void Server::disconnected()
{
qDebug() << "disconnected";
socket->deleteLater();
}
void Server::readyRead()
{
qDebug() << "readyRead";
QByteArray buffer = socket->readAll();
emit dataReceived(buffer);
}
</code></pre>
<p>Here is an example output from the TCP server(the end of qDebug() output):</p>
<blockquote>
<blockquote>
<p>00:00:00$321$24754$321$13132$1$98$0$5.1$0$3c$64$1$96$4d$3e8$38$2$46$dc$4$3$f6$e6$17$0$e6$d3$1$0$e6$d3$996***124b00068c158f$321$52712304$13.212779$0$O$0$0$b4$1$0$3$0$0$0$0$11$0$7$0$1$fe$f1$aaa9fffffffffd80$2132b00$eb460b5e$1$1$2016-02-22
03:01:00$0000-00-00
00:00:00$321$24754$321$13132$1$98$0$5.1$0$3c$64$1$96$4d$3e8$38$2$46$dc$4$3$f6$e6$17$0$e6$d3$1$0$e6$d3$997***124b00068c158f$321$52712304$13.212779$0$O$0$0$b4$1$0$3$0$0$0$0$11$0$7$0$1$fe$f1$aaa9fffffffffd80$2132b00$eb460b5e$1$1$2016-02-22
03:01:00$0000-00-00
00:00:00$321$24754$321$13132$1$98$0$5.1$0$3c$64$1$96$4d$3e8$38$2$46$dc$4$3$f6$e6$17$0$e6$d3$1$0$e6$d3$998***124b00068c158f$321$52712304$13.212779$0$O$0$0$b4$1$0$3$0$0$0$0$11$0$7$0$1$fe$f1$aaa9fffffffffd80$2132b00$eb460b5e$1$1$2016-02-22
03:01:00$0000-00-00
00:00:00$321$24754$321$13132$1$98$0$5.1$0$3c$64$1$96$4d$3e8$38$2$46$dc$4$3$f6$e6$17$0$e6$d3$1$0$e6$d3$999***124b00068c158f$321$52712304$13.212779$0$O$0$0$b4$1$0$3$0$0$0$0$11$0$7$0$1$fe$f1$aaa9fffffffffd80$2132b00$eb460b5e$1$1$2016-02-22
03:01:00$0000-00-00
00:00:00$321$24754$321$13132$1$98$0$5.1$0$3c$64$1$96$4d$3e8$38$2$46$dc$4$3$f6$e6$17$0$e6$d3$1$0$e6$d3$"
disconnected</p>
</blockquote>
</blockquote>
<p><strong>Question 1</strong>
Comparing to the original message, it misses "1$0$e6$d3$2$0£" part of the (14 byte) sent data. What is the reason of the missing message? How to fix the code that the TCP server receives the complete data.</p>
<p><strong>Question 2</strong>
As I mentioned in the beginning that I am using the same code as a part of a large code and TCP server receives packets when I put <strong>sleep(1)</strong> between each packet transmission (otherwise it receives only the first packet). What is the reason of it and how to solve it? </p>
<p>I observed the packet transmission on Wireshark that all the TCP packets are sent successfully, but it seems like the receive part has an issue.</p>
<p>I am using Ubuntu 15.04, kernel 3.19.0-69-generic, gcc version 4.9.2 </p>
| <pre><code>int n = write(*sockfd, message, msgLength);
if (n < 0){
</code></pre>
<p>You are only checking that <code>write()</code> did not return a negative value, indicating an error.</p>
<p>However, a <code>write()</code> to a socket does not guarantee that all requested bytes will be written. <code>write()</code> on a socket may return a positive value, fewer than <code>msgLength</code> here, indicating that fewer than the requested bytes have been written. This is documented, in detail, in <code>write()</code>'s manual page.</p>
<p>You are ignoring this possibility, and that's the likely reason you're missing your data. It's up to you to figure out what to do, in this case. The usual approach is to simply go back and attempt to write the remaining bytes (which, again, may not be written in their entirety).</p>
<p>Similarly, when reading from a socket, you are not guaranteed that everything that was written to the socket, by the sender, will be read in one gulp. It is up to you to verify that your reader has read everything that there is to read, and if the reader expects more data, continue reading from the socket until it is received.</p>
|
How can I resolve this build error when adding facebook sdk <p>I keep getting the BUILD FAILED in Android studio and I have resolved other similar error before but this one is hard. Basically what i do is adding the <a href="https://github.com/firebase/quickstart-android/tree/master/auth/app/src/main/java/com/google/firebase/quickstart/auth" rel="nofollow">quickstart-android-auth</a> to an existing working Android project.</p>
<p>Everything worked until i adding the <strong>quickstart-android-auth</strong> files and independents.</p>
<blockquote>
<p>Error:Execution failed for task ':app:processDebugManifest'.</p>
<blockquote>
<p>Manifest merger failed : uses-sdk:minSdkVersion 14 cannot be smaller than version 15 declared in library
[com.facebook.android:facebook-android-sdk:4.16.0]
D:\AndroidStudioProjects\Nogget\app\build\intermediates\exploded-aar\com.facebook.android\facebook-android-sdk\4.16.0\AndroidManifest.xml
Suggestion: use tools:overrideLibrary="com.facebook" to force usage</p>
</blockquote>
</blockquote>
<p>And here is my Build.gradle</p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion '24.0.2'
dexOptions {
dexInProcess = true
}
defaultConfig {
applicationId "com.port.android"
minSdkVersion 14
targetSdkVersion 24
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
repositories {
maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
mavenCentral()
}
packagingOptions{
exclude 'META-INF/LICENSE'
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.volley:volley:1.0.0'
compile 'com.android.support:support-compat:24.2.0'
compile 'com.google.android.gms:play-services:9.6.0'
compile 'com.android.support:support-v13:24.2.0'
compile "com.google.firebase:firebase-messaging:9.0.0"
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
compile 'com.google.code.gson:gson:2.4'
compile 'com.android.support:design:24.2.0'
compile 'de.hdodenhof:circleimageview:1.3.0'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.android.support:percent:24.2.0'
compile 'me.grantland:autofittextview:0.2.+'
compile 'com.google.firebase:firebase-auth:9.2.1'
compile 'com.google.firebase:firebase-messaging:9.2.1'
compile 'com.google.android.gms:play-services-appinvite:9.6.0'
compile 'com.google.firebase:firebase-analytics:9.2.1'
compile 'com.google.firebase:firebase-crash:9.6.0'
compile 'com.google.android.gms:play-services-ads:9.6.0'
compile 'com.github.bmelnychuk:atv:1.2.+'
compile 'com.github.johnkil.print:print:1.2.2'
testCompile 'junit:junit:4.12'
compile 'com.seatgeek:placesautocomplete:0.2-SNAPSHOT'
compile 'com.fasterxml.jackson.core:jackson-core:2.7.2'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.2'
compile 'com.fasterxml.jackson.core:jackson-databind:2.7.2'
compile 'com.facebook.android:facebook-android-sdk:4.16.0'
compile('com.twitter.sdk.android:twitter-core:1.6.6@aar') {
transitive = true
}
compile('com.twitter.sdk.android:twitter:1.13.1@aar') {
transitive = true;
}
}
apply plugin: 'com.google.gms.google-services'
</code></pre>
| <p>As the error says, your minSDK is 14 but the latest FacebookSDK requires mins SDK 15. Increasing your minSDK should resolve your issue</p>
|
python os.walk and unicode error <p>two questions:
1. why does </p>
<pre><code>In [21]:
....: for root, dir, file in os.walk(spath):
....: print(root)
</code></pre>
<p>print the whole tree but</p>
<pre><code>In [6]: for dirs in os.walk(spath):
...: print(dirs)
</code></pre>
<p>chokes on this unicode error?</p>
<pre><code>UnicodeEncodeError: 'charmap' codec can't encode character '\u2122' in position 1477: character maps to <undefined>
</code></pre>
<p>[NOTE: this is the TM symbol]</p>
<ol start="2">
<li>I looked at these answers</li>
</ol>
<p><a href="http://stackoverflow.com/questions/22184178/scraping-works-well-until-i-get-this-error-ascii-codec-cant-encode-character">Scraping works well until I get this error: 'ascii' codec can't encode character u'\u2122' in position</a></p>
<p><a href="http://stackoverflow.com/questions/30539882/whats-the-deal-with-python-3-4-unicode-different-languages-and-windows/30551552#30551552">What's the deal with Python 3.4, Unicode, different languages and Windows?</a></p>
<p><a href="http://stackoverflow.com/questions/16346914/python-3-2-unicodeencodeerror-charmap-codec-cant-encode-character-u2013-i?noredirect=1&lq=1">python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined></a></p>
<p><a href="https://github.com/Drekin/win-unicode-console" rel="nofollow">https://github.com/Drekin/win-unicode-console</a></p>
<p><a href="https://docs.python.org/3/search.html?q=IncrementalDecoder&check_keywords=yes&area=default" rel="nofollow">https://docs.python.org/3/search.html?q=IncrementalDecoder&check_keywords=yes&area=default</a></p>
<p>and tried these variations</p>
<pre><code>----> 1 print(dirs, encoding='utf-8')
TypeError: 'encoding' is an invalid keyword argument for this function
In [11]: >>> u'\u2122'.encode('ascii', 'ignore')
Out[11]: b''
print(dirs).encode(âutf=8â)
</code></pre>
<p>all to no effect.</p>
<p>This was done with python 3.4.3 and visual studio code 1.6.1 on Windows 10. The default settings in Visual Studio Code include:</p>
<blockquote>
<p>// The default character set encoding to use when reading and writing
files.
"files.encoding": "utf8",</p>
</blockquote>
<p>python 3.4.3
visual studio code 1.6.1
ipython 3.0.0</p>
<p><strong>UPDATE EDIT</strong>
I tried this again in the Sublime Text REPL, running a script. Here's what I got:</p>
<pre><code># -*- coding: utf-8 -*-
import os
spath = 'C:/Users/Semantic/Documents/Align'
with open('os_walk4_align.txt', 'w') as f:
for path, dirs, filenames in os.walk(spath):
print(path, dirs, filenames, file=f)
Traceback (most recent call last):
File "listdir_test1.py", line 8, in <module>
print(path, dirs, filenames, file=f)
File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2605' in position 300: character maps to <undefined>
</code></pre>
<p>This code is only 217 characters long, so where does âposition 300â come from?</p>
| <p>Here's a test case:</p>
<pre><code>C:\TEST
ââââdir1
â file1â¢
â
ââââdir2
file2
</code></pre>
<p>Here's a script (Python 3.x):</p>
<pre><code>import os
spath = r'c:\test'
for root,dirs,files in os.walk(spath):
print(root)
for dirs in os.walk(spath):
print(dirs)
</code></pre>
<p>Here's the output, on an IDE that supports UTF-8 (PythonWin, in this case):</p>
<pre><code>c:\test
c:\test\dir1
c:\test\dir2
('c:\\test', ['dir1', 'dir2'], [])
('c:\\test\\dir1', [], ['file1â¢'])
('c:\\test\\dir2', [], ['file2'])
</code></pre>
<p>Here's the output, on my Windows console, which defaults to <code>cp437</code>:</p>
<pre><code>c:\test
c:\test\dir1
c:\test\dir2
('c:\\test', ['dir1', 'dir2'], [])
Traceback (most recent call last):
File "C:\test.py", line 9, in <module>
print(dirs)
File "C:\Python33\lib\encodings\cp437.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2122' in position 47: character maps to <undefined>
</code></pre>
<p>For Question 1, the reason <code>print(root)</code> works is that no directory had a character that wasn't supported by the output encoding, but <code>print(dirs)</code> is now printing a tuple containing <code>(root,dirs,files)</code> and one of the files has an unsupported character in the Windows console.</p>
<p>For Question 2, the first example misspelled <code>utf-8</code> as <code>utf=8</code>, and the second example didn't declare an encoding for the file the output was written to, so it used a default that didn't support the character.</p>
<p>Try this:</p>
<pre><code>import os
spath = r'c:\test'
with open('os_walk4_align.txt', 'w', encoding='utf8') as f:
for path, dirs, filenames in os.walk(spath):
print(path, dirs, filenames, file=f)
</code></pre>
<p>Content of <code>os_walk4_align.txt</code>, encoded in UTF-8:</p>
<pre><code>c:\test ['dir1', 'dir2'] []
c:\test\dir1 [] ['file1â¢']
c:\test\dir2 [] ['file2']
</code></pre>
|
Deserialize XML dateTime to UTC <p>I am consuming an XML webservice with XSD elements such as:</p>
<pre><code><xs:element nillable="true" type="xs:dateTime" name="ENDDATE"/>
</code></pre>
<p>XML might look like the following:</p>
<pre><code><ENDDATE>2016-08-01T18:35:49+04:00</ENDDATE>
</code></pre>
<p>I used XSD.exe to autogenerate C# classes, when I inspect these the <code>DateTime</code> object will contain the time in system-local time, with <code>Kind==Local</code>.</p>
<p>Is there a way I can force the DateTime instances to be in UTC time without manually hacking the auto-generated classes for every such field (there are rather a lot)?</p>
| <p>I think that you can't tune this behavior using XSD (see <a href="http://www.w3schools.com/xml/schema_dtypes_date.asp" rel="nofollow">here</a>).
So you should update(hack) auto-generated classes and do something like described <a href="http://stackoverflow.com/questions/3188933/prevent-timezone-conversion-on-deserialization-of-datetime-value">there</a>:</p>
<pre><code>[XmlIgnore()]
public DateTime Time { get; set; }
[XmlElement(ElementName = "Time")]
public string XmlTime
{
get { return XmlConvert.ToString(Time, XmlDateTimeSerializationMode.RoundtripKind); }
set { Time = DateTimeOffset.Parse(value).DateTime; }
}
</code></pre>
<p>Or, if you really often auto-generate those classes, you can introduce wrappers for them, which will transparently convert DateTime to UTC.</p>
|
The type or namespace name 'MovieTexture' could not be found.Are you missing a using directive or an assembly reference? <p>During this cause of executing my application, i'm encountering the </p>
<blockquote>
<p>error(CS0246)
error</p>
</blockquote>
<p>when i'm trying to build my game on unity using WebGL.Here's the code :</p>
<pre><code>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
[RequireComponent (typeof(AudioSource))]
public class videoplayer : MonoBehaviour {
private MovieTexture movie;
private AudioSource audio;
void Start () {
GetComponent<RawImage>().texture = movie as MovieTexture;
audio = GetComponent<AudioSource>();
audio.clip = movie.audioClip;
movie.Play ();
audio.Play();
}
void Update () {
}
}
</code></pre>
| <p>Okay I got the problem. Basically, the <code>movie</code> is declared and not assigned any value.That is why it is null.<br>
I think you have missed the name of the object whose texture property is used here</p>
<p><code>GetComponent<RawImage>().texture = movie as MovieTexture;</code>.</p>
<p>It should be like: </p>
<p><code>GetComponent<RawImage>()."THE NAME".texture = movie as MovieTexture;</code></p>
|
Shared preference value not reflecting in app <p>I am getting the saved value in shared preference but not being able to update TextView or ImageView on basis of the value in shared preference.</p>
<p>Here is my code for Shared Pref's class :</p>
<pre><code>public class SharedPref {
public SharedPref(Context context){
}
public void saveString(Context context,String key, String value) {
SharedPreferences sharedPref = context.getSharedPreferences(key,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, value);
editor.apply();
}
public String getString(Context context,String key){
SharedPreferences sharedPref = context.getSharedPreferences(key, Context.MODE_PRIVATE);
String value = sharedPref.getString(key, "");
return value;
}
}
</code></pre>
<p>Here is the code to save & retrieve value of preference :</p>
<pre><code>@Override
public void onNumberOfOversClick(String _overs) {
final SharedPref sharedPref = new SharedPref(MainActivity.this);
String local = sharedPref.getString(MainActivity.this,"overs");
// custom dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_overs_dialog);
dialog.setTitle("Choose Overs...");
TextView text_3 = (TextView) dialog.findViewById(R.id.text_3);
TextView text_5 = (TextView) dialog.findViewById(R.id.text_5);
final ImageView icon_tick_3 = (ImageView) dialog.findViewById(R.id.icon_tick_3);
final ImageView icon_tick_5 = (ImageView) dialog.findViewById(R.id.icon_tick_5);
if(local == "3" || local == "")
{
icon_tick_3.setImageResource(R.drawable.tick);
}
else if(local == "5")
{
icon_tick_5.setImageResource(R.drawable.tick);
}
dialog.show();
text_3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
icon_tick_3.setVisibility(View.VISIBLE);
icon_tick_3.setImageResource(R.drawable.tick);
icon_tick_5.setVisibility(View.INVISIBLE);
sharedPref.saveString(MainActivity.this, "overs", "3");
}
});
text_5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
icon_tick_3.setVisibility(View.INVISIBLE);
icon_tick_5.setVisibility(View.VISIBLE);
icon_tick_5.setImageResource(R.drawable.tick);
sharedPref.saveString(MainActivity.this, "overs", "5");
}
});
}
</code></pre>
<p>As you can see I am able to retrieve value in String variable local, but ImageView is not updated to R.drawable.tick when I re-open the app.</p>
| <p>String comparison the way you are working right now. You need to change equals statement into this</p>
<pre><code> if(local.equals("3") || local.equals(""))
{
icon_tick_3.setImageResource(R.drawable.tick);
}
</code></pre>
|
Loading videoclips in background layer with Actionscript 2 <p>I am trying to load videoclips (or images) into the background layer, based on the frame number, using the Actionscript 2 below, on Macromedia Flash 8 pro.</p>
<p>There are two layers; background and text layer. The script loads clips alright but it puts them in front of the text layer. The script is placed on frame 1 of background layer:-</p>
<p>What am I doing wrong here, please?</p>
<p>I am a newbie and got the script from some forums. I'd appreciate any help.. Thanks!</p>
<pre><code> mclListener.onLoadInit = function(target_mc:MovieClip) {};
this.createEmptyMovieClip("image_mc",1);
var mclListener:Object = new Object();
mclListener.onLoadInit = function(target_mc:MovieClip) {};
var image_mcl:MovieClipLoader = new MovieClipLoader();
image_mcl.addListener(mclListener);
// the first clip on frame 1
image_mcl.loadClip("movie1.swf", image_mc);
onEnterFrame = function () {
if (this._currentframe == 100) {
image_mcl.loadClip("movie2.swf", image_mc);
}
if (this._currentframe == 200) {
image_mcl.loadClip("movie3.swf", image_mc);
}
};
</code></pre>
| <p>I've found the solution to this. In the second line in the script:-</p>
<pre><code> this.createEmptyMovieClip("image_mc",1);
</code></pre>
<p>change 1 to -16384, like so:- </p>
<pre><code> this.createEmptyMovieClip("image_mc",-16384);
</code></pre>
<p>This might help someone still working on software from the stone-age -:)</p>
|
How do you import ngTagsInput into your project with AngularJS and Bootstrap? <p>How do you prevent this message while trying to use ngTagsInput? I tried to go to the module and put in:</p>
<pre><code>var app = angular.module("SinglePageApplication", [ "ngRoute", 'ui.bootstrap', 'ngTagsInput']);
</code></pre>
<p>However, this always throws the following error below.</p>
<pre><code>Uncaught Error: [$injector:modulerr] Failed to instantiate module SinglePageApplication due to:
Error: [$injector:modulerr] Failed to instantiate module ngTagsInput due to:
Error: [$injector:nomod] Module 'ngTagsInput' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.5.8/$injector/nomod?p0=ngTagsInput
</code></pre>
<p>Additionally, I trying to install it, using this <a href="http://mbenford.github.io/ngTagsInput/download" rel="nofollow">link</a> and calling the command:</p>
<pre><code>$ npm install ng-tags-input@3.1.1 --save
</code></pre>
<p>But this always throws the error:</p>
<pre><code>UNMET PEER DEPENDENCY grunt@1.0.1
âââ ng-tags-input@3.1.1
</code></pre>
<p>All I want is to be able to use the tags-input, however I feel I am missing something major to have all of these issue. I would really appreciate any help.</p>
| <p>I remember running into an issue with this and the fix/workaround I came up with was to copy the <code>ng-tags-input.js</code> locally and keep it within .git.</p>
<p>I had totally forgotten to check up on this, at the time there was a bug with any Angular >= 1.5. Can't recall the bug exactly but I think my issue was when hitting enter it would select one of items from the dropdown rather than submitting the input.</p>
|
How do I stop comments of a exe script executing from a .bat fie <p>I have a <code>.bat</code> file that runs a number of <code>.exe</code> scripts used recursively for a number of files and produces different result files.</p>
<p>But each <code>.exe</code> has some useless comments and processes running messages that pop up in my <code>cmd</code> window.</p>
<p>For example, a line in one of my scripts:</p>
<pre><code>for %F in ("*.fa") do "../program.exe" -input %F -output %~dpnF.fasta & copy %F + %~dpnF.fasta %dpnF.txt
</code></pre>
<p>When I run it, <code>program.exe</code> shows different comments and each ones' running information. </p>
<p>How can I stop those messages to pop up in my <code>cmd</code> prompt? </p>
| <p>You can redirect the messages of your batch file to a text file if you don't want to see them on cmd
For ex:</p>
<pre><code>C:\\>run.bat > d:\myfile.txt
</code></pre>
|
How to get dynamic content with script tag working in AngularJS? <p>I'm trying to integrate AngularJS to existing web application. Some of data in application is loaded dynamically via <code>$.ajax()</code> and <code>element.html(data)</code>. <code>data</code> can contain html code with javascript code in tag <code><script></code>. This code succesfully loaded by browser, but angular don't see it when I try call <code>$compile()</code>. How can I fix this?</p>
<p><a href="https://jsfiddle.net/indvd00m/k80q7of4/" rel="nofollow">JSFiddle</a></p>
<pre class="lang-html prettyprint-override"><code><div ng-app="app">
<div id='container'>
</div>
</div>
</code></pre>
<pre class="lang-js prettyprint-override"><code>var app = angular.module('app', []);
$(document).ready(function() {
var container = $('#container');
var html = '';
html += '<scripttag type="text/javascript">';
html += 'app.controller("TestController", function($scope) {$scope.testVar = "testVal"});';
html += 'console.log("Controller added");';
html += '</scripttag>';
html += '<b ng-controller="TestController">{{testVar}}</b>';
container.html(html.replace(/scripttag/g, 'script'));
angular.element(container).injector().invoke([ '$compile', function($compile) {
var $scope = angular.element(container).scope();
console.log("Compiling new element...");
$compile(container)($scope);
$scope.$apply();
} ]);
});
</code></pre>
<p>Console log:</p>
<pre><code>Controller added
Compiling new element...
Uncaught Error: [ng:areq] Argument 'TestController' is not a function, got undefined http://errors.angularjs.org/1.2.30/ng/areq?p0=TestController&p1=not%20a%20function%2C%20got%20undefined
</code></pre>
<p>PS <code>html.replace(/scripttag/g, 'script')</code> - is workaround, because of direct call of <code>html('<script></script>')</code> don't work in jsffidle.com.</p>
| <p>Ok, the problem, is that after your AngularJS application has been bootstrapped you can't define new controllers. <a href="https://www.bennadel.com/blog/2553-loading-angularjs-components-after-your-application-has-been-bootstrapped.htm" rel="nofollow">Description and solution</a>.</p>
<p>I fixed my example <a href="https://jsfiddle.net/indvd00m/8c3g1m6r/" rel="nofollow">here</a>.</p>
<pre><code> app.config(
function( $controllerProvider, $provide, $compileProvider ) {
app._controller = app.controller;
app._service = app.service;
app._factory = app.factory;
app._value = app.value;
app._directive = app.directive;
app.controller = function( name, constructor ) {
$controllerProvider.register( name, constructor );
return( this );
};
app.service = function( name, constructor ) {
$provide.service( name, constructor );
return( this );
};
app.factory = function( name, factory ) {
$provide.factory( name, factory );
return( this );
};
app.value = function( name, value ) {
$provide.value( name, value );
return( this );
};
app.directive = function( name, factory ) {
$compileProvider.directive( name, factory );
return( this );
};
}
);
</code></pre>
|
Mongoose select result based on value of items in database array <p>I have a schema field (prices) which is an array, usually with just 1 price but sometimes with a sale price listed as the second item in the array. </p>
<p>I'd like to be able to query this field and return the all the products, sorted from lowest to highest (and while I'm at it, use $gt and $lt to select by range).</p>
<p>But my challenge is dealing with the sale price, the second value in my array. I need to be able to sort by this price, and not the 1st price if there is in fact a sale price. I don't know how to say "if (prices[1]) { use prices[1] } in my mongoose query.</p>
<p><strong>UPDATE</strong></p>
<p>I'm able to get almost what I want using the query below.<br>
My problem is that when I place the bit where price.1 is false first ( the sections are demarcated by the $and) I only get results reflecting products <em>with</em> price.1. When I place the second one first, being that price.1 is true, I only get the opposite, products with <em>without</em> price.1.</p>
<p>Is mongoose only reading the second part of my query?</p>
<pre><code>Product.find({ $and:
[{"price.1": {$exists : false }},
{"price.0": {$gte : req.body.lower_price}},
{"price.0": {$lte : req.body.higher_price} }],
$and : [{"price.1": {$exists: true}},
{"price.1": {$gte : req.body.lower_price}},
{"price.1": {$lte : req.body.higher_price} }]})
.exec(function(err, products){
if(err){
console.log(err)
}
else{
res.send(products)
}
});
</code></pre>
| <pre><code>Model.find({$or :[{"price.1": {$exists: false}}, {"price.1": {$gt : 10}}]}) //get all documents where either second element of the price array doesn't exist OR if it does it's greater than 10
.sort("price.1") // asc. Docs without second element will come first. Use -price for desc
.exec(function(err, res){
if(err){
console.log(err)
}
else{
console.log(res)
}
});
</code></pre>
|
how to add image on plane using script unity <p>Here is my code to add a plane in unity but the problem is the octopus.jpg seems like not to work.</p>
<pre><code> GameObject my_plane;
my_plane = GameObject.CreatePrimitive (PrimitiveType.Plane);
my_plane.transform.Rotate (-90, 0, 0);
Texture my_img = (Texture)Resources.Load ("octopus.jpg");
my_plane.GetComponent<Renderer>().material.mainTexture = my_img;
</code></pre>
<p>suggestion please or help . Thank you .
my octopus.jpg is in the resources folder.</p>
| <p>It would be easier to create a public field in your class :</p>
<p>public Texture my_img;</p>
<p>and just drag the texture that you want to use.</p>
<p>In case you are not running that code in a monobehaviour, you need to have your image inside a folder called "Resources" inside the "Assets" folder.
<a href="https://docs.unity3d.com/ScriptReference/Resources.html" rel="nofollow">https://docs.unity3d.com/ScriptReference/Resources.html</a></p>
|
jQuery - setTimeout does not work <p>There is my script: <a href="https://jsfiddle.net/hcsofjaa/1/" rel="nofollow">https://jsfiddle.net/hcsofjaa/1/</a>
I want to change color of these cells every 2000ms one by one, but It seems the setTimeout function does not work properly. Does anybody know, where is the problem?</p>
<pre><code>$("#button").click(function(){
for (var i = $("span").length; i > 0; i--) {
setTimeout(function(){
$("span:nth-child("+i+")").css("background-color","blue");
}, 2000);
}
</code></pre>
| <p>1) <strong>$(function)</strong> is important - bind click event to element after it rendered.</p>
<p>2) <strong>2000 * i</strong> : button colors change in the gap of 2000 </p>
<pre><code>$(function(){
$("#button").click(function(){
$("span").each(function(i){
var e = this;
setTimeout(function(){
$(e).css("background-color","blue");
}, 2000 * i);
});
});
});
</code></pre>
|
Printing from an OrderedCollection in Smalltalk <p>I am fairly new to Smalltalk and I'm stuck on how to print elements from a stack. I have two classes, one which creates the stack using OrderedCollection, which works, and a second class (Object subclass). For the second class I have two instance variables name and weight(with set and get methods). I need to make two more methods print and printSpecial. Print output the name and weight to the Transcript on the same line using the get method from name but cannot use the get method from weight. PrintSpecial is similar to print but the weight must be < 100. I have tried doing print and printScpecial but cannot figure it out. Below is what I have so far. Any help would be appreciated.</p>
<pre><code>name: a
name := a
name
^name
print
[ Transcript
show: weight;
show: name;
cr ]
printSpecial
[ weight <= 100 ]
whileTrue: [ Transcript
show: weight;
show: name;
cr ]
</code></pre>
| <p>Both your <code>print</code> and <code>printSpecial</code> methods enclose their bodies in squared brackets. You should remove them. Try:</p>
<pre><code>print
Transcript
show: weight;
show: name;
cr
printSpecial
weight <= 100 ifTrue: [
Transcript
show: weight;
show: name;
cr]
</code></pre>
<p>Notice that in <code>printSpecial</code> I've replaced <code>whileTrue:</code> with <code>ifTrue:</code>. The reason is that you don't want to keep printing for ever if the <code>weight</code> happens to meet the condition.</p>
<p>Another thing I would suggest is to avoid repeating code. So, I would propose this:</p>
<pre><code>printSpecial
weight <= 100 ifTrue: [self print]
</code></pre>
<p>This way, if you later decide to improve <code>print</code> you won't have to copy the improvement to <code>printSpecial</code>.</p>
<p>Finally, you say you have a collection of these objects. Therefore you should have some way of enumerating them (e.g., via <code>do:</code>). Thus, if the actual request consisted in printing them all you should implement <code>print</code> and <code>printSpecial</code> in the elements' class and then implement the same messages in your <code>Stack</code> class.</p>
<pre><code>Stack >> print
collection do: [:elem | elem print]
Stack >> printSpecial
collection do: [:elem | elem printSpecial]
</code></pre>
<p>where I'm assuming that the instance variable that holds your elements is named <code>collection</code>.</p>
<p>Even better. You could implement <code>do:</code> in your <code>Stack</code> class and then use <code>self do:</code> instead of <code>collection do:</code> as I did above. Something on the lines of</p>
<pre><code>Stack >> do: aBlock
collection do: aBlock
</code></pre>
<p>and then</p>
<pre><code>Stack >> print
self do: [:elem | elem print]
Stack >> printSpecial
self do: [:elem | elem printSpecial]
</code></pre>
|
Python - Creating a text file converting Fahrenheit to Degrees <p>I'm new to Python and I've been given the task to create a program which uses a text file which contains figures in Fahrenheit, and then I need to change them into a text file which gives the figures in Degrees... Only problem is, I have no idea where to start.
Any advice?</p>
| <p>First you need to create a Python function to read from a text file.</p>
<p>Second, create a method to convert the degrees.
Third, you will create a method to write to the file the results.</p>
<p>This is a very broad question, and you can't expect to get the full working code.
So start your way from the first mission, and we'll be happy to help with more problem-specific problem.</p>
|
is there a way to add new feature to orientdb studio <p>is there a way i can add a new feature to the orientdb studio? I mean, I need to display a popup window with a timeline of events that each user has made in a frame of time, for now when we click on a node a set of features appeared to modify, see connections to the vertex and connection from the vertex. SO can I add a feature?</p>
| <p>You can make a feature request on <a href="https://github.com/orientechnologies/orientdb/issues" rel="nofollow">github</a>.</p>
|
Having Trouble Testing App On iPhone <p>Having a bit trouble testing my app on the iPhone. I just downloaded Xcode 8/Swift 3. I have already researched online various ways to test my app, since this is my first app to be tested on any device.</p>
<p>To my understanding, setting up a free account to test is doable. I have my account signed in and my device plugged in, so I went to Window -> Devices -> Install A New App. I go to click on my app, but the folder just opens and doesn't allow me to add my project (to even click on it). I also went under Product -> Destination and clicked on my device. Nothing appeared. I'm not sure what else to do in order to test my app on my device. Nothing seems to be working. </p>
| <p>Just build and run your app with your phone plugged into your computer, and your phone selected as the build target in Xcode. Command-R is the keyboard command that should do that. You don't have to manually install the app, as build and run will do that for you.</p>
|
How to copy AND add clipboard contents to text area <pre><code>var content = clipboardData.getData("Text");
document.forms["test"].elements["clipboard"].value = content;
}
</code></pre>
<p>I would like to copy the clipboard contents to a textarea and add it each time instead of replacing the text. I have no issues copying the stuff there just can't figure out how to add rather than replace. Prefer Javascript.</p>
| <p>try this script <a href="https://github.com/zenorocha/clipboard.js" rel="nofollow">clipboard.js</a></p>
<p>You can copy, cut, paste, use different settings ;)</p>
|
Read .json in template Ionic 2 and Angular 2 <p>Template cant read *ngFor="let git of user.ball" whats problem ???
how get array ball from json?? I am traing but its not works </p>
<p>my template</p>
<pre><code><div *ngSwitchCase="'userpage'">
<ion-card>
<ion-card-content>``
<ion-list no-lines>
<ion-item *ngFor="let profile of users">
<ion-avatar item-left>
<img [src]="profile.img">
</ion-avatar>
<h2>{{profile.name}}</h2>
<p>{{profile.about}}</p>
</ion-item>
</ion-list>
</ion-card-content>
</ion-card>
</div>
<!-- ÐÐ°Ð»Ð»Ñ Ð¸ ÐоÑÑÐ¸Ð¶ÐµÐ½Ð¸Ñ -->
<div *ngSwitchCase="'info2'">
<ion-card>
<ion-card-content>
<ion-item *ngFor="let git of user.ball">
<ion-icon name='planet' item-left></ion-icon>
{{git.name}}
<ion-note item-right>
{{git.score}}
</ion-note>
</ion-item>
</ion-card-content>
</ion-card>
</div>
</div>
</code></pre>
<p>.json This is my Api user from here i take ball array, but ionic cant read or i have mistake i dont know help pleace!!!</p>
<pre><code>[
{
"id": 1,
"name": "It Developer",
"img": "/assets/img/1_kanal.png",
"email": "example@example.ru",
"surname": "IT app",
"balls": "400",
"ball": [
{
"id": 1,
"name": "ÐкÑивноÑÑÑ",
"score": "100"
},
{
"id": 2,
"name": "ÐÐ¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ ÐомменÑаÑии",
"score": "150"
},{
"id": 3,
"name": "РепоÑÑ Ð² Ð¡Ð¾Ñ Ð¡ÐµÑÑ",
"score": "200"
},
{
"id": 4,
"name": "Ðайк",
"score": "50"
}
]
}
]
</code></pre>
| <p><strong>NOTE</strong> : The answer is regarding to this shown object only. answer may vary according to your json.</p>
<p>Let's say </p>
<pre><code>this.users = [
{
"id": 1,
"name": "It Developer",
"img": "/assets/img/1_kanal.png",
"email": "example@example.ru",
"surname": "IT app",
"balls": "400",
"ball": [
{
"id": 1,
"name": "ÐкÑивноÑÑÑ",
"score": "100"
},
{
"id": 2,
"name": "ÐÐ¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ ÐомменÑаÑии",
"score": "150"
},{
"id": 3,
"name": "РепоÑÑ Ð² Ð¡Ð¾Ñ Ð¡ÐµÑÑ",
"score": "200"
},
{
"id": 4,
"name": "Ðайк",
"score": "50"
}
]
}
]
</code></pre>
<p>To access <code>ball array</code>, you should do following,</p>
<pre><code><div *ngFor="let git of users[0].ball"> // user[0] refers to 0th element of users array.
{{git.id}}-{{git.name}}-{{git.scrore}}
</div>
</code></pre>
<p><strong>DEMO: <a href="https://plnkr.co/edit/WWbTRASJCuz8UMi18JP7?p=preview" rel="nofollow">https://plnkr.co/edit/WWbTRASJCuz8UMi18JP7?p=preview</a></strong></p>
|
Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? <p>so I'm on Python 3.5.2, I'm trying to install scrapy, it throws an error saying</p>
<blockquote>
<p>Failed building wheel for lxml <br> Could not find function
xmlCheckVersion in library libxml2. Is libxml2 installed?</p>
</blockquote>
<p>So I try installing lxml, it throws the same error. I try installing it from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml" rel="nofollow">Here</a>, it says:</p>
<blockquote>
<p>Could not find a version that satisfies the requirement
lxml-3.6.4-cp35-cp35m-win32 (from versions: ) No matching distribution
found for lxml-3.6.4-cp35-cp35m-win32</p>
</blockquote>
<p>I can install almost nothing with pip. I'm on a Windows 10 machine. Note that it works flawlessly on my ubunto machine.</p>
| <p>try this first</p>
<p>pip install lxml==3.6.0</p>
|
javascript arrays change together <p>Created second array = to first array and then performed 'shift' on second array and first array was affected also. See code below. I am expecting the secondArray to contain Larry and Moe after the shift and the firstArray to have the original three elements. After the shift, both arrays only have Larry and Moe as elements?</p>
<pre><code>var firstArray = ["Curly", "Larry", "Moe"]
var secondArray = firstArray;
var thirdArray = firstArray;
alert("This is first array " + firstArray + "<br>");
secondArray.shift();
alert("This is first array " + firstArray + "<br>");
alert("This is second array " + secondArray + "<br>");
alert("This is third array " + thirdArray + "<br>");
</code></pre>
| <p>Here <code>secondArray</code> & <code>thirdArray</code> refers to the same array as <code>firstArray</code> instead of a new independent array.</p>
<p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice" rel="nofollow"><strong>slice</strong></a> which will return a shallow copy of portion of array</p>
<pre><code>var firstArray = ["Curly", "Larry", "Moe"]
var secondArray = firstArray.slice();
var thirdArray = firstArray.slice();
alert("This is first array " + firstArray + "<br>");
secondArray.shift();
alert("This is first array " + firstArray + "<br>");
alert("This is second array " + secondArray + "<br>");
alert("This is third array " + thirdArray + "<br>");
</code></pre>
<p><a href="https://jsfiddle.net/2gk6qbLo/1/" rel="nofollow"><strong>DEMO</strong></a></p>
|
How do I set the scope in the Facebook ionic authentication provider? <p>I am using the facebook ionic authentication provider; <strong><em>where and how do I set my scope to ask the user for consent on the data my ionic app will be retrieving from his or her facebook profile?</em></strong></p>
<p>I am using this on the client side</p>
<pre><code>$ionicAuth.login('facebook',['public_profile','email,user_friends','user_posts','user_photos','user_videos']).then(function(response){
</code></pre>
<p>The facebook login screen comes up but after successful authentication, with facebook, the facebook consent page does not come up.</p>
<p>Therefore, the OAuth 2.0 token I get only grants me access to facebook's default access, not to the scope I need. However, on the server side when FacebookTemplate.java constructs an object with the token I get an exception.</p>
<p>On the server side I am using Facebook <code>facebook = new FacebookTemplate(token);</code></p>
<p>I tried with Apache Cordova but I get the same results.</p>
| <p>Try with <a href="http://coenraets.org/blog/2014/04/sociogram-angularjs-ionic-facebook/" rel="nofollow">OpenFb Angular JS</a></p>
<pre><code> OpenFB.login('email,public_profile,user_friends,user_website,user_work_history,user_about_me,user_education_history,publish_actions,user_posts,user_photos,user_birthday').then(
function (token) {
})
</code></pre>
<p>From that scope person who have some role in app get full access but for any other user you have to take permission from facebook. Go To app section /Review </p>
|
How to List Executable File Names In Powershell <p>I need to list all installed applications in windows. Using <code>powershell</code> and the following command, I can find out the name and some other details of the installed applications. </p>
<pre><code>Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\ * | Select-Object DisplayName
</code></pre>
<p>What I want is to also find out the <code>commandline</code> of the applications so that I can run the application using that <code>commandline</code>. So basically I need following informations-</p>
<ol>
<li>Name of the application</li>
<li>Command line of the application</li>
<li>Start an application using commandline</li>
</ol>
<p>What might be the possible solution for doing that?</p>
| <p>The installed program are located in other registry key:</p>
<pre><code> HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
</code></pre>
<p>The following script get all programs and the their commandline:</p>
<pre><code> $q="`""
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*" |
Where-Object {$_."(default)" -ne $null} |
Select-Object @{ expression={$_.PSChildName}; label='Program'} ,@{ expression={$q + $_."(default)" +$q}; label='CommandLine'}
</code></pre>
<p>Sample of output result:</p>
<pre><code> Program CommandLine
------- -----------
7zFM.exe "C:\Program Files (x86)\7-Zip\7zFM.exe"
AcroRd32.exe "C:\Program Files (x86)\Adobe\Reader 9.0\Reader\AcroRd32.exe"
excel.exe "C:\PROGRA~2\MICROS~1\Office12\EXCEL.EXE"
</code></pre>
|
Hi, I cant seem to print the results of a program that will compare three circles size using DrawingPanel <p>Hi beginner programer here I need help with printing the results for this program. I have already created a method to compare the circles radius, however I would like to include the color of the circles compared when I print the results, I however cant seem to be able to do that as shown by the (?). how can i print a different color?</p>
<p>ex: when i compare green and red
"The green circle is bigger than the red circle"
to when i compare green to blue
"The green circle is smaller than the blue circle"</p>
<pre><code> //class
// main method
//asked for input and stored values in variable for r1, x1, y1
g.setColor(Color.GREEN);
g.fillOval(x1-r1, y1-r1, r1*2, r1*2);
//asked for input and stored values in variable for r2, x2, y2
g.setColor(Color.RED);
g.fillOval(x2-r2, y2-r2, r2*2, r2*2);
//asked for input and stored values in variable for r3, x3, y3
g.setColor(Color.BLUE);
g.fillOval(x3-r3, y3-r3, r3*2, r3*2);
int compare = size(r1, r2);
result1(compare);
compare = size(r1, r3);
result1(compare);
compare = size(r2, r3);
result1(compare);
public static int size(int r1, int r2){
if(r1 < r2){
return -1;
}else if( r1 == r2){
return 0;
}else{
return 1;
}
}
public static void result1(int n){
if (n == -1){
System.out.println("The " + ? + "cirlce is smaller than the " + ? + "circle.");
}else if(n == 0){
System.out.println("The " + ? + "circle is the same size as the " + ? + "cirle.");
}else{
System.out.println("The " + ? + "circle is bigger than the " + ? + "circle");
}
</code></pre>
<p>Thanks for the help.</p>
| <p>Create a class circle, like</p>
<pre><code>public class MyCircle {
int radius;
Color color;
public MyCircle(int radius, Color color) {
this.radius = radius;
this.color = color;
}
//Getter Setter...
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
}
</code></pre>
<p>Create a method to get the color name as string</p>
<pre><code>public static String getColorAsName(MyCircle circle) {
String colorName = null;
if (circle.getColor().equals(Color.BLACK)) {
colorName = "BLACK";
} else if(circle.getColor().equals(Color.RED)) {
colorName = "RED";
}
...
return colorName;
}
</code></pre>
<p>Then create circle objects, like</p>
<pre><code>MyCircle c1 = new Circle(r1, Color.GREEN)
MyCircle c2 = new Circle(r2, Color.GREEN)
etc...
</code></pre>
<p>Using getter-setter you can update the attributes when needed.</p>
<p>Change method </p>
<pre><code>public static void result1(int n){
</code></pre>
<p>to</p>
<pre><code>public static void result1(int n, MyCircle firstCircle, MyCircle lastCircle){
if (n == -1){
System.out.println("The " + getColorAsName(firstCircle) + " cirlce is smaller than the " + getColorAsName(lastCircle) + " circle.");
...
</code></pre>
<p>and call <code>result1()</code> like:</p>
<pre><code>result1(compare, c1, c2);
...
</code></pre>
|
How are "Web Components" different from "jQueryUI"? <p>While developing our own UI component libraries for Web and Mobile which one is more preferable - web component or jQueryUI?</p>
| <blockquote>
<p>How are âWeb Componentsâ different from âjQueryUIâ?</p>
</blockquote>
<p>They are very different by nature:</p>
<ul>
<li><p>Web Components are a set of HTML and DOM standards implemented in modern browsers.</p></li>
<li><p>jQueryUI is a JS library which proposes some advanced UI controls.</p></li>
</ul>
<blockquote>
<p>While developing our own UI component libraries for Web and Mobile which one is more preferable?</p>
</blockquote>
<p>It... depends!</p>
<ul>
<li><p>If you have a team with jQuery skills, and you want to reuse lots of predefined controls, and build a cross-browser application, you could choose jQueryUI.</p></li>
<li><p>If performance is your main concern, if you don't want to rely on 3rd party library/framework, you may want to use native Web Components.</p></li>
<li><p>You can also use a mix: create Web Components that use internally jQueryUI controls.</p></li>
</ul>
|
Cannot pass bound value of select box to second polymer element <p>I'm very new to Polymer and am having quite a time making this work. I've spent a few days scanning the docs at Google and other questions posed here on SE. My problem is similar to this one:</p>
<p><a href="http://stackoverflow.com/questions/39918908/advanced-data-binding-in-polymer">advanced data binding in Polymer</a></p>
<p>But I can't seem to get my code to run even after trying to apply the answers to this question and others. I have two elements and I just want to pass the value of the {{selected}} binding from one (my-symptom): </p>
<pre><code><link rel="import" href="../bower_components/iron-selector/iron-selector.html">
<link rel="import" href="../bower_components/paper-listbox/paper-listbox.html">
<link rel="import" href="../bower_components/paper-item/paper-item.html">
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="shared-styles.html">
<dom-module id="my-symptom">
<template>
<style include="shared-styles">
:host {
display: block;
padding: 10px;
}
</style>
<iron-ajax
auto
url="../data/topic1/symptom1/data.json"
handle-as="json"
last-response="{{response}}"></iron-ajax>
<div class="card">
<div class="circle">2</div>
<h1>Causes</h1>
<p>Please select a <strong>Cause</strong> that you wish to troubleshoot from the list below.</p>
<paper-listbox attr-for-selected="data-key" selected="{{selected}}" id="causeSelect">
<template is="dom-repeat" items="{{response}}">
<paper-item data-key="{{item.solution}}"><a href="{{item.url}}">{{item.cause}}</a></paper-item>
</template>
</paper-listbox>
</template>
<script>
Polymer({
is: 'my-symptom',
properties: {
selected:{
type: String,
notify: true
}
}
});
</script>
</dom-module>
</code></pre>
<p>to the other (my-solution):</p>
<pre><code><link rel="import" href="../bower_components/iron-selector/iron-selector.html">
<link rel="import" href="../bower_components/paper-listbox/paper-listbox.html">
<link rel="import" href="../bower_components/paper-item/paper-item.html">
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="shared-styles.html">
<link rel="import" href="my-symptom.html">
<dom-module id="my-solution">
<template>
<style include="shared-styles">
:host {
display: block;
padding: 10px;
}
</style>
<div class="card">
<div class="circle">3</div>
<h1>Solutions</h1>
<p>Here is the <strong>Solution</strong> that corresponds to the cause you selected.</p>
<my-symptom selected="{{selected}}"></my-symptom>
</template>
<script>
Polymer({
is: 'my-solution'
});
</script>
</dom-module>
</code></pre>
<p>Within the first element, the code outputs the expected value for {{selected}}, if I set the binding to appear in that element. however, when I try to insert it into my-solution using the selected attribute, I get everything except the selected value from my-cause.</p>
<p>This seems like it should be really simple, but obviously there are many things I don't yet understand about Polymer. Thanks in advance for any help, it's greatly appreciated!</p>
| <p>I don't see any issue with your code except for the one's mentioned in comments(unbalanced div tag and missing iron-ajax). The only thing that i see is that you have not used/printed <code>selected</code> anywhere in your <code>my-solution</code>.
Below snippet contains your code where i've printed <code>selected</code> in <code>my-solution</code> and it's working as expected.</p>
<p>I've replaced iron-ajax call with hardcoded value for the sake of demo. This code will work fine even with ajax call </p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><base href="https://polygit.org/polymer+:master/components/">
<script src="webcomponentsjs/webcomponents-lite-min-js"></script>
<link rel="import" href="iron-selector/iron-selector.html">
<link rel="import" href="paper-listbox/paper-listbox.html">
<link rel="import" href="paper-item/paper-item.html">
<link rel="import" href="iron-ajax/iron-ajax.html">
<link rel="import" href="polymer/polymer.html">
<dom-module id="my-symptom">
<template>
<style>
:host {
display: block;
padding: 10px;
}
</style>
<!-- commenting for the sake of demo -->
<!-- <iron-ajax
auto
url="data/data.json"
handle-as="json"
last-response="{{response}}"></iron-ajax> -->
<div class="card">
<div class="circle">2</div>
<h1>Causes</h1>
<p>Please select a <strong>Cause</strong> that you wish to troubleshoot from the list below.</p>
<!-- binding paper-listbox's selected to my-symptom's selected -->
<paper-listbox attr-for-selected="data-key" selected="{{selected}}" id="causeSelect">
<template is="dom-repeat" items="{{response}}">
<paper-item data-key="{{item.solution}}">{{item.cause}}</paper-item>
</template>
</paper-listbox>
</div>
</template>
<script>
Polymer({
is: 'my-symptom',
properties: {
selected: {
type: String,
notify: true
},
response: {
type: Array,
value: function() {
return [{
"solution": "1",
"url": "1",
"cause": "1"
}, {
"solution": "2",
"url": "2",
"cause": "2"
}, {
"solution": "3",
"url": "3",
"cause": "3"
}]
}
}
}
});
</script>
</dom-module>
<link rel="import" href="iron-selector/iron-selector.html">
<link rel="import" href="paper-listbox/paper-listbox.html">
<link rel="import" href="paper-item/paper-item.html">
<link rel="import" href="polymer/polymer.html">
<dom-module id="my-solution">
<template>
<style>
:host {
display: block;
padding: 10px;
}
</style>
<div class="card">
<div class="circle">3</div>
<h1>Solutions</h1>
<p>Here is the <strong>Solution</strong> that corresponds to the cause you selected.</p>
<!-- binding my-symptom's selected to my-solution's selected -->
<my-symptom selected="{{selected}}"></my-symptom>
<!-- printing my-solution's selected. You can also read this value in js using this.selected -->
My Solution: {{selected}}
</div>
</template>
<script>
Polymer({
is: 'my-solution'
});
</script>
</dom-module>
<my-solution></my-solution></code></pre>
</div>
</div>
</p>
|
how to use rubyxl to access the first row <pre><code>workbook = RubyXL::Parser.parse(params[:file].path)
worksheet = workbook[0]
puts worksheet.sheet_data[0][0]
</code></pre>
<p>But I am getting this as output </p>
<pre><code><RubyXL::Cell(0,0): "0", datatype="s", style_index=1>
</code></pre>
<p>My excel sheet is of this form</p>
<pre><code> name coupon
gates gates1234
jobs jobs1234
</code></pre>
<p>I want to access rows one by one .. any help will be appreciated. </p>
<p>I also made a sample app for this post, if you want to run it .. </p>
<p><code>https://github.com/vamsipavanmahesh/example-excel-reader</code></p>
| <p><pre>worksheet.sheet_data[0]</pre> gives you a Ruby object representing the first row.</p>
<p><pre>worksheet.sheet_data[0][0]</pre> gives you a Ruby object representing the first cell on the first row. But to get the actual contents of that cell, you need <pre>worksheet.sheet_data[0][0].value</pre></p>
<p>The worksheet is organised as an array of cells. You have to deal with the cells one by one in each row, if you are processing the rows sequentially.</p>
|
Csharp with node.js and socket.io <p>I wanted to send data from csharp to a webpage live without having to reload or anything annoying like that so I decided to use Node.JS and socket.io</p>
<p>I am totally new to socket.io and node.js so correct me if this isnt how it works...<br><br>
1) I sent data from my Csharp application using the code below.</p>
<pre><code>using Quobject.SocketIoClientDotNet.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Plus.HabboHotel.Roleplay.Extra.SocketIO
{
public static class SocketIOManager
{
public static void SendMessage(string message)
{
var socket = IO.Socket("http://127.0.0.1:400");
socket.On(Quobject.SocketIoClientDotNet.Client.Socket.EVENT_CONNECT, () =>
{
socket.Emit("emu_msg", @"Hello from PlusEMU");
socket.Disconnect();
});
}
}
}
</code></pre>
<p>2) The Node.JS app.js picks it up</p>
<pre><code>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
});
io.on('emu_msg', function(socket){
console.log('emu message received?');
});
http.listen(400, function(){
console.log('listening on *:400');
});
</code></pre>
<p>Now on the node.js console I should be getting "emu message received" should I not? I am not receiving that<br><br>
Does anybody know why?</p>
<p>I do receive the 'a user connected' when visiting the webpage that uses the code below</p>
<pre><code><script>
var socket = io.connect('http://127.0.0.1:400');
socket.on('emu_msg', function(data) {
alert(data);
});
</script>
</code></pre>
<p>But when sending a message with csharp I don't get anything, not even the user connect message, am I missing something here? And I don't get the alert on the webpage when sending with csharp either.</p>
| <p>on the client you should be listening for the message on the socket. </p>
<pre><code>io.on('connection', function(socket){
console.log('a user connected');
socket.on('emu_msg', function(msg){
console.log('emu message received?');
});
});
</code></pre>
<p>see: <a href="http://socket.io/docs/server-api/#socket#emit(name:string[,-%E2%80%A6]):socket" rel="nofollow">here</a> for more information</p>
|
How do I make the combobox update? <pre><code># IMPORT MODULES -----------------------------------------------------------
from tkinter import *
from tkinter import Tk, StringVar, ttk
#---------------------------------------------------------------------------
# LISTS
</code></pre>
<p><strong>Here are the lists which are used in the comboboxes</strong></p>
<pre><code>BlankLines = ["------------"]
CarBrandModel = ["------------","Audi", "BMW", "Mercedes"]
AudiModels = ["------------", "A4", "A8", "Q7", "R8"]
#----------------------------------------------------------------------------------
#FUNCTIONS
def ModelSelectionFunction():
CarBrandModelSelected = Var1.get()
print(CarBrandModelSelected)
</code></pre>
<p><strong>Here it gets the value from the combobox, but my problem is that it does not update when I select something else from the combobox</strong></p>
<pre><code> if CarBrandModelSelected == "------------":
CarModelBox["value"] = BlankLines
CarModelBox.current(0)
elif CarBrandModelSelected == "Audi":
CarModelBox["value"] = AudiModels
CarModelBox.current(0)
# SET SCREEN ---------------------------------------------------------------
root = Tk()
root.geometry("1350x750")
root.title("Car Showroom System")
root.configure(bg="white")
#--------------------------------------------------------------------------
# VAR
Var1 = StringVar()
Var2 = StringVar()
</code></pre>
<p><strong>Here the string variable are stored</strong></p>
<p>#---------------------------------------------------------------------------</p>
<pre><code># SELECTION
SelectionFrame.grid_propagate(False)
CarBrand = Label(SelectionFrame, text="Car :")
CarBrand.grid(row=0, column=0)
CarBrandBox = ttk.Combobox(SelectionFrame, textvariable=Var1, state="readonly")
CarBrandBox.bind("<<ComboboxSelected>>")
CarBrandBox["value"] = CarBrandModel
CarBrandBox.current(0)
CarBrandBox.grid(row=0, column=1)
CarModel = Label(SelectionFrame, text="Model :")
CarModel.grid(row=1, column=0)
CarModelBox = ttk.Combobox(SelectionFrame, textvariable=Var2, state="readonly")
CarModelBox.grid(row=1, column=1)
ModelSelectionFunction()
</code></pre>
<p><strong>This calls the function in order to decide what to put into the combobox</strong></p>
<pre><code> root.mainloop()
</code></pre>
| <p>You have to add function name to bind</p>
<pre><code>CarBrandBox.bind("<<ComboboxSelected>>", ModelSelectionFunction)
</code></pre>
<p>and tkinter executes it when you select in combobox.</p>
<p>Because <code>tkinter</code> sends extra argument to binded function so you need to receive it in your function. I add <code>=None</code> so you can still execute it without arguments. </p>
<pre><code>def ModelSelectionFunction(event=None)
</code></pre>
<hr>
<p>BTW: this argument can give you selected value</p>
<pre><code>if event:
print(event.widget.get())
</code></pre>
|
How can I center <ul> in nav <p>I have this code and I want center the buttons of nav, especifically Page1,2 and 3.
I use boostrap 3.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html{
font-family: 'Nunito', sans-serif;
}
nav{
opacity: 0.8;
}
.navbar-default{
background-color: #ff4000!important;
font-family: 'Nunito', sans-serif;
}
.navbar-default a{
color: white!important;
}
.navbar-default .active a{
background-color: dimgrey!important;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<!DOCTYPE html>
<html lang="en">
<head>
<title>title</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" charset="UTF-8">
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>
<script type="text/javascript" src="js/scripts.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/index.css"/>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<!--This is the <ul> that I want center, especifically, the buttons "Page1,2 & 3"-->
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Page 1 <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Page 1-1</a></li>
<li><a href="#">Page 1-2</a></li>
<li><a href="#">Page 1-3</a></li>
</ul>
</li>
<li><a href="#">Page 2</a></li>
<li><a href="#">Page 3</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
<li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
</ul>
</div>
</div>
</nav>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>I have been looking many pages for solve this and I test so many things, I hope that someone could help me.</p>
| <pre><code>.navbar .navbar-nav {
display: inline-block;
float: none;
vertical-align: top;
}
.navbar .navbar-collapse {
text-align: center;
}
</code></pre>
<p><a href="http://codepen.io/anon/pen/VKGONw" rel="nofollow">http://codepen.io/anon/pen/VKGONw</a></p>
|
iOS - Accessibility for images <p>I am building out an app in iOS. I am working on accessibility and there is a logo on multiple screens that are cumbersome to go through continuously with VoiceOver. Is there a way for VoiceOver to not pick up the logo?</p>
| <p>Depending on how its used, a logo can be very valuable for a screen reader user. They're often linked back to the home page or they're accompanied with the title of the site (which sometimes isn't represented elsewhere). If it provides this information or functionality, it's important not to remove it. </p>
<p>Instead, common practice is to provide a 'skip to content' button that allows keyboard/screen reader users to skip past repeating blocks of content and land on the main content area of the page. This is a good resource, although it's focused towards implementing on web:
<a href="http://stackoverflow.com/questions/25259822/showing-hiding-a%E2%80%8C%E2%80%8Bccessibility-element%E2%80%8C%E2%80%8Bs-in-an-overflow-men%E2%80%8C%E2%80%8Bu-when-opening-a-cus%E2%80%8C%E2%80%8Bto">skip navigation</a></p>
<p>I hope this can help.</p>
<p>Edit: The solution (if the above isn't applicable) is to set <code>isAccessibilityElement</code> to <code>no</code> as suggested in <a href="http://stackoverflow.com/questions/25259822/showing-hiding-a%E2%80%8C%E2%80%8Bccessibility-element%E2%80%8C%E2%80%8Bs-in-an-overflow-men%E2%80%8C%E2%80%8Bu-when-opening-a-cus%E2%80%8C%E2%80%8Bto">this SO question</a> (as mentioned in the comment of this answer as the correct fix for the problem)</p>
|
Redirecting Azure logs to a particular log service <p>I have some VMs running on Azure Service. I'd like to redirect logs from them (Windows Event Logs and MS SQL server logs) to a specific log concentrator (like Graylog). For Windows logs, I'm using Nxlog (<a href="https://nxlog.co/docs/nxlog-ce/nxlog-reference-manual.html#quickstart_windows" rel="nofollow">https://nxlog.co/docs/nxlog-ce/nxlog-reference-manual.html#quickstart_windows</a>). However, for specific (PaaS) applications such as SQL Server (PaaS in general) Nxlog does not apply. </p>
<p>Is there a way to redirect logs (VMs and PaaS) just using Azure (web) tools?</p>
| <p>Most services keep their logs in a Storage Account so you can tap into that source and forward logs to your own centralized log database. You generally define the storage account at the place you enable diagnostics for the service.</p>
<p>Don't know what king of logs you are looking for in SQL DB, but for example the audit logs are saved in a storage account.</p>
|
Changes to app.rb don't seem to go into effect <p>I need to test a GET request in sendRequest.js:</p>
<pre><code>$.get( '/test/test2', {name: 'Larry', time: '2pm'} );
</code></pre>
<p>This sends the request fine and everything works on the JavaScript end, but obviously returns a 404 (route not found) so I added in app.rb:</p>
<pre><code>get '/test/test2' do
logger.info "this is a test log"
end
</code></pre>
<p>I sent the request again, and I got the same 404. </p>
<p>This scenario originates from none of my changes in app.rb going into effect. I've deleted entire routes, commented stuff out, etc., nothing I do in app.rb seems to have any effect on the server. </p>
<p>Any ideas?</p>
| <p>Have you tried stopping and restarting the server?</p>
<p>By default Sinatra won't know its code has changed, and Ruby will have loaded all the script into memory and won't look at the file.</p>
<p>Stopping the server, by using <kbd>Cntrl</kbd>+<kbd>C</kbd> then restarting the server will refresh Ruby's idea of what should be done.</p>
|
Service reference not defined <p>I have added a wcf service (SifService) reference to my Kentico web application in VS. I didn't select any of the advanced options. I just provided the wsdl address, provide a namespace (SifService) and click OK. The service reference seems to have added successfully. However, when I attempt to create an instance of the client like in the code below, VS says the type or namespace "SifService" could not be found. We have just recently upgraded from Kentico 8 to Kentico 9. The same exact code works fine in the Kentico 8 code branch. The issue only appears in the Kentico 9 branch. </p>
<pre><code>var sifClient = new SifService.SifClient();
</code></pre>
<p>When I attempt to run the site in VS, I get this error in the browser:</p>
<pre><code>Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Reference.svcmap: Could not load file or assembly 'System.Web.Http, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Source Error:
[No relevant source lines]
Source File: /App_WebReferences/SifService/ Line: 1
Assembly Load Trace: The following information can be helpful to determine why the assembly 'System.Web.Http, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' could not be loaded.
</code></pre>
<p>NOTE: Everything runs fine until I add the service reference to SifService.</p>
| <p>Sometimes it's an error of visual studio, clean the solution, build, so close the visual studio and build again, for me it worked a few times!</p>
|
Switching scenes error <p>I'm trying to create a little game but when the app switches to the game scene (when pressing the restart button), than this game scene won't load correctly. It'll give an error: thread 1 exc_bad_instruction (code=exc_i386_invop subcode=0x0). The whole game works fine in the beginning (if I didn't died yet) but when I die I'll go to another scene with a restart button and once this restart button is pressed I'll go again to the game. I won't even get the right background etc.</p>
<p>Code:</p>
<p>Game Scene (in this part the error will happen)</p>
<pre><code> func enemySpawn() {
let enemy = SKSpriteNode(imageNamed: "Enemy")
let minValue = self.size.width / 8
let maxValue = self.size.width - 150
let spawnPoint = UInt32(maxValue - minValue) // HERE IS THE ERROR
enemy.position = CGPoint(x: CGFloat(arc4random_uniform(spawnPoint)), y: self.size.height)
enemy.physicsBody = SKPhysicsBody(rectangleOf: enemy.size)
enemy.physicsBody?.affectedByGravity = false
enemy.physicsBody?.categoryBitMask = physicsCatagory.enemy
enemy.physicsBody?.contactTestBitMask = physicsCatagory.bullet
enemy.physicsBody?.isDynamic = true
let action = SKAction.moveTo(y: -70, duration: TimeInterval(enemyMoveSpeed))
let actionDone = SKAction.removeFromParent()
enemy.run(SKAction.sequence([action, actionDone]))
self.addChild(enemy)
}
</code></pre>
<p>This is the restart scene:</p>
<pre><code>var restartButton : UIButton!
override func didMove(to view: SKView) {
scene?.backgroundColor = UIColor.white
restartButton = UIButton(frame: CGRect(x: 0, y: 0, width: view.frame.size.width / 3, height: 30))
restartButton.center = CGPoint(x: view.frame.size.width / 2, y: view.frame.size.height / 7)
restartButton.setTitle("Play Again", for: UIControlState.normal)
restartButton.setTitleColor(UIColor.black, for: UIControlState.normal)
restartButton.addTarget(self, action: #selector(StartViewController.restart), for: UIControlEvents.touchUpInside)
self.view?.addSubview(restartButton)
}
func restart() {
self.view?.presentScene(GameScene(), transition: SKTransition.crossFade(withDuration: 0.3))
restartButton.removeFromSuperview()
}
</code></pre>
<p>I hope someone will be able to help me!
Thanks!</p>
| <p>My personal impression is that you get the error from the previous (disposed scene.), but I might be wrong...</p>
<pre><code>let nextScene = GameScene(size: self.scene.size)
nextScene.scaleMode = SKSceneScaleMode.AspectFill
self.view?.presentScene(nextScene, transition: transition)
</code></pre>
<p>I would pass size to the GameScene, instead of default constructor.</p>
|
Xcode Autolayout How to centre uitextfield with fixed width that can adjust for smaller screens <p>I can't seem to form how the constraints will work, so in Descriptive terms:</p>
<ul>
<li>the textfield is horizontally center to the container</li>
<li>the textfield is 100 points offset from the top layout guide</li>
<li>the textfield is 370points wide.</li>
<li>if the container shrinks in width smaller than 370 points it will adjust proportionally </li>
<li>if the screen goes wider the text field does not resize but stays at 370 points</li>
</ul>
<p>I can more or less define constraints for most of them except for the ability to constrain its width automatically if the screen shrinks in width for smaller screen sizes.</p>
<p>Some pointers would be good</p>
<p>Thanks!</p>
| <p>This should do it:</p>
<pre><code>let textField = UITextField()
view.addSubview(textField)
textField.translatesAutoresizingMaskIntoConstraints = false
// center horizontally
textField.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
// 100 from top layout guide
textField.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 100).isActive = true
// make sure textfield width never exceeds the superview width
textField.leftAnchor.constraint(greaterThanOrEqualTo: view.leftAnchor).isActive = true
textField.rightAnchor.constraint(lessThanOrEqualTo: view.rightAnchor).isActive = true
// give the textfield its default width, notice the lowered priority which allows this constraint to be broken when needed to satisfy the above constraints
let widthConstraint = textField.widthAnchor.constraint(equalToConstant: 370)
widthConstraint.priority = UILayoutPriorityDefaultHigh
widthConstraint.isActive = true
</code></pre>
|
Spark K-Mean Retrieve Cluster Members <p>Can you please provide me sample code snippet to retrieve the cluster members of K mean?</p>
<p>The below code prints cluster centers. I needed cluster members belonging to each center.</p>
<pre><code>val clusters = KMeans.train(parsedData, numClusters, numIterations)
clusters.clusterCenters.foreach(println)
</code></pre>
| <pre><code> parsedData.foreach(
new VoidFunction<Vector>() {
@Override
public void call(Vector vector) throws Exception {
System.out.println(clusters.predict(vector));
}
}
);
</code></pre>
|
Crop a trapezoidal portion from a bitmap and create a rectangular resulting bitmap <p>I want to crop a trapezoidal part from a bitmap using four coordinate points that I have. And then get this cropped bitmap as an rectangular image as the resulting bitmap.</p>
<p>I want to do this with Android JAVA as I am not familiar with C++ native development or openCV for android.</p>
<p>Figure -
<a href="https://i.stack.imgur.com/yM1ZR.png" rel="nofollow"><img src="https://i.stack.imgur.com/yM1ZR.png" alt="figure represents problem statement"></a></p>
| <pre><code> // Set up a source polygon.
// X and Y values are "flattened" into the array.
float[] src = new float[8];
src[0] = x1; // from your diagram
src[1] = y1;
src[2] = x2;
src[3] = y2;
src[4] = x3;
src[5] = y3;
src[6] = x4;
src[7] = y4;
// set up a dest polygon which is just a rectangle
float[] dst = new float[8];
dst[0] = 0;
dst[1] = 0;
dst[2] = width;
dst[3] = 0;
dst[4] = width;
dst[5] = height;
dst[6] = 0;
dst[7] = height;
// create a matrix for transformation.
Matrix matrix = new Matrix();
// set the matrix to map the source values to the dest values.
boolean mapped = matrix.setPolyToPoly (src, 0, dst, 0, 4);
// check to make sure your mapping succeeded
// if your source polygon is a distorted rectangle, you should be okay
if (mapped) {
// create a new bitmap from the original bitmap using the matrix for transform
Bitmap imageOut = Bitmap.createBitmap(imageIn, 0, 0, width, height, matrix, true);
}
</code></pre>
|
Get all products which have both product category <p>I need all products which have both categories. I am using a query below:</p>
<pre><code>$args = array(
'post_type' => array('product', 'product_variation'),
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'shop', 'cat1' ),
'operator' => 'AND',
)
)
);
</code></pre>
<p>It's working correctly if cat1 category does not have any subcategory like cat1-1,cat1-2 etc. But when i made subcategory in backend of cat1 than result will give zero.</p>
<p>Query is same just no result if cat1 have subcategory.</p>
<p>Thanks</p>
| <p>Add include children in your arguments.</p>
<p>Make sure your products have both categories. </p>
<p>In case you want to filter by multiple categories operator could be 'IN' instead of 'AND'.</p>
<pre><code>$args = array(
'post_type' => array('product', 'product_variation'),
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'include_children' => true,
'field' => 'slug',
'terms' => array( 'shop', 'cat1' ),
'operator' => 'AND',
)
)
);
</code></pre>
|
c# MongoDB Repo reference for Delete(string id) function won't accept being passed string DAO parameter <p>I'm trying to create a Delete function in a DAL EmployeeDAO, as seen here:</p>
<pre><code>public long Delete(string Id)
{
HelpdeskRepository repo = new HelpdeskRepository(new DbContext());
long deleteFlag = 0;
if (Id.Count() > 0)
{
repo.Delete(Id.GetIdAsString());
deleteFlag = 1;
return deleteFlag;// if found count = 1 == true
}
else
{
return deleteFlag;
}
}
</code></pre>
<p>However, the <code>repo.Delete(Id.GetIdAsString());</code> won't work, giving me the error</p>
<blockquote>
<p>Cs1061
Error CS1061 'string' does not contain a definition for 'GetIdAsString' and >no extension method 'GetIdAsString' accepting a first argument of type 'string' >could be found </p>
</blockquote>
<p>The Repository (repo) function it is referencing is thus:</p>
<pre><code>public long Delete<HelpdeskEntity>(string id)
{
var filter = new FilterDefinitionBuilder<HelpdeskEntity>().Eq("Id", new ObjectId(id));
var collection = GetCollection<HelpdeskEntity>();
var deleteRes = collection.DeleteOne(filter);
return deleteRes.DeletedCount;
}
</code></pre>
<p>and the GetIdAsString() function:</p>
<pre><code>public string GetIdAsString()
{
return this.Id.ToString();
}
</code></pre>
<p>I do not understand why the Id parameter won't work in the <code>repo.Delete</code> call either, as Delete accepts string parameters and Id is of type string.</p>
<p>Any thoughts, or better ways to achieve this? I cannot use Insert/async/await methods of creation for this due to future project requirements relying on repository methods, so it must be done using the <code>repo.Delete</code> function.</p>
| <p>So firstly, you are referencing GetIsAsString() as if it is an extension method here:</p>
<pre><code>repo.Delete(Id.GetIdAsString());
</code></pre>
<p>If you want it to be a extension method it should look something like this (within a static class)</p>
<pre><code>public static string GetIdAsString(this ObjectId id)
{
return id.ToString();
}
</code></pre>
<p>Otherwise, reference it like this if it is within the same class as your Id property:</p>
<pre><code>repo.Delete(GetIdAsString());
</code></pre>
<p>But to be honest, I don't understand the purpose of the GetIdAsString() method.</p>
<p>It is being called on the Id parameter which is already a string variable.</p>
<p>So this should work</p>
<pre><code>repo.Delete(Id);
</code></pre>
<p>Also, i think you will want to be referencing _id here, and you shouldn't need to cast it to ObjectId either</p>
<pre><code>var filter = new FilterDefinitionBuilder<HelpdeskEntity>().Eq("_id", id);
</code></pre>
|
find a number is between which range in a list of list <p>Need some python help, I have a list: </p>
<pre><code>[[sql1, 1, 10], [sql2, 12, 16]...]
</code></pre>
<p>I want to know if 15 is in the sql2, please let me know in python the easy way. </p>
<p>I have tried in the loop. </p>
| <p>You're going to have to give a few more details about your desired implementation, but this was too fun not to answer. </p>
<p>My answer assumes:</p>
<ol>
<li>You want a list of the beginning strings (<code>index == 0</code>) of the sublists whose:</li>
<li>2nd and 3rd elements contain <code>15</code> in the range of a (inclusive) and b (exclusive)</li>
</ol>
<p>This is in Python 3.</p>
<pre>
>>> x = [['sql1', 1, 10], ['sql2', 12, 16]]
>>> [a for a, *b in x if 15 in range(*b)]
['sql2']
</pre>
<p>This also works with multiple matches:</p>
<pre><code>>>> x = [['sql1', 1, 10], ['sql2', 12, 16], ['sql3', 15, 17]]
>>> [a for a, *b in x if 15 in range(*b)]
['sql2', 'sql3']
</code></pre>
<p>If you want to accept <code>'sql2'</code> and <code>15</code> as input and return a boolean:</p>
<pre><code>>>> x = [['sql1', 1, 10], ['sql2', 12, 16]]
>>> check = 'sql2'
>>> n = 15
>>> any(a == check and n in range(*b) for a, *b in x)
True
</code></pre>
|
What is gcc compiler option "-unsigned" meant for? <p>I am compiling legacy code using gcc compiler 4.8.5 on RHEL7. All C and C++ files have "-unsigned" as one of the default flags for both gcc and g++ compilation. The compiler accepts this option and compiles successfully. However, I cannot find any documentation of this option anywhere either in gcc manual or online. Does anyone know what this option is? I have to port the code and am confused whether this compiler option needs to be ported or not.</p>
| <p>I suspect it was just a mistake in the Makefile, or whatever is used to compile the code.</p>
<p>gcc does not support a <code>-unsigned</code> option. However, it does pass options to the linker, and GNU ld has a <code>-u</code> option:</p>
<blockquote>
<p>'-u SYMBOL'<br>
'--undefined=SYMBOL'<br>
Force SYMBOL to be entered in the output file as an undefined
symbol. Doing this may, for example, trigger linking of additional
modules from standard libraries. '-u' may be repeated with
different option arguments to enter additional undefined symbols.
This option is equivalent to the 'EXTERN' linker script command.</p>
</blockquote>
<p>The space between <code>-u</code> and the symbol name is optional.</p>
<p>So the intent might have been to do something with unsigned types, but the effect, at least with modern versions of gcc, is to enter <code>nsigned</code> in the output file as an undefined symbol.</p>
<p>This seems to have no effect in the quick test I did (compiling and running a small "hello, world" program). The program runs correctly, and the output of <code>nm hello</code> includes:</p>
<pre><code> U nsigned
</code></pre>
<p>With an older version of gcc (2.95.2) on a different system, I get a fatal link-time error about the undefined symbol.</p>
|
XCode 8.0, Building for Store Submission, Errors <p>Getting the following errors with XCODE 8.0. This was working fine with Xcode 7.x as far as we can remember.</p>
<pre><code>ERROR ITMS-90087: "Unsupported Architectures. The executable for xxx.framework contains unsupported architectures '[x86_64, i386]'."
</code></pre>
<p>Does this mean that Apple is not smart enough not to include the simulator slice? We have to provide an SDK that has the simulator and does not?</p>
<pre><code>ERROR ITMS-90209: "Invalid Segment Alignment. The app binary at 'XXX' does not have proper segment alignment. Try rebuilding the app with the latest Xcode version."
</code></pre>
<p>But we are using the latest XCODE 8.0 version? What gives here?</p>
<pre><code>ERROR ITMS-90125: "The binary is invalid. The encryption info in the LC_ENCRYPTION_INFO load command is either missing or invalid, or the binary is already encrypted. This binary does not seem to have been built with Apple's linker."
</code></pre>
<p>Not sure what this is. All Signing stuff is set correctly in all of the builds. Again, this was working fine before. We did use LIPO to make the universals. So maybe stripping the universals would do it????</p>
<pre><code>WARNING ITMS-90080: "The executable 'Payload/mediumSDKSwift.app/Frameworks/VRSDK.framework' is not a Position Independent Executable. Please ensure that your build settings are configured to create PIE executables. For more information refer to Technical Q&A QA1788 - Building a Position Independent Executable in the iOS Developer Library."
</code></pre>
<p>All PIE stuff was working find, no changes, etc. All are set to NO for Position Dependent. Have been doing some reading on this and some have solved by flipping bits? hmmmm.....</p>
| <blockquote>
<p>ERROR ITMS-90087: "Unsupported Architectures. The executable for xxx.framework contains unsupported architectures '[x86_64, i386]'."</p>
</blockquote>
<p>This is a <a href="http://www.openradar.me/radar?id=6409498411401216" rel="nofollow">known Apple bug</a>. </p>
<p>Your other errors are resulting of manipulating an already signed product, so you have to code sign your product again after you sliced out the unsupported architectures.</p>
<hr>
<p>Workaround:</p>
<p>The <code>Carthage</code> installer comes with a handy script, which I am using as an easy workaround.</p>
<p>1) Install <a href="https://github.com/Carthage/Carthage/releases" rel="nofollow">Carthage</a></p>
<p>2) Add Build Phase Script</p>
<p>From <a href="https://github.com/Carthage/Carthage" rel="nofollow">Carthage site:</a></p>
<blockquote>
<p>On your application targetsâ âBuild Phasesâ settings tab, click the â+â icon and choose âNew Run Script Phaseâ. Create a Run Script in which you specify your shell (ex: bin/sh), add the following contents to the script area below the shell:</p>
</blockquote>
<pre><code>/usr/local/bin/carthage copy-frameworks
</code></pre>
<blockquote>
<p>and add the paths to the frameworks you want to use under âInput Filesâ, e.g.:</p>
</blockquote>
<pre><code>$(SRCROOT)/Carthage/Build/iOS/Box.framework
$(SRCROOT)/Carthage/Build/iOS/Result.framework
...
</code></pre>
|
How to display color in two parts of a ggplot legend? <p>I'm trying to plot line plots of several different series, where each series will be drawn with a different line width, and each belongs to one of several groups which will determine the color. </p>
<p>What I'm struggling to do is to create a legend which shows the group names and colors, as well as the individual series names and the width/color combination for each.</p>
<p>To give a minimal working example:</p>
<pre><code># Create data
names <- c("A", "B", "C", "D", "E", "F")
df <- data.frame(
name = rep(names, 3),
group = rep(c(rep("X", 2), rep("Y", 2), rep("Z", 2)), 3),
x = c(rep(1, 6), rep(2, 6), rep(3, 6)),
y = c(runif(6, 0, 1), runif(6, 1, 2), runif(6, 2, 3)),
stringsAsFactors=FALSE
)
line.widths <- setName(runif(6, 0, 3), names)
group.colors <- setNames(c("#AA0000", "#00AA00", "#0000AA"), c("X", "Y", "Z"))
name.colors <- setNames(c(rep("#AA0000", 2), rep("#00AA00", 2), rep("#0000AA", 2)),
names)
</code></pre>
<p>And now the plot:</p>
<pre><code>library(ggplot2)
# Names and groups separately
ggplot(df, aes_string(x="x", y="y", group="name")) +
geom_line(aes(size=name, color=group)) +
scale_size_manual(values=line.widths) +
scale_color_manual(values=group.colors)
</code></pre>
<p><a href="https://i.stack.imgur.com/kTWeF.png" rel="nofollow"><img src="https://i.stack.imgur.com/kTWeF.png" alt="Six lines, with three different colors and three different line sizes."></a></p>
<p>My question is whether it's possible to add the group colors to the <code>name</code> portion of the legend, without losing the <code>group</code> portion. </p>
<p>Thanks!</p>
| <p>You are <em>incredibly</em> close (and thank you for the well researched and attempted question). You just need to add <code>override.aes</code> in the legend, like so:</p>
<pre><code>ggplot(df, aes_string(x="x", y="y", group="name")) +
geom_line(aes(size=name, color=group)) +
scale_size_manual(values=line.widths) +
scale_color_manual(values=group.colors) +
guides(size = guide_legend(override.aes = list(col = name.colors)))
</code></pre>
<p><a href="https://i.stack.imgur.com/64NRV.png" rel="nofollow"><img src="https://i.stack.imgur.com/64NRV.png" alt="enter image description here"></a></p>
|
Tooltip element with absolute positioning being clipped by container with overflow: auto <p>I have a tooltip in a modal. Is there a way that I can avoid the tooltip from being clipped? I need the modal-dialog to handle content overflow and so I cannot remove the <code>overflow: auto</code> from it.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
margin: 0;
}
.container {
display: flex;
height: 100vh;
align-items: center;
justify-content: center;
}
.modal-dialog {
display: block;
height: 50%;
width: 50%;
background: cyan;
border: 1px solid;
overflow: auto;
}
.tooltip {
position: relative;
color: red;
text-decoration: underline;
}
.tooltip::after {
display: none;
content: 'Hello';
position: absolute;
left: -100%;
top: -100%;
height: 20px;
width: 60px;
}
.tooltip:hover::after {
display: inline-block;
background: black;
color: white;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="modal-dialog">
<span class="tooltip">Tooltip</span> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
</div>
</div></code></pre>
</div>
</div>
</p>
| <p>The <code>overflow: auto</code> will clip any content outside the container, as you have indicated. You would get a similar result with <code>overflow: hidden</code>.</p>
<p>Because your tooltip pop-up (hover state) is absolutely positioned, and the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/position#Absolute_positioning" rel="nofollow">nearest positioned ancestor</a> is the tooltip trigger itself (<code>position: relative</code>), and this trigger is within the container with <code>overflow: auto</code>, there's no way to show the pop-up with this set up.</p>
<p>What you can do is make the nearest positioned ancestor an element higher up in the DOM structure. Then the abspos pop-up will reference that element, as opposed to the element with the <code>overflow</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
margin: 0;
}
.container {
display: flex;
height: 100vh;
align-items: center;
justify-content: center;
position: relative; /* moved here from .tooltip */
}
.modal-dialog {
display: block;
height: 50%;
width: 50%;
background: cyan;
border: 1px solid;
overflow: auto;
}
.tooltip {
color: red;
text-decoration: underline;
}
.tooltip::after {
display: none;
content: 'Hello';
position: absolute;
left: 15%; /* adjust as necessary */
top: 15%; /* adjust as necessary */
height: 20px;
width: 60px;
}
.tooltip:hover::after {
display: inline-block;
background: black;
color: white;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="modal-dialog">
<span class="tooltip">Tooltip</span> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque cupiditate ducimus, ea numquam est magnam quia ex consequuntur! Ratione modi dicta totam vel dolore, consequuntur nulla, amet labore odio voluptate!
</div>
</div></code></pre>
</div>
</div>
</p>
|
Initialise class and having problems with undefined offset <p>Im recently moving across from procedural to oop with my php, im studying from a book and as well as doing the exercises and projects in the book i am also giving myself a real life project to do for my own website.</p>
<p>I want to implement an sms feature to my website and while researching the project came across this small class library that connects to the API of the company i will be using, the library is on github and seems to be unsupported and my emails to the developer are bouncing back.</p>
<p>This is the <a href="https://github.com/nicksantamaria/smsbroadcastau_php" rel="nofollow">library</a> and this is the code i use to initialise it:</p>
<pre><code>require_once('classes/class.smsquick.php');
$username = "someuser";
$password = "somepass";
$api = new SmsQuick($username, $password);
//uncommenting the line below returns undefined_index @ line 312 and 282
//$available_credits = $api->checkBalance();
//var_dump($api); //used for checking
</code></pre>
<p>These are the errors i am receiving:</p>
<blockquote>
<p>Notice: Undefined offset: 1 in C:\websites\ooptuts\public\classes\class.smsquick.php on line 312</p>
<p>Warning: array_values() expects parameter 1 to be array, boolean given in C:\websites\ooptuts\public\classes\class.smsquick.php on line 282</p>
</blockquote>
<p>lines 312 and 282 are pointed out in the next two methods, the final two methods are required so i have shown those also:</p>
<pre><code>public function checkBalance() {
$vars = array(
'username' => $this->api_username,
'password' => $this->api_password,
'action' => 'balance',
);
$retval = $this->executeApiRequest($vars);
list(, $response) = array_values(reset($retval)); // line 282
return (int) $response;
}
/**
* Helper method to execute an API request.
*
* @param array $vars
* Data to POST to SMS gateway API endpoint.
*
* @return array
* Response from SMS gateway.
*/
public function executeApiRequest($vars) {
// Basic validation on the authentication details
foreach ($vars as $key => $value) {
switch ($key) {
case 'username':
case 'password':
if (empty($value)) {
throw new Exception('API username or password not specified.');
}
break;
}
}
$data = $this->preparePostData($vars);
$retval = $this->executePostRequest($data);
list($status, $response) = explode(':', $retval); // line 312
if ($status == 'ERROR') {
throw new Exception(strtr('There was an error with this request: !error.', array('!error' => $response)));
}
$data = array();
$lines = explode("\n", $retval);
foreach (array_filter($lines) as $i => $line) {
$line = trim($line);
$data[$i] = explode(':', $line);
}
return $data;
}
protected function preparePostData($data) {
$post_data = array();
foreach ($data as $key => $value) {
switch ($key) {
case 'to':
// Support multiple phone numbers.
$value = implode(',', array_unique($value));
break;
}
$post_data[] = $key . '=' . rawurlencode($value);
}
return implode('&', $post_data);
}
protected function executePostRequest($data) {
$ch = curl_init($this->api_endpoint);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$retval = curl_exec($ch);
curl_close($ch);
return $retval;
}
</code></pre>
<p>Are the problems caused by how i am initialising the class or something that i am overlooking?.. i seem to have spent two days running around in circles with google etc and not making much progress and would appreciate some advice from others.</p>
<p>thanks </p>
| <p>Because reset() returns a Boolean. Move the reset() call to its own line:</p>
<pre><code>reset($retval);
list(, $response) = array_values($retval); // line 282
</code></pre>
<p>I should say it returns the first value, however in your case its returning FALSE</p>
<p>From the <a href="http://php.net/manual/en/function.reset.php" rel="nofollow">PHP Manual: reset()</a></p>
<p>Also, its possible that on line 312 the array you are passing in is empty. Try printing out the value of the array to be sure. Perhaps your CURL call is not returning what you expect.</p>
|
iOS Change every cell colour (section + row) <p>I would like to change cell color in every cell (4 colours % 4) :</p>
<p><strong>1. Section 1</strong></p>
<p>Cell 1 : RED</p>
<p>Cell 2 : BLUE</p>
<p><strong>2. Section 2</strong></p>
<p>Cell 3 : BLACK</p>
<p><strong>3. Section 3</strong></p>
<p>Cell 4 : WHITE</p>
<p><strong>4. Section 4</strong></p>
<p>Cell 5 : RED</p>
<p>Cell 6 : BLUE</p>
<p>Cell 7 : BLACK
...</p>
<p>How can I achieve this ?</p>
<p>I know how to change color in <code>cellForRow</code> : <code>cell.contentView.backgroundColor = [UIColor colorWithRed:119.0/255.0 green:221.0/255 blue:167.0/255 alpha:1.0f];</code></p>
| <p>I'm assuming you have an array of arrays that stores your section and row data. I would create a function that takes a section and row number as arguments and returns a position that ignores the section:</p>
<pre><code>- (Int) getPosition:(Int) section rowNumber:(Int) row {
int position = 0;
for (int i = 0; i < section; i++) {
position += DataArray[i].count;
}
return position + row;
}
</code></pre>
<p>This would add up all the counts in previous sections, then add the row in the current section, to give you a new number to use for the coloring. Then to call it, write this in your cellForRow method:</p>
<pre><code>newIndex = [self getPosition:indexPath.section rowNumber:indexPath.row]
</code></pre>
<p>If you use this number to determine the colors, it'll be colored correctly.</p>
|
java synchronized Thread clarification <p>The answer for this program will have to be "Changing done" after 5 secs, but I get "Changing done" and "DONE". I do not have the getDone method as synchronized. Any ideas what am I doing for the thread to finish processing. </p>
<pre><code>public class Main {
private static boolean done = false;
private static int count;
public static void main(String[] args)throws InterruptedException {
new Thread(() -> {
while (!getDone()) {
count = count + 1;
}
System.out.println("DONE!!!!");
}).start();
Thread.sleep(5000);
System.out.println("Changing done");
synchronized (Main.class) {
done = true;
}
}
public static boolean getDone() {
return done;
}
}
</code></pre>
| <p>If you don't synchronize access to <code>done</code> properly, it means your code <em>may</em> fail, i.e. the thread <em>may</em> not see the updated value. </p>
<p>It does not mean the value is guaranteed not visible unless synchronizing correctly. So, in many cases the write to <code>done</code> is still visible (the fact that broken code still works in many cases makes concurrent programming harder). It is just not guaranteed to work in every case.</p>
|
Oracle - From WebFocus to Oracle - Sum with case <p>I have an ETL that was created in WebFocus, and will migrate it to Oracle.</p>
<p>I would like an alternative to the following situations. In WebFocus, he can use a previous calculated column, as a parameter to calculate another value.</p>
<p>Example:</p>
<pre><code>SUM(CASE
WHEN T1.M2143831 > T1.M2460254
THEN
(T1.M2143831 * 100 / T1.M2143833)
ELSE
(T1.M2460254 * 100 / T1.M2460256)
END) AS TAXA_L,
SUM(CASE
WHEN T4.FABR_ID = 'TEST'
AND TAX_L >= 80
THEN 1
ELSE NULL
END) OVER80
</code></pre>
<p>As an example, it uses the <strong>TAX_L</strong> calculated in the previous step, as a parameter for second <em>case</em>, and Oracle can not do this.
I tried as follows:</p>
<pre><code>SUM(CASE
WHEN T4.FABR_ID = 'TEST'
AND SUM(CASE
WHEN T1.M2143831 > T1.M2460254
THEN
(T1.M2143831 * 100 / T1.M2143833)
ELSE
(T1.M2460254 * 100 / T1.M2460256)
END) >= 80
THEN
1
ELSE
NULL
END)AS OVER80
</code></pre>
<p>But I received the following error:</p>
<blockquote>
<p>ORA-00937: not a single-group group function</p>
</blockquote>
<p>Any alternative to this case?</p>
<p><strong>--- Part of Original query / WebFocus</strong></p>
<pre><code> SELECT T4.FABR_ID,
T3.REPORT_DATE_TIME,
T3.DAY_OF_WEEK,
T4.REGIONAL_ID,
T4.UF_ID,
T4.BSC_ID,
T2.COD_IBGE,
T4.BTS_ID,
SUM (T1.M2251827) AS CAP_ALLOC,
SUM(CASE
WHEN T1.M2143831 > T1.M2460254
THEN
(T1.M2143831 * 100 / T1.M2143833)
ELSE
(T1.M2460254 * 100 / T1.M2460256)
END)
AS TAX_L,
SUM (100 * T1.M2489212 / T1.M2489213) AS IUB_FRAME_LOST,
SUM (T1.M1979632 * T1.M1979630) AS NUM_ACE,
SUM (T1.M1977785 * T1.M1973189) AS DEN_ACE,
SUM (T1.M2225994) AS THROUGHPUT_IUB_DOWNLINK_E,
SUM( (T1.M2016166 + T1.M2016172 + T1.M1978319 + T1.M1978331)
* 8
/ 3600)
AS THROUGHPUT_DADOS_TOTAL_H,
SUM(CASE
WHEN T4.FABR_ID = 'TEST'
AND TAX_L >= 80
THEN
1
ELSE
NULL
END)
AS OVER80,
SUM(CASE
WHEN T4.FABR_ID = 'TEST'
AND TAX_L < 80
AND TAX_L IS NOT NULL
THEN
1
ELSE
NULL
END)
AS OVER80
FROM DBN1.F_BTS T1,
DBN1.DA_CADASTRO T2,
DBN1.D_TIME T3,
DBN1.D_ENTITY_BTS T4
WHERE (T2.AA_CADASTRO_KEY = T1.AA_CADASTRO_KEY)
AND (T3.TIME_KEY = T1.TIME_KEY)
AND (T4.ENTITY_KEY = T1.ENTITY_KEY)
AND (T2.COD_IBGE <> -1)
AND (T3.HOUR BETWEEN 08 AND 23)
AND (T3.REPORT_DATE_TIME BETWEEN TO_DATE ('27-09-2016 08:00:00',
'DD-MM-YYYY HH24:MI:SS')
AND TO_DATE ('27-09-2016 23:59:59',
'DD-MM-YYYY HH24:MI:SS'))
AND (T4.FABR_ID IN ('TEST1', 'TEST2'))
AND (T4.BTS_ID NOT IN ('', '*, -1'))
GROUP BY T4.FABR_ID,
T3.REPORT_DATE_TIME,
T3.DAY_OF_WEEK,
T4.REGIONAL_ID,
T4.UF_ID,
T4.BSC_ID,
T2.COD_IBGE,
T4.BTS_ID
ORDER BY T4.FABR_ID,
T3.REPORT_DATE_TIME,
T3.DAY_OF_WEEK,
T4.REGIONAL_ID,
T4.UF_ID,
T4.BSC_ID,
T2.COD_IBGE,
T4.BTS_ID;
</code></pre>
| <p>I am totally unfamiliar with the construct you listed above, but I'm going to take a stab anyway since you can validate results from one system to the other. My guess (and it's just a guess) is that you can achieve this result by using a CTE to get the first sum (<code>TAX_L</code>) and then use that value in the main query to get the over/under 80 values:</p>
<pre><code>with yoda as (
SELECT
T4.FABR_ID, T3.REPORT_DATE_TIME, T3.DAY_OF_WEEK, T4.REGIONAL_ID,
T4.UF_ID, T4.BSC_ID, T2.COD_IBGE, T4.BTS_ID,
SUM (T1.M2251827) AS CAP_ALLOC,
SUM(CASE
WHEN T1.M2143831 > T1.M2460254
THEN (T1.M2143831 * 100 / T1.M2143833)
ELSE (T1.M2460254 * 100 / T1.M2460256)
END) AS TAX_L,
SUM (100 * T1.M2489212 / T1.M2489213) AS IUB_FRAME_LOST,
SUM (T1.M1979632 * T1.M1979630) AS NUM_ACE,
SUM (T1.M1977785 * T1.M1973189) AS DEN_ACE,
SUM (T1.M2225994) AS THROUGHPUT_IUB_DOWNLINK_E,
SUM ((T1.M2016166 + T1.M2016172 + T1.M1978319 + T1.M1978331)
* 8 / 3600) AS THROUGHPUT_DADOS_TOTAL_H
FROM
DBN1.F_BTS T1,
DBN1.DA_CADASTRO T2,
DBN1.D_TIME T3,
DBN1.D_ENTITY_BTS T4
WHERE
T2.AA_CADASTRO_KEY = T1.AA_CADASTRO_KEY
AND T3.TIME_KEY = T1.TIME_KEY
AND T4.ENTITY_KEY = T1.ENTITY_KEY
AND T2.COD_IBGE <> -1
AND T3.HOUR BETWEEN 08 AND 23
AND T3.REPORT_DATE_TIME BETWEEN
TO_DATE ('27-09-2016 08:00:00', 'DD-MM-YYYY HH24:MI:SS') and
TO_DATE ('27-09-2016 23:59:59', 'DD-MM-YYYY HH24:MI:SS')
AND T4.FABR_ID IN ('TEST1', 'TEST2')
AND T4.BTS_ID NOT IN ('', '*, -1')
GROUP BY
T4.FABR_ID, T3.REPORT_DATE_TIME, T3.DAY_OF_WEEK, T4.REGIONAL_ID,
T4.UF_ID, T4.BSC_ID, T2.COD_IBGE, T4.BTS_ID
)
select
fabr_id, report_date_time, day_of_week, regional_id, uf_id, bsc_id,
cod_ibge, bts_id, cap_alloc, tax_l, iub_frame_lost, num_ace,
den_ace, throughput_uib_downlink_e, throughput_dados_total_h,
SUM(CASE
WHEN FABR_ID = 'TEST' AND TAX_L >= 80 THEN 1
ELSE NULL
END) AS OVER80,
SUM(CASE
WHEN FABR_ID = 'TEST' AND TAX_L < 80
-- AND TAX_L IS NOT NULL -- < 80 automatically means not null
THEN 1
ELSE NULL
END) AS OVER80 -- you mean under 80?
from yoda
group by
fabr_id, report_date_time, day_of_week, regional_id, uf_id, bsc_id,
cod_ibge, bts_id, cap_alloc, tax_l, iub_frame_lost, num_ace,
den_ace, throughput_uib_downlink_e, throughput_dados_total_h
</code></pre>
<p>Some miscellaneous observations.</p>
<ol>
<li>The "else null" usually isn't necessary, but since we're on the topic did you mean "else 0"? instead? 1 + 1 + 1 + 1 + null + 1 = null</li>
<li>You had two columns aliased at "over 80." I assumed one was "under"</li>
<li>FIELD > x, FIELD < x, FIELD != x all imply non-null values. null is not > 80, < 80 and it's not NOT 80 [double not intended] (it's null).</li>
</ol>
<p>Again, since I've never seen an aggregate referenced in the same portion of a query, my SQL above is an educated guess.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.