title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
EmberJS global error when running tests
<p>I am trying to integrate automated testing using Ember Testing.</p> <p>The application runs fine on browser, without any errors. I tried simply running </p> <pre><code>ember test </code></pre> <p>on command line, but get a bunch of global errors and all the tests fail.</p> <p>These are the errors I'm getting:</p> <pre><code>not ok 1 PhantomJS 2.1 - Global error: SyntaxError: Unexpected token ',' at http://localhost:4302/assets/vendor.js, line 145617 not ok 2 PhantomJS 2.1 - Global error: Error: Could not find module ember-metal/core required by: ember-testing/index at http://localhost:4302/assets/test-support.js, line 62 not ok 3 PhantomJS 2.1 - Global error: ReferenceError: Can't find variable: define at http://localhost:4302/assets/tests.js, line 1 ... </code></pre> <p>When I run the tests on the browser, I do not get the syntax error (first one above), the first error is </p> <pre><code>Uncaught Error: Could not find module `analogue/resolver` imported from `analogue/tests/helpers/resolver` </code></pre> <p>These don't make sense to me since I shouldn't be editing vendor.js and the modules it says it cannot find are there. Any ideas?</p>
2
swift Regular Expression and (.*?)
<p>I want to extract substrings from a string that match a regex pattern.</p> <p>The problem is this code : <code>("ytplayer.config = {(.*?)};").exec(responseStringC)</code>. It must match but return nil.</p> <p>string.exec function : </p> <pre><code>extension String { func exec (str: String) -&gt; Array&lt;String&gt; { do { let regex = try NSRegularExpression(pattern: self, options: [.CaseInsensitive,.IgnoreMetacharacters]) let nsstr = str as NSString let all = NSRange(location: 0, length: nsstr.length) var matches : Array&lt;String&gt; = Array&lt;String&gt;() regex.enumerateMatchesInString(str, options: NSMatchingOptions(rawValue: 0), range: all) { (result : NSTextCheckingResult?, _, _) in let theResult = nsstr.substringWithRange(result!.range) matches.append(theResult) } return matches } catch { print("error") return Array&lt;String&gt;() } } } </code></pre> <p>"responseStringC" variable is : </p> <p><a href="http://pastebin.com/uvvq9ULA" rel="nofollow">http://pastebin.com/uvvq9ULA</a></p> <p>the problem is return nil. Any Clue?</p>
2
VBA Set Excel.Application Object to already open workbook instead of creating a new Excel instance
<p>I use the following all the time to manipulate Excel data from Access.</p> <pre><code>Set xl = CreateObject("Excel.Object") </code></pre> <p>However, this method creates a new Excel instance and only applies formatting, for example, to it.</p> <pre><code>xl.Range(...).Interior.Color = blah, blah, blah </code></pre> <p>Will only refer to that instance of an Excel object that was create with the first line of code.</p> <p>The problem I am having is that I already have an instance of Excel open and there is VBA in Access that I want to use to apply formatting to the already open file to prep it for importing. I guess I could create the new instance of Excel and just refer to the workbook I am working on with <code>xl.Workbook(blah).Activate</code> but that seems kinda messy.</p> <p>Yea, I could move the code to Excel, but that defeats the purpose of manipulating Excel from Access and having my VBA in central location accessible to users.</p>
2
Creating many objects in sequence diagram
<p>Suppose I am creating an order handling system. A user may request many different kinds of product for an order. So an order consists of many orderlines. Whenever a customer makes an order the oder object has to create many orderlines objects. How to draw that in sequence diagram? </p>
2
gradle configurations/artifacts only uses "default" configuration
<p>submodule <strong>(locallibs)</strong> build.gradle looks like the following:</p> <pre><code>configurations.create("default") artifacts.add("default", file('defaultdistro.aar')) configurations.create("distro2") artifacts.add("distro2", file('distro2.aar')) configurations.create("distro3") artifacts.add("distro3", file('distro3.aar')) </code></pre> <p>the build.gradle for the app has a dependencies{} section that looks like the following:</p> <pre><code>dependencies { debugCompile project(':locallibs') flavor1ReleaseCompile project(path: ':locallibs', configuration: 'distro2') flavor2ReleaseCompile project(path: ':locallibs', configuration: 'distro3') } </code></pre> <p>The issue I'm having is that regardless of the flavor/build type the "default" configuration is always compiled so all of my flavors are including the "defaultdistro.aar" instead of the correct .aar distro.</p> <p>I am expecting for flavor1 release build type to compile the distro2.aar but <em>all</em> flavors are compiling the defaultdistro.aar</p> <p>EDIT: fixed the locallibs build.gradle representation</p> <p>EDIT #2: the .aar distros are mutually exclusive</p>
2
What is wrong with my XDocument save?
<p>I am trying to save some changes back to an XML file using Linq and I have seen many examples on SO and tutorial sites doing it like this but for some reason I am getting an error on the xmlDoc.Save(customerXMLPath); line <strong>Argument 1: cannot convert from 'string' to 'System.IO.Stream'</strong>. </p> <p>Most of the samples I have seen are ASP.Net samples but I wouldn't think that should make much a difference on the syntax (this is a UWP app). Can someone please tell me what I am doing wrong?</p> <pre><code>private void SaveChange_Click(object sender, RoutedEventArgs e) { string customerXMLPath = Path.Combine(Package.Current.InstalledLocation.Path, "XML/Customers.xml"); XDocument xmlDoc = XDocument.Load(customerXMLPath); var updateQuery = from r in xmlDoc.Descendants("Customer") where r.Element("CustomerId").Value == txtCustomerId.Text select r; foreach (var query in updateQuery) { query.Element("State").SetValue(txtState.Text); } xmlDoc.Save(customerXMLPath); } </code></pre> <p>Edit: according to the comments there is no overload for Save in UWP. So does that mean (based on another comment) that I have to save as a stream? If that is the case wouldn't I have to overwrite the file? &lt;-- that doesn't make sense when I am just trying to change a few values but maybe I misunderstood the answer. </p> <p>My assumption is that there is a way to update a XML file in UWP so am I just going about this all wrong? What is the recommended way? By the way SQLite is not an option right now because the files have to remain in XML format </p>
2
How do I compile Qt Application under Manjaro KDE?
<p>Complete noob right here, I'm learning c++ and I saw some tutorial somewhere with instructions to compile the Qt application example from the command line, then I noticed the path from the tutorial was not correct, I want to learn how to compile Qt from command line, and maybe even do some makefiles to automate the process, at least I want to get started ...It seems like the qt libraries are already installed within my system since it is using the KDE desktop environment, but I don't know how should I link or what paths should I include as arguments. Please guide me, remember I'm a complety noob but I really want to learn. This is the tutorial I'm talking about <a href="http://zetcode.com/gui/qt5/introduction/" rel="nofollow">http://zetcode.com/gui/qt5/introduction/</a></p>
2
Assert Statement for ternary operator in Rhino mocks?
<pre><code>x(string)= y(string) != ? y : string.empty </code></pre> <p>How to get 100% code coverage for above line using Assert statement</p> <p>We've tried using: Assert.AreEqual(Actualvalue,ExpectedValue); but we are missing code coverage somewhere</p>
2
Spring Boot applications stop right after start
<p>I had a couple of Spring Boot applications running in my workspace using STS IDE, and right after i did maven update on one of the projects every single one of them stops right after application boot process. I even created the smallest example just to start something and the same thing happens. </p> <pre><code>@SpringBootApplication public class App implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(App.class, args); } @Override public void run(String... arg0) throws Exception { System.out.println("Started..."); } } </code></pre> <p>This is my pom.xml </p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;sasa-test-app&lt;/groupId&gt; &lt;artifactId&gt;sasa-app&lt;/artifactId&gt; &lt;version&gt;1.0.0&lt;/version&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;name&gt;sasa-app&lt;/name&gt; &lt;description&gt;Sasa&lt;/description&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;1.4.0.BUILD-SNAPSHOT&lt;/version&gt; &lt;relativePath /&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-tomcat&lt;/artifactId&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;repositories&gt; &lt;repository&gt; &lt;id&gt;spring-snapshots&lt;/id&gt; &lt;name&gt;Spring Snapshots&lt;/name&gt; &lt;url&gt;https://repo.spring.io/snapshot&lt;/url&gt; &lt;snapshots&gt; &lt;enabled&gt;true&lt;/enabled&gt; &lt;/snapshots&gt; &lt;/repository&gt; &lt;repository&gt; &lt;id&gt;spring-milestones&lt;/id&gt; &lt;name&gt;Spring Milestones&lt;/name&gt; &lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt; &lt;snapshots&gt; &lt;enabled&gt;false&lt;/enabled&gt; &lt;/snapshots&gt; &lt;/repository&gt; &lt;/repositories&gt; &lt;pluginRepositories&gt; &lt;pluginRepository&gt; &lt;id&gt;spring-snapshots&lt;/id&gt; &lt;name&gt;Spring Snapshots&lt;/name&gt; &lt;url&gt;https://repo.spring.io/snapshot&lt;/url&gt; &lt;snapshots&gt; &lt;enabled&gt;true&lt;/enabled&gt; &lt;/snapshots&gt; &lt;/pluginRepository&gt; &lt;pluginRepository&gt; &lt;id&gt;spring-milestones&lt;/id&gt; &lt;name&gt;Spring Milestones&lt;/name&gt; &lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt; &lt;snapshots&gt; &lt;enabled&gt;false&lt;/enabled&gt; &lt;/snapshots&gt; &lt;/pluginRepository&gt; &lt;/pluginRepositories&gt; &lt;/project&gt; </code></pre> <p>And this is what i get on application start. I tried every suggestion i could find online - i am missing something here.</p> <pre> . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ [32m :: Spring Boot :: [39m[2m (v1.4.0.BUILD-SNAPSHOT)[0;39m [2m2016-07-10 22:35:25.204[0;39m [32m INFO[0;39m [35m10028[0;39m [2m---[0;39m [2m[ main][0;39m [36msasa_test_app.sasa_app.App [0;39m [2m:[0;39m Starting App on LAPTOP-C36O81UQ with PID 10028 (C:\Users\sasar\DEVCODE\STS_WORKSPACE\sasa-app\target\classes started by sasar in C:\Users\sasar\DEVCODE\STS_WORKSPACE\sasa-app) [2m2016-07-10 22:35:25.210[0;39m [32m INFO[0;39m [35m10028[0;39m [2m---[0;39m [2m[ main][0;39m [36msasa_test_app.sasa_app.App [0;39m [2m:[0;39m No active profile set, falling back to default profiles: default [2m2016-07-10 22:35:25.426[0;39m [32m INFO[0;39m [35m10028[0;39m [2m---[0;39m [2m[ main][0;39m [36ms.c.a.AnnotationConfigApplicationContext[0;39m [2m:[0;39m Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@641147d0: startup date [Sun Jul 10 22:35:25 CEST 2016]; root of context hierarchy [2m2016-07-10 22:35:29.004[0;39m [32m INFO[0;39m [35m10028[0;39m [2m---[0;39m [2m[ main][0;39m [36mo.s.j.e.a.AnnotationMBeanExporter [0;39m [2m:[0;39m Registering beans for JMX exposure on startup Started... [2m2016-07-10 22:35:29.041[0;39m [32m INFO[0;39m [35m10028[0;39m [2m---[0;39m [2m[ main][0;39m [36msasa_test_app.sasa_app.App [0;39m [2m:[0;39m Started App in 4.664 seconds (JVM running for 5.876) [2m2016-07-10 22:35:29.070[0;39m [32m INFO[0;39m [35m10028[0;39m [2m---[0;39m [2m[ Thread-1][0;39m [36ms.c.a.AnnotationConfigApplicationContext[0;39m [2m:[0;39m Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@641147d0: startup date [Sun Jul 10 22:35:25 CEST 2016]; root of context hierarchy [2m2016-07-10 22:35:29.075[0;39m [32m INFO[0;39m [35m10028[0;39m [2m---[0;39m [2m[ Thread-1][0;39m [36mo.s.j.e.a.AnnotationMBeanExporter [0;39m [2m:[0;39m Unregistering JMX-exposed beans on shutdown </pre> <p>Even those Getting started examples stop right after boot. I would be very thankful for some help here.</p> <p>edit: <strong>As Alexandru Marina stated in the comment, I was using SNAPSHOT instead of stable release.</strong></p>
2
Close Realm instance after execution finishes
<p>I want to close my Realm instance in <code>executeTransactionAsync</code> after execution finished. Reason is that my applications main thread keeps on freezing, I think the reason for it is that the background realm instance is not being closed after execution finishes. See my code below:</p> <pre><code>realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { // Execute realm code realm.copyToRealmOrUpdate(myData); // Can I close the realm instance here without getting an // error? realm.close(); causes an error. } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { Log.i("CB", "success"); // looks like I cannot access the execute Realm // instance here. // Closing realm.getDefaultInstance does not change my issue } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { Log.i("CB", "error - " + error.getMessage()); } }); } </code></pre> <p>Please see my comments. My application screen just turns black. Execution completes successfully and <code>onSuccess()</code> gets called, but I cannot access the <code>execute</code> realm instance to close it from here. </p> <p>Do you have any suggestions as to what I can try? Am I doing something wrong?</p> <p>Thank you in advance.</p> <p><strong>EDIT</strong></p> <pre><code>07-19 11:43:42.379 8146-8146/com.shortterminsurance.shortterm I/CB: success 07-19 11:43:43.258 8146-8152/com.shortterminsurance.shortterm W/art: Suspending all threads took: 33.234ms 07-19 11:43:43.266 8146-8156/com.shortterminsurance.shortterm I/art: Background partial concurrent mark sweep GC freed 476307(17MB) AllocSpace objects, 512(10MB) LOS objects, 40% free, 33MB/55MB, paused 7.261ms total 163.497ms 07-19 11:43:44.131 8146-8156/com.shortterminsurance.shortterm I/art: Background sticky concurrent mark sweep GC freed 408160(9MB) AllocSpace objects, 459(15MB) LOS objects, 35% free, 35MB/55MB, paused 10.287ms total 147.823ms 07-19 11:43:44.834 8146-8152/com.shortterminsurance.shortterm W/art: Suspending all threads took: 103.676ms 07-19 11:43:44.848 8146-8156/com.shortterminsurance.shortterm W/art: Suspending all threads took: 13.424ms </code></pre> <p>This is my logcat after my onSuccess gets called. I think the background instance of realm in <code>execute</code> keeps running for some reason :(.</p>
2
Test a Batch Flow in MUnit
<p>I am trying to test a batch flow but if I place a reference to a batch flow in my MUnit test, the test will finish instantly and run the asserts, while the batch flow continues in the background. Is there a way to force my batch job to run synchronously so that I can examine the results in my MUnit tests?</p>
2
Material-ui Textfield auto-scroll up the window on first redux-form/FOCUS
<p>I made a form using <a href="https://github.com/erikras/redux-form" rel="nofollow">redux-form</a> with <a href="http://www.material-ui.com/#/components/text-field" rel="nofollow">Textfield</a> from <a href="http://www.material-ui.com/#/" rel="nofollow">material-ui</a> to send an email. Everything is working well except a single thing : When I click on a TextField for the FIRST time, the window scroll uptop. Sometime, the focus stay on the TextField. Afterward it's working fine</p> <p>Here's an example of what's happening <a href="https://gyazo.com/e790ea8339d8541d4ed4fde7e1ef7754" rel="nofollow">Example</a></p> <p>My form:</p> <pre><code>import React, { PropTypes, Component } from 'react'; import { reduxForm } from 'redux-form'; import TextField from 'material-ui/TextField'; import RaisedButton from 'material-ui/RaisedButton'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import styles from './EmailForm.css'; import theme from '../../../theme/theme'; import { mediaQueries } from '../../../decorators'; export const fields = ['name', 'email', 'subject', 'message']; const validate = values =&gt; { ... }; @mediaQueries @withStyles(styles) @reduxForm({ form: 'EmailForm', fields, validate }) export default class EmailForm extends Component { static propTypes = { fields: PropTypes.object.isRequired, handleSubmit: PropTypes.func.isRequired, submitting: PropTypes.bool.isRequired, mediaQueries: PropTypes.func.isRequired, }; state = { mobile: false, } componentDidMount() { this.props.mediaQueries('(max-width: 399px)', () =&gt; { this.setState({ mobile: true }); }); this.props.mediaQueries('(min-width: 400px) and (max-width: 919px)', () =&gt; { this.setState({ mobile: true }); }); this.props.mediaQueries('(min-width: 920px)', () =&gt; { this.setState({ mobile: false }); }); } render() { const { fields: { name, email, subject, message }, handleSubmit, submitting } = this.props; const emailMarginLeft = this.state.mobile ? 0 : '8px'; // SOME STYLE HERE return ( &lt;form className={styles.form} onSubmit={handleSubmit} &gt; &lt;div className={styles.nameAndEmail}&gt; &lt;TextField style={nameFieldStyle} floatingLabelText="Votre Nom" floatingLabelStyle={labelStyle} floatingLabelFocusStyle={labelFocusStyle} errorText={(name.touched &amp;&amp; name.error) ? name.error : ''} errorStyle={errorStyle} id="nameField" {...name} /&gt; &lt;TextField style={emailTextField} floatingLabelText="Votre courriel" floatingLabelStyle={labelStyle} floatingLabelFocusStyle={labelFocusStyle} errorText={(email.touched &amp;&amp; email.error) ? email.error : ''} errorStyle={errorStyle} id="emailField" {...email} /&gt; &lt;/div&gt; &lt;div className={styles.subjectAndMessage}&gt; &lt;TextField style={textField} floatingLabelText="Sujet" floatingLabelStyle={labelStyle} floatingLabelFocusStyle={labelFocusStyle} errorText={(subject.touched &amp;&amp; subject.error) ? subject.error : ''} errorStyle={errorStyle} id="sujet" {...subject} /&gt; &lt;TextField style={messageTextField} floatingLabelText="Message" floatingLabelStyle={labelStyle} floatingLabelFocusStyle={labelFocusStyle} errorText={(message.touched &amp;&amp; message.error) ? message.error : ''} errorStyle={errorStyle} multiLine rows={5} id="message" {...message} /&gt; &lt;/div&gt; &lt;RaisedButton style={buttonStyle} key="submitButton" type="submit" label="Envoyer" primary disabled={submitting} /&gt; &lt;/form&gt; ); } } </code></pre> <p>The component using the form :</p> <pre><code>@withStyles(styles) export default class ContactUs extends Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(data) { // Do stuff } render() { return ( &lt;div className={styles.contactUs}&gt; &lt;h2&gt;Formulaire&lt;/h2&gt; &lt;EmailForm ref="EmailForm" onSubmit={this.handleSubmit} submitting /&gt; &lt;/div&gt; ); } } </code></pre> <p>The theme imported contain the color used for material-ui style. I have also found that onFocus and onBlur props of the TextFields doesn't work. I tried to simply log text and it doesn't work. </p> <p>What makes it even weirder is that it isnt the first time I'm using this emailForm. I used it on another site and it was working perfectly fine.</p> <p>Anyone has an idea of why it's happening?</p>
2
Similar solutions for java.lang.NoClassDefFoundError: org/joda/time/DateTime not working
<p>I have seen this question posted here before and I have looked at the solutions however I cannot fix the problem I'm having. I created a very simple Maven project in Eclipse for Java and I want to run the output jar file e.g. java -jar jarfilename.jar </p> <p>I can run the program by right clicking on the project in eclipse and indicating run as Java application. I can build the project to a jar file with mvn package. Running the jar file I get the output of NoClassDefFoundError for the joda time. The joda jar files are in the configured repository e.g. .m2/repository/joda-time/joda-time/2.8.2. There are no errors indicated for the project in Eclipse. I'm using jdk1.8.0_92 Maven version 3.3.9 and eclipse Java EE Neon release 4.6.0. Java home is configured in the environment variables and so too is the class path as: ...\Java\jdk1.8.0_92\jre\lib;C:\Users\username.m2\repository</p> <p>Some additional information the classpath is correct in terms of not having typos in it. I also looked at a solution from another similar question wherein the suggestion was to add the external jar to the bootstrap entries under run configuratotion. I have also made an entry in the Java build path for joda time which points corretly to the .m2/repository.../joda-time/2.8.2 What this seems like is that when this runs from eclipse the path to the joda time jar file is (for lack of a better term) known. When the jar file is built however that path is not known. I opened the jar file and looked at the MANIFEST.MF file and I see: </p> <pre><code>Manifest-Version: 1.0 Built-By: John Class-Path: joda-time-2.8.jar Build-Jdk: 1.8.0_92 Created-By: Maven Integration for Eclipse Main-Class: hello.HelloMain </code></pre> <p>The source is very simple: package hello;</p> <pre><code>import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; public class HelloMain { public static void main(String[] args) { System.out.println("Hello From My Main ! It worked\n"); final DateTime today = new DateTime().withZone(DateTimeZone.UTC); DateTime tommorrow = today.plusDays(3); String startTime = today.toString(DateTimeFormat.forPattern("yyyy-MM- dd'T'HH:mm'Z")); String endTime = tommorrow.toString(DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm'Z")); System.out.printf("The start time %s End Time %s \n", startTime, endTime); } } </code></pre> <p>This is my pom file: </p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;hello&lt;/groupId&gt; &lt;artifactId&gt;hello&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;!-- Build an executable JAR --&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt; &lt;version&gt;2.4&lt;/version&gt; &lt;configuration&gt; &lt;archive&gt; &lt;manifest&gt; &lt;addClasspath&gt;true&lt;/addClasspath&gt; &lt;mainClass&gt;hello.HelloMain&lt;/mainClass&gt; &lt;/manifest&gt; &lt;/archive&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;dependencies&gt; &lt;!-- https://mvnrepository.com/artifact/joda-time/joda-time --&gt; &lt;dependency&gt; &lt;groupId&gt;joda-time&lt;/groupId&gt; &lt;artifactId&gt;joda-time&lt;/artifactId&gt; &lt;version&gt;2.8&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p> </p>
2
MVC gives Error Value cannot be null or empty. when i return model to view during updateing
<p>I am trying to return model to view to <strong>Preserve</strong> the data that the user entered if there is an exception. So when I return the model to view it tells me "Value cannot be null or empty" but the model still has the data</p> <pre><code>@Html.EditorFor(model =&gt; model.NewsTitle, new { htmlAttributes = new { @class = "form-control" } }) </code></pre> <p><a href="https://i.stack.imgur.com/X73ws.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X73ws.jpg" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/it9jd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/it9jd.jpg" alt="enter image description here"></a></p> <pre><code> [HttpGet] public ActionResult Edit(int? Id) { using (var db = new NewsDatabaseEntities()) { db.Configuration.LazyLoadingEnabled = false; var Result = (from n in db.News.Include("Categories") from c in db.Categories where n.NewsId == Id select new { news = n, neweCategories = n.Categories, cate = c }).ToList(); News NewsDetails = (from news in Result select new News { NewsId = news.news.NewsId, NewsTitle = news.news.NewsTitle, NewsBody = news.news.NewsBody, NewsImagePath = news.news.NewsImagePath, Categories = news.neweCategories }).FirstOrDefault(); var AllCategories = (from c in Result select new Category { CategoryId = c.cate.CategoryId, CategoryName = c.cate.CategoryName }).ToList(); if (NewsDetails != null) { var model = new NewsViewModel(); model.NewsId = NewsDetails.NewsId; model.AllCategories = AllCategories; model.Categories = NewsDetails.Categories; model.NewsTitle = NewsDetails.NewsTitle; model.NewsBody = NewsDetails.NewsBody; model.NewsImagePath = NewsDetails.NewsImagePath; return View(model); } else { return RedirectToAction("Index", "Home"); } } return View(); } [ValidateInput(false)] [ValidateAntiForgeryToken] public ActionResult Edit(NewsViewModel model) { using (var db = new NewsDatabaseEntities()) { db.Configuration.LazyLoadingEnabled = false; News NewsToUpdate = db.News.Include("Categories").SingleOrDefault(n =&gt; n.NewsId == model.NewsId); if (NewsToUpdate != null) { using (var transaction = db.Database.BeginTransaction()) { try { db.SaveChanges(); transaction.Commit(); return RedirectToAction("Details", "Admin", new { Id = model.NewsId }); } catch (Exception ex) { transaction.Rollback(); TempData["Error"] = ex.Message + " " + ex.ToString(); return View(model); } } } else { return RedirectToAction("Index", "Home"); } } return View(); } </code></pre> <p>Razor View</p> <pre><code>@model Assignment.Models.NewsViewModel @{ ViewBag.Title = "Edit"; } &lt;h2&gt;Update News&lt;/h2&gt; &lt;br /&gt; @if (TempData["Error"] != null) { &lt;p class=" alert alert-danger"&gt; &lt;strong&gt;Error! &lt;/strong&gt; @TempData["Error"] &lt;/p&gt; } @using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { id = "MyForm", enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() &lt;div class="form-horizontal"&gt; @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(model =&gt; model.NewsId) @Html.HiddenFor(model =&gt; model.SelectedCategoriesIds, new { id = "hid" }) &lt;div class="form-group"&gt; @Html.Label("Enter News Title", htmlAttributes: new { @class = "control-label col-md-2" }) &lt;div class="col-md-10"&gt; @Html.EditorFor(model =&gt; model.NewsTitle, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model =&gt; model.NewsTitle, "", new { @class = "text-danger" }) &lt;br /&gt;&lt;br /&gt; &lt;img src="@Url.Content(Model.NewsImagePath)" alt="Image" id="ImagePreview" width=330 height=250 /&gt; &lt;br /&gt;&lt;br /&gt; @Html.TextBoxFor(model =&gt; model.NewsImageFile, new { type = "file", data_val = "false" }) @Html.ValidationMessageFor(model =&gt; model.NewsImageFile, "", new { @class = "text-danger" }) &lt;br /&gt; &lt;br /&gt; &lt;div class="form-group"&gt; &lt;div class="col-md-10"&gt; @Html.TextAreaFor(model =&gt; model.NewsBody, new { htmlAttributes = new { @class = "ckeditor" } }) @Html.ValidationMessageFor(model =&gt; model.NewsBody, "", new { @class = "text-danger" }) &lt;br /&gt; This News under these categories: &lt;br /&gt;&lt;br /&gt; &lt;select id="dropdownOne" name="dropdownOne" multiple="multiple" class="form-control"&gt; @foreach (var Category in Model.AllCategories) { if (Model.Categories.Select(c =&gt; c.CategoryId).Contains(Category.CategoryId)) { &lt;option selected value="@Category.CategoryId"&gt;@Category.CategoryName&lt;/option&gt; } else { &lt;option value="@Category.CategoryId"&gt;@Category.CategoryName&lt;/option&gt; } } &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;div class="col-md-offset-2 col-md-10"&gt; &lt;input type="submit" value="Save" class="btn btn-default" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; } </code></pre>
2
Empty override C++11
<p>Having the Observer pattern.</p> <pre><code>class Observer { virtual eventA()=0; virtual eventB()=0; ... virtual eventZ()=0; } </code></pre> <p>The Observer class cannot be changed, but my class is only interested in the event B. Therefore I need to:</p> <pre><code>class MyObserver{ eventA() override {} eventB() override { /* Do something */ } eventC() override {} ... eventZ() override {} } </code></pre> <p>It is overhead to empty-implement all events, specially if you have a policy to always implement in cpp files (except templates obviously).</p> <p>Does C++11 offer any keyword for that? Like</p> <pre><code>... eventC() override = empty; ... </code></pre> <p>In that way, I wouldn't need to add the empty implementation in the CPP file.</p>
2
ASP.NET Core fails to start in debug mode when SSL is enabled
<p>I'm getting the following error while launching debugger (F5) in Visual Studio:</p> <blockquote> <p>An error occurred attempting to determine the process id of WebApplication5.exe which is hosting your application. One or more errors occurred.</p> </blockquote> <p>I've noticed that it happens when I set the applicationUrl (in launchSettings.json) to point to https url:</p> <pre><code>"iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "https://localhost:44399/", "sslPort": 44399 } </code></pre> <p>}</p> <p>It started happening after I upgraded .net code tools from RC2 to RTM. Please help</p> <p><a href="https://i.stack.imgur.com/8X0cq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8X0cq.png" alt="enter image description here"></a></p>
2
Accessing ngModel elements that use a class
<p>I have many elements in my HTML code that have their <code>ngModel</code> assignment defined as <code>ng-model = "object.[something]"</code>.</p> <p>For example: </p> <p><code>&lt;div class="form-group row" ng-model="object.askUser"&gt;</code></p> <p>I do this to be clear of my purpose for these elements. My question is how do I access these element in my Javascript? Do I call <code>$scope.object.askUser</code>, <code>$object.askUser</code>, or something else? I had a hard time finding things on the web about this, most likely because I wasn't quite sure of the words to use in the search bar to describe what I am trying to do.</p>
2
How to "reset" a DOM subtree's CSS style?
<p>I'm developing a Chrome Extension, an HTML subtree and a CSS style sheet are injected into the original page. I want the injected HTML subtree not to be affected by the original CSS, but I have no idea about how to finish the job perfectly. The problem:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;style&gt; /* original CSS */ input[type="text"] { background: green; } input[type="text"]:focus { background: yellow; } /* my injected CSS somewhere else */ .injected-root input[type="text"] { border: solid 1px navy; } &lt;/style&gt; &lt;input type="text" value="original text"&gt; &lt;div class='injected-root'&gt; &lt;input type="text" value="injected text"&gt; &lt;/div&gt; </code></pre> <p>The original page is a random page on the internet, so it's impossible to know what the original CSS would be. As you can see from the code above, my injected text input is affected by the original CSS, I know it can be fixed by override the original CSS with new default values:</p> <pre><code>.injected-root input[type="text"] { border: solid 1px navy; background: white; } .injected-root input[type="text"]:focus { background: white; } </code></pre> <p>But I don't think it's feasible to do it "manually" by supply every default attribute.</p> <p>So, the question is: </p> <ul> <li><strong>Is there a way to reset the style of a subtree completely?</strong></li> </ul> <p>or</p> <ul> <li><strong>Any other strategy to make the subtree seems in an "isolated universe" (only affected by its own injected CSS)?</strong></li> </ul>
2
external css and @font-face
<p>all. I've referenced SO often and appreciate the community and expertise. Great site! I'm a noob member, so bear with me.</p> <p>PROBLEM: embedded files not loaded/displayed</p> <p>ROOT DIR has two dirs: plugins and project</p> <p>plugins has files mycss.css and 4 font files (2 woff, 2 ttf)</p> <p>mycss.css</p> <pre><code>@font-face { font-family: 'ALG'; src: url('ALGbvs.woff') format('woff'), url('ALGbvs.ttf') format('truetype'); } @font-face { font-family: 'BVS'; src: url('BitstreamVeraSans.woff') format('woff'), url('BitstreamVeraSans.ttf') format('truetype'); } </code></pre> <p>index.html contains (excerpts)</p> <pre><code>&lt;head&gt; ... &lt;!-- font-family: ALG and BVS --&gt; &lt;link href="../plugins/mycss.css" rel="stylesheet" type="text/css" /&gt; ... &lt;style&gt; body { font-family: ALG; background-color: #F9EFE2; margin: 0; } &lt;/style&gt; &lt;/head&gt; </code></pre> <p>I thought I was referencing the css file and the fonts correctly, but they are not loaded/displayed in the body. What am I missing? Thanks for all reads and replies.</p>
2
Daylight saving time with NSTimeZone best practice
<p>I have created a weekly view(similar to calendar) with header day of week. I am creating the current time using below code :</p> <pre><code>+(NSDate *) getCurrentDate { NSDate* datetime = [NSDate date]; NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init]; NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"America/Juneau"];// this is dynamic and coming from server. [dateFormatter setTimeZone:timeZone]; // Prevent adjustment to user's local time zone. [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"]; NSString* dateTimeInIsoFormatForUserTimeZone = [dateFormatter stringFromDate:datetime]; return [dateFormatter dateFromString:dateTimeInIsoFormatForUserTimeZone]; } </code></pre> <p>I am using this date as reference to create week date (from monday to sunday). My code work fine for all case but I was failing at DST time zone.</p> <p>I have seen similar question on stack-overflow but they are more subjective and not able to solve my problem. Answer with code and best practise is highly appreciated. Thanks In advance!. </p>
2
Why are map values not addressable?
<p>While playing with Go code, I found out that map values are not addressable. For example,</p> <pre><code>package main import "fmt" func main(){ var mymap map[int]string = make(map[int]string) mymap[1] = "One" var myptr *string = &amp;mymap[1] fmt.Println(*myptr) } </code></pre> <p>Generates error</p> <blockquote> <p>mapaddressable.go:7: cannot take the address of mymap[1]</p> </blockquote> <p>Whereas, the code,</p> <pre><code>package main import "fmt" func main(){ var mymap map[int]string = make(map[int]string) mymap[1] = "One" mystring := mymap[1] var myptr *string = &amp;mystring fmt.Println(*myptr) } </code></pre> <p>works perfectly fine.</p> <p>Why is this so? Why have the Go developers chosen to make certain values not addressable? Is this a drawback or a feature of the language?</p> <p><strong>Edit</strong>: Being from a C++ background, I am not used to this <code>not addressable</code> trend that seems to be prevalent in Go. For example, the following code works just fine:</p> <pre><code>#include&lt;iostream&gt; #include&lt;map&gt; #include&lt;string&gt; using namespace std; int main(){ map&lt;int,string&gt; mymap; mymap[1] = "one"; string *myptr = &amp;mymap[1]; cout&lt;&lt;*myptr; } </code></pre> <p>It would be nice if somebody could point out why the same <em>addressability</em> cannot be achieved (or intentionally wasn't achieved) in Go.</p>
2
SharePoint 2010 CSOM get field values of a folder in document library
<p>Using client object model, with below caml query able to fetch items with in a folder, but seeing a way to get "folder" field values where these items or documents is residing.</p> <pre><code>+ "&lt;Query&gt;" + " &lt;Where&gt;" + " &lt;Eq&gt;&lt;FieldRef Name='FSObjType' /&gt;&lt;Value Type='int'&gt;0&lt;/Value&gt;&lt;/Eq&gt;" + " &lt;/Where&gt;" + "&lt;/Query&gt;" </code></pre> <p>My code for retrieving folder information...</p> <pre><code>string strFieldValue = string.Empty; CamlQuery qryFolder = new CamlQuery(); qryFolder.ViewXml = @"&lt;View Scope='RecursiveAll'&gt;" + "&lt;Query&gt;" + " &lt;Where&gt;" + " &lt;And&gt;" + " &lt;Eq&gt;&lt;FieldRef Name='FSObjType' /&gt;&lt;Value Type='int'&gt;1&lt;/Value&gt;&lt;/Eq&gt;" + " &lt;Eq&gt;&lt;FieldRef Name='FileRef' /&gt;&lt;Value Type='Text'&gt;"+folderName+"&lt;/Value&gt;&lt;/Eq&gt;" + " &lt;/And&gt;" + " &lt;/Where&gt;" + "&lt;/Query&gt;" + "&lt;ViewFields&gt;" + "&lt;FieldRef Name='Title' /&gt;&lt;FieldRef Name='FieldValue' /&gt;&lt;FieldRef Name='FileRef' /&gt;" + "&lt;/ViewFields&gt;" + "&lt;/View&gt;"; qryFolder.FolderServerRelativeUrl = rootFolder;//+@"/"+folderName; ListItemCollection itemColl = docs.GetItems(qryFolder); context.Load(itemColl); context.ExecuteQuery(); if (itemColl.Count == 1) { strFieldValue = itemColl[0]["FieldValue"].ToString(); } return strFieldValue </code></pre> <p>I get a value here when used caml query with FSObjType is 1 which is for only folders... but unfortunately i get null when query with FSObjType is 0 which queries only files. My requirement is to get a value even when you are at the file level... Not sure if i'm going correct with the CAML query..</p> <p>Thanks, Jameel</p>
2
MySQL load data infile is slow
<p>I'm new to SQL, and I see this question has been asked many times, but none of the answers have helped me. So I'm hoping to get feedback on my situation.</p> <p>I am trying to load a tab-delimited file with about 1.5 million rows and 48 columns. Each field is enclosed with double quotes. My query ran for over an hour and I killed it. Here is what I did:</p> <pre><code>CREATE TABLE mytable ( *48 variable declarations given types varchar, int, or decimal*, PRIMARY KEY (id) ); </code></pre> <p>&nbsp;</p> <pre><code>load data local infile 'MyFile.tsv' into table mytable fields terminated by '\t' enclosed by '"' lines terminated by '\n' IGNORE 1 LINES (*comma separated list of all 48 variable names in 'mytable'*); </code></pre> <p>Is there something obviously that I'm missing that is blowing up the runtime of this query? I was careful to declare variables with only enough space as needed. So if I have an integer field with up to 3 digits, it is declared as <code>myfield int(3)</code>.</p>
2
Re-arranging flex items for mobile and desktop
<p>I'm trying to make the layout below using flex:</p> <p><a href="https://i.stack.imgur.com/yv1ic.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yv1ic.png" alt="layout of header"></a></p> <p>Can I make this layout with flex? </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>.objectref-use .page-header { display: flex; flex-direction: row; } .objectref-use .page-header .header-col { flex: 1; display: flex; } .objectref-use .page-header .header-content { display: flex; flex-wrap: wrap; flex-direction: column; } .objectref-use .page-header .header-content .together-content { flex-wrap: nowrap; } .objectref-use .page-header .objectref-title { margin-right: 8px; } .objectref-use .page-header .objectref-title.header-col { justify-content: flex-start; } .objectref-use .page-header .objectref-title .header-content { flex: 0 1 auto; background: blue; } .objectref-use .page-header .objectref-timeline { flex: 0 0 35px; display: flex; } .objectref-use .page-header .objectref-timeline .header-content { background: pink; flex: 1 1 100%; } .objectref-use .page-header .objectref-menu.header-col { justify-content: flex-end; } .objectref-use .page-header .objectref-menu .header-content { flex: 0 1 auto; background: green; } @media screen and (max-width: 768px) { .page-header { flex-direction: column; } .page-header .header-row { flex-direction: row; } } @media screen and (max-width: 480px) { .page-header { flex-direction: column; } .page-header .header-col { flex: 1; } .page-header .objectef-timeline { margin: 0; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="objectref-use"&gt; &lt;div class="page-header"&gt; &lt;div class="header-col objectref-title"&gt; &lt;div class="header-content"&gt; &lt;h1&gt;title here (can be loooong) [block 1]&lt;/h1&gt; &lt;h6&gt;text on next line&lt;/h6&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="header-col objectref-timeline"&gt; &lt;div class="header-content"&gt;timeline [block 3]&lt;/div&gt; &lt;/div&gt; &lt;div class="header-col objectref-menu"&gt; &lt;div class="header-content"&gt; &lt;div class="together-content"&gt; few button groups here [block 2] &lt;/div&gt; &lt;h6&gt;text on next line&lt;/h6&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>This is <a href="http://codepen.io/Alxd/pen/AXbdpG" rel="nofollow noreferrer" title="code">the current CSS on Codepen</a>. Thanks.</p>
2
hardware transactional memory: _xbegin() return 0
<p>By gcc docs: <a href="https://gcc.gnu.org/onlinedocs/gcc-4.9.2/gcc/X86-transactional-memory-intrinsics.html" rel="nofollow">x86-transactional-memory-intrinsics.html</a>, when transaction failed/abort, <strong>_xbegin()</strong> should return a <strong>abort status</strong> . However, I find it return 0 sometimes. And the frequency is very high. What kind of situation that **_xbegin()**will return 0?</p> <p><strong>After checking manual, I find many situations may cause this result. For example, CPUID, SYSTEMCALL, CFLUSH.etc</strong>. However, I don't think my code has triggered any of them.</p> <p>Here is my code: Simulating a small bank, a random account transfer 1$ to another account. </p> <pre><code>#include "immintrin.h" #include &lt;thread&gt; #include &lt;unistd.h&gt; #include &lt;iostream&gt; using namespace std; #define n_threads 1 #define OPSIZE 1000000000 typedef struct Account{ long balance; long number; } __attribute__((aligned(64))) account_t; typedef struct Bank{ account_t* accounts; long size; } bank_t; bool done = 0; long *tx, *_abort, *capacity, *debug, *failed, *conflict, *zero; void* f1(bank_t* bank, int id){ for(int i=0; i&lt;OPSIZE; i++){ int src = rand()%bank-&gt;size; int dst = rand()%bank-&gt;size; while(src == dst){ dst = rand()%bank-&gt;size; } while(true){ unsigned stat = _xbegin(); if(stat == _XBEGIN_STARTED){ bank-&gt;accounts[src].balance++; bank-&gt;accounts[dst].balance--; _xend(); asm volatile("":::"memory"); tx[id]++; break; }else{ _abort[id]++; if (stat == 0){ zero[id]++; } if (stat &amp; _XABORT_CONFLICT){ conflict[id]++; } if (stat &amp; _XABORT_CAPACITY){ capacity[id]++; } if (stat &amp; _XABORT_DEBUG){ debug[id]++; } if ((stat &amp; _XABORT_RETRY) == 0){ failed[id]++; break; } if (stat &amp; _XABORT_NESTED){ printf("[ PANIC ] _XABORT_NESTED\n"); exit(-1); } if (stat &amp; _XABORT_EXPLICIT){ printf("[ panic ] _XBEGIN_EXPLICIT\n"); exit(-1); } } } } return NULL; } void* f2(bank_t* bank){ printf("_heartbeat function\n"); long last_txs=0, last_aborts=0, last_capacities=0, last_debugs=0, last_faileds=0, last_conflicts=0, last_zeros = 0; long txs=0, aborts=0, capacities=0, debugs=0, faileds=0, conflicts=0, zeros = 0; while(1){ last_txs = txs; last_aborts = aborts; last_capacities = capacities; last_debugs = debugs; last_conflicts = conflicts; last_faileds = faileds; last_zeros = zeros; txs=aborts=capacities=debugs=faileds=conflicts=zeros = 0; for(int i=0; i&lt;n_threads; i++){ txs += tx[i]; aborts += _abort[i]; faileds += failed[i]; capacities += capacity[i]; debugs += debug[i]; conflicts += conflict[i]; zeros += zero[i]; } printf("txs\t%ld\taborts\t\t%ld\tfaileds\t%ld\tcapacities\t%ld\tdebugs\t%ld\tconflit\t%ld\tzero\t%ld\n", txs - last_txs, aborts - last_aborts , faileds - last_faileds, capacities- last_capacities, debugs - last_debugs, conflicts - last_conflicts, zeros- last_zeros); sleep(1); } } int main(int argc, char** argv){ int accounts = 10240; bank_t* bank = new bank_t; bank-&gt;accounts = new account_t[accounts]; bank-&gt;size = accounts; for(int i=0; i&lt;accounts; i++){ bank-&gt;accounts[i].number = i; bank-&gt;accounts[i].balance = 0; } thread* pid[n_threads]; tx = new long[n_threads]; _abort = new long[n_threads]; capacity = new long[n_threads]; debug = new long[n_threads]; failed = new long[n_threads]; conflict = new long[n_threads]; zero = new long[n_threads]; thread* _heartbeat = new thread(f2, bank); for(int i=0; i&lt;n_threads; i++){ tx[i] = _abort[i] = capacity[i] = debug[i] = failed[i] = conflict[i] = zero[i] = 0; pid[i] = new thread(f1, bank, i); } // sleep(5); for(int i=0; i&lt;n_threads;i++){ pid[i]-&gt;join(); } return 0; } </code></pre> <p>Supplements:</p> <ol> <li>All accounts is 64bit aligned. I printed bank->accounts[0], bank->accounts<a href="https://gcc.gnu.org/onlinedocs/gcc-4.9.2/gcc/X86-transactional-memory-intrinsics.html" rel="nofollow">1</a> address. 0xf41080,0xf410c0。</li> <li>Using -O0 and <code>asm volatile("":::"memory");</code>therefore there is no instruction reordering problems.</li> <li><p>Abort rate increases at time. Here is the result</p> <pre><code>txs 84 aborts 0 faileds 0 capacities 0 debugs 0 conflit 0 zero 0 txs 17070804 aborts 71 faileds 68 capacities 9 debugs 0 conflit 3 zero 59 txs 58838 aborts 9516662 faileds 9516661 capacities 0 debugs 0 conflit 1 zero 9516661 txs 0 aborts 9550428 faileds 9550428 capacities 0 debugs 0 conflit 0 zero 9550428 txs 0 aborts 9549254 faileds 9549254 capacities 0 debugs 0 conflit 0 zero 9549254 </code></pre></li> <li><p>Even through n_threads is 1, the result is same.</p></li> <li><p>If I add coarse lock after fallback as follow, the result seems be correct.</p> <pre><code>int fallback_lock; bool rtm_begin(int id) { while(true) { unsigned stat; stat = _xbegin (); if(stat == _XBEGIN_STARTED) { return true; } else { _abort[id]++; if (stat == 0){ zero[id]++; } //call some fallback function if (stat&amp; _XABORT_CONFLICT){ conflict[id]++; } //will not succeed on a retry if ((stat &amp; _XABORT_RETRY) == 0) { failed[id]++; //grab a fallback lock while (!__sync_bool_compare_and_swap(&amp;fallback_lock,0,1)) { } return false; } } } } .... in_rtm = rtm_begin(id); y = fallback_lock; accounts[src].balance--; accounts[dst].balance++; if (in_rtm){ _xend(); }else{ while(!__sync_bool_compare_and_swap(&amp;fallback_lock, 1, 0)){ } } </code></pre></li> </ol>
2
MySQL GROUP BY on large tables
<p>I have a table with over 75 millions registers. I want to run a group by to summarize this registries.</p> <p>The table structure is:</p> <pre><code>CREATE TABLE `output_medicos_full` ( `name` varchar(100) NOT NULL DEFAULT '', `term` varchar(50) NOT NULL DEFAULT '', `hash` varchar(40) NOT NULL DEFAULT '', `url` varchar(2000) DEFAULT NULL, PRIMARY KEY (`name`,`term`,`hash`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; </code></pre> <p>I want execute the query bellow, but is taking so long using a dedicate mysql server 5.5 with 4GB RAM:</p> <pre><code>INSERT INTO TABLE report SELECT `hash` ,CASE UPPER(SUBSTRING_INDEX(url, ':', 1)) WHEN 'HTTP' THEN 1 WHEN 'HTTPS' THEN 2 WHEN 'FTP' THEN 3 WHEN 'FTPS' THEN 4 ELSE 0 end ,url FROM output_medicos_full GROUP BY `hash`; </code></pre> <p>On table report there is an unique index on hash column</p> <p>Any help to speed it up?</p> <p>Thank's</p>
2
How can i sort ExpandableListview?
<p>I am using one ExpndableListview with two arraylist and one Adapter. How can I sort both child and parent arraylist data in descending order.</p> <p>1.parent Arraylist</p> <pre><code>private List&lt;PhoneNumber&gt; listDataHeader = new ArrayList&lt;&gt;(); </code></pre> <p>2.child list</p> <pre><code> private HashMap&lt;String, List&lt;SubBalance&gt;&gt; listDataChild = new HashMap&lt;&gt;(); </code></pre> <p>And I am using Adapter code in Activity class as below :</p> <pre><code> listAdapter = new ExpandableAdapter(getActivity(), listDataHeader, listDataChild, AccountProfileFragment.this); </code></pre> <p>ExpandableAdapter code</p> <pre><code>public class ExpandableAdapter extends BaseExpandableListAdapter implements OnClickListener, OnCheckedChangeListener { private Context context; private List&lt;PhoneNumber&gt; _listDataHeader; private HashMap&lt;String, List&lt;SubBalance&gt;&gt; _listDataChild; private DataSwitchListner listner; private Activity activity; private LoadingDialog loading; public ExpandableAdapter(Activity activity, List&lt;PhoneNumber&gt; listDataHeader, HashMap&lt;String, List&lt;SubBalance&gt;&gt; listChildData, DataSwitchListner listner) { loading = LoadingDialog.getInstance(); this.context = activity; this._listDataHeader = listDataHeader; this._listDataChild = listChildData; this.listner = listner; this.activity = activity; } @Override public Object getChild(int groupPosition, int childPosititon) { return this._listDataChild.get(this._listDataHeader.get(groupPosition).getNumber()).get(childPosititon); } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @SuppressLint("InflateParams") @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.item_exp_child, null); } SubBalance account = (SubBalance) getChild(groupPosition, childPosition); TextView currency = (TextView) convertView.findViewById(R.id.currency); TextView balance = (TextView) convertView.findViewById(R.id.balance); TextView expiry = (TextView) convertView.findViewById(R.id.expiry); TextView days = (TextView) convertView.findViewById(R.id.days); TextView daysLabel = (TextView) convertView.findViewById(R.id.daysLabel); TextView lblInfinite = (TextView) convertView.findViewById(R.id.lblInfinite); ImageView imgIcon = (ImageView) convertView.findViewById(R.id.imgIcon); ProgressBar progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar); LinearLayout llChart = (LinearLayout) convertView.findViewById(R.id.llChart); if (account != null &amp;&amp; account.getCurrencyName() != null &amp;&amp; currency != null) { currency.setText(account.getCurrencyName()); balance.setText(account.getBalance()); String expDateStr = account.getExpiryDate(); Log.e("expDateStr12345",expDateStr); Date expDate; if (expDateStr.contains(".")) { /* expiry.setText(DateUtils.convertFromOldFormatToNewFormat(expDateStr, DateUtils.FORMAT_1, DateUtils.FORMAT_4));*/ expiry.setText(DateUtils.convertFromOldFormatToNewFormat(expDateStr, DateUtils.FORMAT_1, DateUtils.FORMAT_1)); expDate = DateUtils.convertFromString(expDateStr, DateUtils.FORMAT_1); LogEvent.Log("ExpandableAdapterdate1", "Phone: " + expDate); } else { expiry.setText(DateUtils.convertFromOldFormatToNewFormat(expDateStr, DateUtils.FORMAT_1_WOD, DateUtils.FORMAT_1_WOD)); expDate = DateUtils.convertFromString(expDateStr, DateUtils.FORMAT_1_WOD); LogEvent.Log("ExpandableAdapterdate", "Phone: " + expDate); } long daysBetween = DateUtils.daysBetween(new Date(), expDate); Log.e("expDateStr12345",""+daysBetween); int progress = 0; if (daysBetween &gt; 0) { progress = 100; if (daysBetween &lt;= 30) { progress = (int) ((daysBetween / 30.0) * 100); } } days.setTypeface(Methods.getNovaBoldItalic()); Log.e("expDateStr12345",""+days); if (daysBetween &gt; 100) { progressBar.setVisibility(View.VISIBLE); llChart.setVisibility(View.VISIBLE); lblInfinite.setVisibility(View.INVISIBLE); //days.setText("NO"); days.setText("No"); daysLabel.setText("VENCE"); progress = 0; // Log.e("expDateStr12345",""+days); } else { progressBar.setVisibility(View.VISIBLE); llChart.setVisibility(View.VISIBLE); lblInfinite.setVisibility(View.INVISIBLE); days.setText(Long.toString(daysBetween)); // Log.e("expDateStr12345",""+days.getText().toString()); } progressBar.setProgress(progress); try { if (account.getIconResource() != null) { imgIcon.setImageResource(Integer.parseInt(account.getIconResource())); } } catch (Exception e) { e.printStackTrace(); } } return convertView; } @Override public int getChildrenCount(int groupPosition) { return this._listDataChild.get(this._listDataHeader.get(groupPosition).getNumber()).size(); } @Override public Object getGroup(int groupPosition) { return this._listDataHeader.get(groupPosition); } @Override public int getGroupCount() { return this._listDataHeader.size(); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @SuppressLint("InflateParams") @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { PhoneNumber account = (PhoneNumber) getGroup(groupPosition); CheckBox cbxIsOn; FontTextView lblPhoneNumber = null; TextView lblBalance = null, lblTarrif = null, lblBundles = null, lblReload = null, lblAddbundle = null, lblHistory = null; LinearLayout llHeader = null; ImageView imgIndicator = null; if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.item_exp_parent1, null); } cbxIsOn = (CheckBox) convertView.findViewById(R.id.cbxIsOn); lblPhoneNumber = (FontTextView) convertView.findViewById(R.id.lblPhoneNumber); lblBalance = (TextView) convertView.findViewById(R.id.lblBalance); lblTarrif = (TextView) convertView.findViewById(R.id.lblTarrif); lblBundles = (TextView) convertView.findViewById(R.id.lblBundles); imgIndicator = (ImageView) convertView.findViewById(R.id.imgIndicator); llHeader = (LinearLayout) convertView.findViewById(R.id.llHeader); lblReload = (TextView) convertView.findViewById(R.id.lblReload); lblAddbundle = (TextView) convertView.findViewById(R.id.lblAddbundle); lblHistory = (TextView) convertView.findViewById(R.id.lblHistory); if (isExpanded) llHeader.setVisibility(View.VISIBLE); else llHeader.setVisibility(View.GONE); if (account.getIsVerified().equalsIgnoreCase("0")) { cbxIsOn.setEnabled(false); lblTarrif.setVisibility(View.INVISIBLE); lblBundles.setVisibility(View.INVISIBLE); lblBalance.setVisibility(View.INVISIBLE); } else { cbxIsOn.setEnabled(true); lblTarrif.setVisibility(View.VISIBLE); lblBundles.setVisibility(View.VISIBLE); lblBalance.setVisibility(View.VISIBLE); } lblReload.setTag(groupPosition); lblAddbundle.setTag(groupPosition); lblHistory.setTag(groupPosition); lblReload.setOnClickListener(this); lblAddbundle.setOnClickListener(this); lblHistory.setOnClickListener(this); if (account != null) { LogEvent.Log("Expandable Adapter", "Phone: " + account.getNumber()); lblPhoneNumber.setText(account.getNumber()); LogEvent.Log("Expandable Adapter", "Plan: " + account.getTariffName()); lblTarrif.setText(account.getTariffName()); LogEvent.Log("Expandable Adapter", "Bundle: " + account.getBundles()); lblBundles.setText(account.getBundles()); if (account.getCacheBalance() != null) { lblBalance.setText("S/ " + account.getCacheBalance()); } imgIndicator.setSelected(isExpanded); cbxIsOn.setOnCheckedChangeListener(null); cbxIsOn.setChecked(account.isEnabled()); cbxIsOn.setTag(groupPosition); cbxIsOn.setOnCheckedChangeListener(this); } return convertView; } @Override public boolean hasStableIds() { return true; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return false; } @Override public void onClick(final View view) { final PhoneNumber ph = (PhoneNumber) getGroup((int) view.getTag()); final String phone = ph.getNumber(); LogEvent.Log("Expandable Adapter", "Phone: " + ph.getNumber()); LogEvent.Log("Expandable Adapter", "Phone Id: " + ph.getId()); switch (view.getId()) { case R.id.lblReload: SPManager.save(SPManager.KEY_CURRENT_PHONE, phone); SPManager.save(SPManager.KEY_CURRENT_PHONE_ID, ph.getId()); getBalances(MainActivity.FRAG_RELOAD); break; case R.id.lblAddbundle: SPManager.save(SPManager.KEY_CURRENT_PHONE, phone); SPManager.save(SPManager.KEY_CURRENT_PHONE_ID, ph.getId()); getBalances(MainActivity.FRAG_PACKAGES); break; case R.id.lblHistory: SPManager.save(SPManager.KEY_CURRENT_PHONE, phone); SPManager.save(SPManager.KEY_CURRENT_PHONE_ID, ph.getId()); getBalances(MainActivity.FRAG_HISTORY); break; default: break; } } private void getBalances(final int gotoThis) { String currentPhoneNumber = SPManager.retrive(SPManager.KEY_CURRENT_PHONE); try { QueryBuilder&lt;PhoneNumber, Integer&gt; qb = App.getDbHelper().getPhoneNumbersDao().queryBuilder(); qb.where().eq("number", currentPhoneNumber); PhoneNumber phoneNumber = qb.queryForFirst(); String token = SPManager.retrive(SPManager.KEY_TOKEN); String subId = SPManager.retrive(SPManager.KEY_CURRENT_PHONE_ID); MyEndpoint e = new MyEndpoint(); e.setUrl(Urls.BASE_URL_NEW); RestAdapter.Builder builder = new RestAdapter.Builder(); builder.setEndpoint(e); if (loading != null &amp;&amp; !loading.isShowing()) { loading.showDialog(context); } eLog("Balances: " + Urls.BASE_URL_NEW + Urls.METHOD_BALANCES); // eLog("Balances: " + Webservices.balance(subId, token)); eLog("Balances: " + Webservices.balance(subId, token)); builder.build().create(RetroClient.class).balancesWb(Webservices.balance(subId, token), new Callback&lt;BalancesResponse&gt;() { @Override public void success(BalancesResponse m, retrofit.client.Response arg1) { if (loading != null &amp;&amp; loading.isShowing()) { loading.dismissDialog(); } if (Strings.RESPONSE_SUCCESS.equalsIgnoreCase(m.getCode())) { Methods.updateCurrentBalanceCurrency(m.getMain().getBalance(), m.getMain().getCurrency()); eLog("Sliding menu go to: " + gotoThis); ((MainActivity) activity).selectSideMenu(gotoThis, true); } else { DialogUtil.displayAlert(context, context.getString(R.string.dialog_title_error), Strings.getError(m.getError(), context), context.getString(R.string.dialog_button_ok)); } } @Override public void failure(RetrofitError e) { eLog("Error from retrofit: " + e.getMessage()); if (loading != null &amp;&amp; loading.isShowing()) { loading.dismissDialog(); } } }); } catch (SQLException e) { e.printStackTrace(); } } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int pos = (int) buttonView.getTag(); PhoneNumber ph = _listDataHeader.get(pos); _listDataHeader.get(pos).setEnabled(buttonView.isChecked()); listner.onDataSwitched(isChecked, ph.getNumber(), ph.getSubscriberId()); } public void eLog(String str) { Log.e("TAG", "" + str); } </code></pre> <p>Please help me how can i sort expandableListview data in decending order Thank you</p>
2
YOLO neural network not compiling in VS13
<p>I'm trying to use <a href="http://pjreddie.com/darknet/yolo/" rel="nofollow">YOLO</a> in VS13, but it's not compiling. I was using <a href="https://github.com/frischzenger/yolo-windows" rel="nofollow">this</a> (which gave me <a href="https://github.com/frischzenger/yolo-windows/issues/1" rel="nofollow">this</a> error) and now I'm trying <a href="https://github.com/AlexeyAB/yolo-windows" rel="nofollow">this</a> (which is not compiling). If I use opencv 2.4.13, the error is </p> <pre><code>Error 1075 error LNK1104: cannot open file 'opencv_core249.lib' </code></pre> <p>(downloading this lib not helping and causes another linker error)</p> <p>If I use opencv 3.1.0 this error accures</p> <pre><code>Error 14 error : this declaration may not have extern "C" linkage C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\limits 78 1 darknet </code></pre> <p>I found <a href="https://groups.google.com/forum/#!searchin/darknet/opencv$203/darknet/AfZcD-C6yXY/RWp5V2tXBAAJ" rel="nofollow">solution</a> which didn't work for me, because if i remove </p> <pre><code>#ifdef OPENCV #include "opencv2/highgui/highgui_c.h" #include "opencv2/imgproc/imgproc_c.h" #endif </code></pre> <p>from image.h, and add it to image.c (generally it's already in image.c, so i'm just deleting this lines from image.h) the error accures in this lines (image.h)</p> <pre><code>#ifdef OPENCV void save_image_jpg(image p, char *name); image get_image_from_stream(CvCapture *cap); image ipl_to_image(IplImage* src); #endif </code></pre> <p>(CvCapture and IplImage not defined)</p> <p>So, how can I use YOLO in windows? What should I fix in frischzenger or AlexeyAB solution?</p>
2
Log python on Openshift
<p>I have configured my Django project on Openshift with success.</p> <p>But somewhere in my site I launch a command tool installed by <strong>pip</strong> and I think the command failed. But I don't find python log with</p> <pre><code>rhc tail -a project </code></pre> <p>Or when I got to <strong>/var/lib/openshift/<em>id</em>/app-root/logs/python.log</strong> file I don't find more log than displayed at screen</p> <p><strong>How can I see all my python output console ?</strong></p> <p>Thanks</p> <p><strong>[EDIT]</strong> </p> <p>I tried to use the <a href="https://docs.djangoproject.com/en/1.8/topics/logging/#examples" rel="nofollow">logging configuration for django</a>, but I can't see my log even if I put my app name in <strong>loggers</strong>.</p>
2
Polymorphic Associations in Entity Framework
<p>I have a legacy database that has a few tables which were designed using <a href="https://stackoverflow.com/questions/2002985/mysql-conditional-foreign-key-constraints">Polymorphic Associations</a>. By polymorphic associations, I mean that those tables can be child of different tables according to a column <code>ObjectType</code>. </p> <p>Example: </p> <ul> <li><code>Documents</code> table has <code>DocumentID</code> (identity primary key), some other columns, and 2 special columns called <code>ObjectType</code> and <code>ObjectID</code>. </li> <li>If <code>ObjectType='STUDENT'</code>, <code>ObjectID</code> points to <code>Students</code> table. </li> <li>If <code>ObjectType='TEACHER'</code>, <code>ObjectID</code> points to <code>Teachers</code> table, etc. </li> </ul> <p>This is similar to <a href="https://stackoverflow.com/questions/7000283/what-is-the-best-way-to-implement-polymorphic-association-in-sql-server">this design</a> (as described in the "no foreign key approach") or <a href="https://stackoverflow.com/questions/3894056/how-do-i-apply-subtypes-into-an-sql-server-database">this one</a> (described as an anti-pattern). And obviously, there are <strong>no foreign key constraints</strong> on those columns <em>(AFAIK no database would allow that kind of relationship)</em>.</p> <p>I'm writing a new Data Access Layer using Entity Framework 6 (code-first with Fluent API) which should work side-by-side with existing code. Since this database structure was deployed to hundreds of different customers (each one with a different codebase and different database customizations), modifying the structure of existing tables is not an option.</p> <p>My question is: How do I map those Polymorphic Associations into my EF code-first model?</p> <hr> <p><strong>EDIT</strong>: It seems that I was trying to design the class hierarchy on the wrong entities. My understanding was that I had a lot of "GenericChildTables" (like Documents) that should point to a (non-existing) entity that would have a composite key ObjectType+ObjectID. And then I was trying to create that new entity (let's call it "BusinessObject") and map my core entities (Students, Teachers, etc) to be subtypes of this BusinessObject. </p> <p>THAT design was probably just plain wrong, and maybe totally impossible because this new table that I was creating (BusinessObject) depended on StudentID/TeacherID, etc, so it couldn't be a parent of those tables. Using some ugly workarounds I could create that BusinessObject as a single-child for each core entity, and map those BusinessObjects to the polymorphic tables, and it was working indeed but in a completely wrong design. </p> <p><strong>Then</strong> I saw <a href="https://stackoverflow.com/questions/13953675/modelling-polymorphic-associations-database-first-vs-code-first">Gert Ardold's question</a> and realized that what should be designed as a class hierarchy was NOT Students/Teachers/etc (grouped into a generic entity), but each one of those ChildTables, which were holding different subtypes according to the <code>ObjectType</code> discriminator - those were the types that should be splitted into subtypes. <strong>See my solution on my own answer below.</strong></p>
2
search gridview using javascript
<p>i trying to search gridview but fail,please tell me where i did wrong,or i need include reference? my javascript</p> <pre><code>&lt;script type="text/javascript"&gt; function Search_Gridview(strKey, strGV) { var strData = strKey.value.toLowerCase().split(" "); var tblData = document.getElementById(strGV); var rowData; for (var i = 1; i &lt; tblData.rows.length; i++) { rowData = tblData.rows[i].innerHTML; var styleDisplay = 'none'; for (var j = 0; j &lt; strData.length; j++) { if (rowData.toLowerCase().indexOf(strData[j]) &gt;= 0) styleDisplay = ''; else { styleDisplay = 'none'; break; } } tblData.rows[i].style.display = styleDisplay; } } </code></pre> <p> my gridview</p> <pre><code>&lt;div style="border: 1px solid Black; width: 800px; padding: 20px; height: 350px; font-size: 20px;"&gt; Search : &lt;asp:TextBox ID="txtSearch" runat="server" Font-Size="20px" onkeyup="Search_Gridview(this, 'gvTest')"&gt;&lt;/asp:TextBox&gt;&lt;br /&gt; &lt;br /&gt; &lt;asp:GridView ID="gvTest" runat="server" CellPadding="10" Width="500px"&gt; &lt;/asp:GridView&gt; </code></pre> <p></p> <p>my c# data fill gridview</p> <pre><code>private void FillRoleGrid() { string constr = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("SELECT EmployeeNo,Name,POsition FROM userInfo")) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.Connection = con; sda.SelectCommand = cmd; using (DataTable dt = new DataTable()) { sda.Fill(dt); gvTest.DataSource = dt; gvTest.DataBind(); } } } } } </code></pre> <p>im totally no idea where i did wrong ,please guide me,thank you.</p>
2
R: unable to save an element of a object
<p>I am attempting to save an object, but it fails:</p> <pre><code>&gt; save("MEs", "moduleColors", "net$dendrograms", file = "TNF_AH-network-auto.RData") Error in save("MEs", "moduleColors", "net$dendrograms", file = "TNF_AH-network-auto.RData") : object ‘net$dendrograms’ not found &gt; save(list=c("MEs", "moduleColors", "net$dendrograms"), file = "TNF_AH-network-auto.RData") Error in save(list = c("MEs", "moduleColors", "net$dendrograms"), file = "TNF_AH-network-auto.RData") : object ‘net$dendrograms’ not found &gt; save(list=c(MEs, moduleColors, net$dendrograms), file = "TNF_AH-network-auto.RData") Error in FUN(X[[i]], ...) : invalid first argument &gt; save(MEs, moduleColors, as.vector(net$dendrograms), file = "TNF_AH-network-auto.RData") Error in save(MEs, moduleColors, as.vector(net$dendrograms), file = "TNF_AH-network-auto.RData") : object ‘as.vector(net$dendrograms)’ not found &gt; save(MEs, moduleColors, list(net$dendrograms), file = "TNF_AH-network-auto.RData") Error in save(MEs, moduleColors, list(net$dendrograms), file = "TNF_AH-network-auto.RData") : object ‘list(net$dendrograms)’ not found &gt; head(net$dendrograms) [[1]] Call: fastcluster::hclust(d = as.dist(dissTom), method = "average") ... &gt; ls(net) [1] "blockGenes" "blocks" "colors" "dendrograms" [5] "goodGenes" "goodSamples" "MEs" "MEsOK" [9] "TOMFiles" "unmergedColors" </code></pre> <p>I can access it and I can save it with saveRDS:</p> <pre><code>&gt; saveRDS(net$dendrograms, "dendro") &gt; </code></pre> <p>Or I can save it with:</p> <pre><code>&gt; tmp &lt;- list(net$dendrograms) &gt; save(MEs, moduleColors, tmp, file = "TNF_AH-network-auto.RData") &gt; </code></pre> <p>Why I can't save the object as expected with <code>save(MEs, moduleColors, net$dendrograms, file = "TNF_AH-network-auto.RData")</code> ?</p> <p>The sessionInfo:</p> <pre><code>&gt; sessionInfo() R version 3.2.3 (2015-12-10) Platform: x86_64-pc-linux-gnu (64-bit) Running under: Ubuntu 14.04.2 LTS locale: [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C [3] LC_TIME=es_ES.UTF-8 LC_COLLATE=en_US.UTF-8 [5] LC_MONETARY=es_ES.UTF-8 LC_MESSAGES=en_US.UTF-8 [7] LC_PAPER=es_ES.UTF-8 LC_NAME=C [9] LC_ADDRESS=C LC_TELEPHONE=C [11] LC_MEASUREMENT=es_ES.UTF-8 LC_IDENTIFICATION=C attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] WGCNA_1.51 RSQLite_1.0.0 DBI_0.4-1 [4] fastcluster_1.1.20 dynamicTreeCut_1.63-1 loaded via a namespace (and not attached): [1] Rcpp_0.12.5 RColorBrewer_1.1-2 GenomeInfoDb_1.4.3 [4] plyr_1.8.4 iterators_1.0.8 tools_3.2.3 [7] rpart_4.1-10 preprocessCore_1.30.0 gtable_0.2.0 [10] lattice_0.20-33 Matrix_1.2-6 foreach_1.4.3 [13] parallel_3.2.3 gridExtra_2.2.1 cluster_2.0.4 [16] S4Vectors_0.6.6 IRanges_2.2.9 stats4_3.2.3 [19] grid_3.2.3 nnet_7.3-12 impute_1.42.0 [22] Biobase_2.28.0 data.table_1.9.6 AnnotationDbi_1.30.1 [25] survival_2.39-4 foreign_0.8-66 latticeExtra_0.6-28 [28] Formula_1.2-1 GO.db_3.1.2 ggplot2_2.1.0 [31] Hmisc_3.17-4 scales_0.4.0 codetools_0.2-14 [34] matrixStats_0.50.2 splines_3.2.3 BiocGenerics_0.14.0 [37] colorspace_1.2-6 acepack_1.3-3.3 doParallel_1.0.10 [40] munsell_0.4.3 chron_2.3-47 </code></pre>
2
Matlab: How to 'cd' (change directory) to a folder with name as num2str(#number)?
<p>I have a loop and in each iteration I create a directory with the iteration name and I copy some files inside that folder and afterwards I want to <code>cd</code> to that folder, but when I want to <code>cd</code>, I get the error as </p> <p>"Error using cd Cannot CD to num2str(i) (Name is nonexistent or not a directory)." </p> <p>How can I fix this issue?</p> <pre><code>parfor i=1:20000 iter=num2str(i); mkdir(iter) copyfile('./mainfolder',iter) cd ./num2str(i) [pow_maxx,FFee,AA33,BB33,shape] = main(i); power_max(i,:)=pow_maxx(1,:); Fe(i,:)=FFee; A3(i,:)=AA33; B3(i,:)=BB33; Shape_all(i,:)=shape(1,:); end </code></pre>
2
Laravel Relation belongsTo id not recognized
<p>I have those schemas:</p> <pre><code>Schema::create('tickets', function (Blueprint $table) { $table-&gt;increments('id'); $table-&gt;integer('ticket_reason_id')-&gt;unsigned(); $table-&gt;integer('user_id')-&gt;unsigned(); $table-&gt;timestamps(); $table-&gt;foreign('ticket_reason_id')-&gt;references('id')-&gt;on('ticket_reasons')-&gt;onDelete('cascade'); $table-&gt;foreign('user_id')-&gt;references('id')-&gt;on('users')-&gt;onDelete('cascade'); }); Schema::create('ticket_reasons', function (Blueprint $table) { $table-&gt;increments('id'); $table-&gt;string('name'); $table-&gt;timestamps(); }); </code></pre> <p>And those defined relationships</p> <pre><code>class Ticket extends Model { public function user() { return $this-&gt;belongsTo(User::class); } public function reason() { return $this-&gt;belongsTo(TicketReason::class, 'ticket_reason_id'); } } </code></pre> <p>The "reason" method works but I had to manually add the ID. Why do I have to add the id if I'm following the convention? (or at least I think so). It follows the same convention than the user_id column and it doesnt need the id setter.</p>
2
How to add multiple wp_editor in single page
<p>I tried to add multiple wp_editor() in single page and it shows, but when I tried to add media, the media button is not working and I added the option (drag_drop_upload to true) to wp_editor option to make drag and drop and its worked.</p> <p>But when I drag and drop the image, all the images are inserting in the first wp_editor instance. Even I tried to drag and drop in second or third wp_editor, but it again displaying in the first editor.</p> <p>Is there any solution to insert the media either by uploading or drag and drop to the particular wp_editor instance?</p> <p>Thanks</p>
2
Run next in "foreach" only once previous finished in javascript
<p>It might be smth simple, but I just cannot find the way to do it. I have an array, and I want to do a few actions for each array value BUT only once the previous is finished. Lets say I have an array [1,2,3,4,5] and I want to add img tag with a picture with the name "picture"+i+".jpg" ,if picture file doesnt exist - use default picture, do few more actions with that img and, only once its all done, do the next "foreach".</p> <p>I am looking into promises but still cannot figure it out. Problem is that its not just one async action (ajax or get) but a few different actions.</p> <p>Thanks</p>
2
Django - complex calculations in the template
<p>As far as I understand, there's no way to do math including django variables in the template, for example</p> <pre><code>&lt;td&gt;{{variable_1}} + {{variable_2}}&lt;/td&gt; </code></pre> <p>People recommend to do the calculations in the views, but my concern is that we should use servers-side just to transmit data from server to client - that's it. All the calculations should be done using client computer power. The other option might be doing calculations in javascript, particularly jquery, after the page load, but the downside is that data is rendered with a lag in those cases when calculations are very complex. What is the best practice here and most balanced soltion ? </p>
2
Enable/Disable Delete Button with Javascript
<p>I am having an issue with Enabling a button with a checkbox using JavaScript. Whenever I click the checkbox, the Delete button stays disabled.</p> <p>The code I am using is as follows:</p> <pre><code>&lt;script type="text/javascript"&gt; $('#cb_delete').click(function(){ if($(this).attr('checked') == false){ $('#btn-delete').attr("disabled","disabled"); } else { $('#btn-delete').removeAttr('disabled'); } }); &lt;/script&gt; &lt;button type='submit' name='btn-delete' disabled='disabled' id='btn-delete' class='btn btn-default btn-sm'&gt;Delete&lt;/button&gt; &lt;td&gt;&lt;input type='checkbox' name='cb_delete[]' id='cb_delete' value='$mID'&gt;&lt;/td&gt; </code></pre>
2
ng-click doesn't work when open link in new tab is clicked
<p><code>ng-click</code> and <code>ng-href</code> directives when used together will first execute click function. In the following example navigation to Google will be prevented and alert will be shown.</p> <pre><code>&lt;a ng-href='http://google.com' ng-click="click($event)"&gt;Link&lt;/a&gt; $scope.click = function (event) { event.preventDefault(); alert('click has been trigerred'); } </code></pre> <p>This will work though only when user clicks a link using left mouse button. If user will try to open the link in a new tab the click event won't be triggered. To some extent it seems correct because it's not strictly speaking "click", but is there any Angular directive for handling opening link in the new tab?</p> <p><strong>UPDATE:</strong></p> <p>I don't want to open new tab programatically, but handle event of opening new tab by the user.</p>
2
Why its not recommended to pass object to fragment with simple getter setter
<p>I'm new to android, I wonder why this easy method for parameter passing is not recommended.</p> <pre><code>class DemoFragment extends Fragment{ private MyObject myObject; public void setMyObject(MyObject myObject){ this.myObject = myObject; } } DemoFragment fragmentDemo = new DemoFragment(); fragmentDemo.setMyObject(myObject); </code></pre>
2
Import PowerShell Module from C# Failing
<p>I have seen quite a number of solutions, but none addresses my problem. I am trying to import a custom PowerShell module called "DSInternals" to my C# DLL.</p> <p><a href="https://github.com/MichaelGrafnetter/DSInternals" rel="nofollow">https://github.com/MichaelGrafnetter/DSInternals</a></p> <p>Everything in my code seems just fine, but when I try to get the available module it's not loaded.</p> <p>The stream responds with</p> <blockquote> <p>The term 'Get-ADReplAccount' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.</p> </blockquote> <p>Where Am I going wrong with this code?</p> <pre class="lang-cs prettyprint-override"><code>InitialSessionState init = InitialSessionState.CreateDefault(); init.ImportPSModule(new string[] { @"D:\\DSInternals\\dsinternals.psd1" }); //location of the module files Runspace runspace = RunspaceFactory.CreateRunspace(init); runspace.Open(); PowerShell ps = PowerShell.Create(); ps.Runspace = runspace; ps.Commands.AddCommand("Get-ADReplAccount"); //this command is un-recognized foreach (PSObject result in ps.Invoke()) { Console.WriteLine(result); //this always returns null } </code></pre>
2
finding modulus of huge numbers in java
<pre><code> for(i=0; i&lt;n+1; i++) { y=y+(a[i]*(int)Math.pow(j,i)); } int r=y/786433; s[k]=y-(r*786433); k++; </code></pre> <p>Now in this code the <code>j</code> value can be <code>786432</code>. So when I try to get modulus of a number say <code>(1+2*(786432)^2+3*(786432)^3)%786433</code> then I get <code>-521562</code> which is not correct I was using modulus operator before too but I got the same answer even with this approach I am getting the same answer. In this approach the modulus of the number is stored in array <code>s[k]</code>. Can anyone help?</p>
2
Error when settingDBus property
<p>I'm trying to set a property of a DBus Interface with Qt5.7.0. This is the doc:</p> <p><a href="http://git.kernel.org/cgit/network/ofono/ofono.git/tree/doc/modem-api.txt" rel="nofollow">http://git.kernel.org/cgit/network/ofono/ofono.git/tree/doc/modem-api.txt</a></p> <p>and I want to set the <code>Powered</code> property to <code>true</code>. Here my code:</p> <pre><code>QDBusInterface *iface = new QDBusInterface("org.ofono", "/hfp/org/bluez/hci0/dev_xx_xx_xx_xx_xx_xx", "org.ofono.Modem", QDBusConnection::systemBus()); iface-&gt;call("SetProperty", "Powered", QVariant(true)); </code></pre> <p>and this is the error:</p> <blockquote> <p>QDBusError("org.freedesktop.DBus.Error.UnknownMethod", "Method "SetProperty" with signature "sb" on interface "org.ofono.Modem" doesn't exist")</p> </blockquote> <p>The path comes from the <code>GetModem</code> method and it's correct. Also, I tried the same with Python:</p> <pre><code>modem = dbus.Interface(bus.get_object('org.ofono', '/hfp/org/bluez/hci0/dev_xx_xx_xx_xx_xx_xx'), 'org.ofono.Modem') modem.SetProperty('Powered', dbus.Boolean(1)) </code></pre> <p>and it works fine! So the problem is definitely related to my Qt5 code. How to better understand the error message? Is wrong my signature or it doesn't find the <code>SetProperty</code> method at all?</p>
2
Apache CXF 3.1.6 webservice client - NTLM Authentication
<p>I am trying to connect to service authenticated with NTLM. I have client generated with maven cxf plugin wsdl2java. I got an exception: org.apache.cxf.ws.policy.PolicyException: None of the policy alternatives can be satisfied. Maybe there is another way to do this authentication.</p> <pre><code>public class UFENTLM1Test { public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException, InstantiationException { System.out.println("UFE SERVICE TEST (NTLM No1 WRAPPER)"); System.out.println("PARAMS: " + args[1] + " " + args[2] + " "); System.out.println("START"); Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return (new PasswordAuthentication(args[1], args[2].toCharArray())); } }); //LAMAccountAPI service = new LAMAccountAPI(); URL url = LAMAccountAPI.class.getClassLoader().getResource("wsdl/ufe/ufe_account.wsdl"); // TO AVOID SEIStub cannot be cast to ClientProxy LAMAccountAPI service = new LAMAccountAPI(url, LAMAccountAPI.SERVICE); Field delegateField = Service.class.getDeclaredField("delegate"); delegateField.setAccessible(true); ServiceDelegate previousDelegate = (ServiceDelegate) delegateField.get(service); if (!previousDelegate.getClass().getName().contains("cxf")) { ServiceDelegate serviceDelegate = ((Provider) Class.forName("org.apache.cxf.jaxws.spi.ProviderImpl").newInstance()) .createServiceDelegate(url, LAMAccountAPI.SERVICE, service.getClass()); delegateField.set(service, serviceDelegate); } ILAMZarzadzanieKontem port = service.getBasicHttpBindingILAMZarzadzanieKontem(); // Many various tryings Client client = ClientProxy.getClient(port); HTTPConduit http = (HTTPConduit) client.getConduit(); http.getAuthorization().setUserName(args[1]); http.getAuthorization().setPassword(args[2]); AuthorizationPolicy policy = new AuthorizationPolicy(); policy.setUserName(args[1]); policy.setPassword(args[2]); http.setAuthorization(policy); HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); httpClientPolicy.setConnectionTimeout(36000); httpClientPolicy.setAllowChunking(false); http.setClient(httpClientPolicy); List&lt;Konto&gt; accounts = null; try { accounts = port.pobierzKonta().getKonto(); } catch (ILAMZarzadzanieKontemPobierzKontaSOAPExceptionFaultMessage | ILAMZarzadzanieKontemPobierzKontaDataConversionExceptionFaultMessage ilamZarzadzanieKontemPobierzKontaSOAPExceptionFaultMessage) { ilamZarzadzanieKontemPobierzKontaSOAPExceptionFaultMessage.printStackTrace(); } } </code></pre> <p>And policy definition from WSDL:</p> <pre><code>&lt;wsp:Policy wsu:Id="BasicHttpBinding_ILAMZarzadzanieKontem_policy"&gt; &lt;wsp:ExactlyOne&gt; &lt;wsp:All&gt; &lt;http:NtlmAuthentication xmlns:http="http://schemas.microsoft.com/ws/06/2004/policy/http"/&gt; &lt;/wsp:All&gt; &lt;/wsp:ExactlyOne&gt; &lt;/wsp:Policy&gt; </code></pre> <p>Finally, full stacktrace:</p> <pre><code>UFE SERVICE TEST (NTLM No1 WRAPPER) START lip 01, 2016 2:38:20 PM [com.sun.xml.internal.ws.policy.EffectiveAlternativeSelector] selectAlternatives WARNING: WSP0075: Policy assertion "{http://schemas.microsoft.com/ws/06/2004/policy/http}NtlmAuthentication" was evaluated as "UNKNOWN". lip 01, 2016 2:38:20 PM [com.sun.xml.internal.ws.policy.EffectiveAlternativeSelector] selectAlternatives WARNING: WSP0019: Suboptimal policy alternative selected on the client side with fitness "UNKNOWN". lip 01, 2016 2:38:21 PM org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean buildServiceFromWSDL INFO: Creating Service {http://tempuri.org/}LAMAccountAPI from WSDL: file:/C:/dev/work/compfort/warta/3639/iiq-connector/target/classes/wsdl/ufe/ufe_account.wsdl lip 01, 2016 2:38:22 PM org.apache.cxf.ws.policy.AssertionBuilderRegistryImpl handleNoRegisteredBuilder WARNING: No assertion builder for type {http://schemas.microsoft.com/ws/06/2004/policy/http}NtlmAuthentication registered. Exception in thread "main" org.apache.cxf.ws.policy.PolicyException: None of the policy alternatives can be satisfied. at org.apache.cxf.ws.policy.EndpointPolicyImpl.chooseAlternative(EndpointPolicyImpl.java:172) at org.apache.cxf.ws.policy.EndpointPolicyImpl.finalizeConfig(EndpointPolicyImpl.java:146) at org.apache.cxf.ws.policy.EndpointPolicyImpl.initialize(EndpointPolicyImpl.java:142) at org.apache.cxf.ws.policy.PolicyEngineImpl.createEndpointPolicyInfo(PolicyEngineImpl.java:604) at org.apache.cxf.ws.policy.PolicyEngineImpl.getEndpointPolicy(PolicyEngineImpl.java:316) at org.apache.cxf.ws.policy.PolicyEngineImpl.getClientEndpointPolicy(PolicyEngineImpl.java:303) at org.apache.cxf.ws.policy.PolicyDataEngineImpl.getClientEndpointPolicy(PolicyDataEngineImpl.java:61) at org.apache.cxf.transport.http.HTTPConduit.updateClientPolicy(HTTPConduit.java:318) at org.apache.cxf.transport.http.HTTPConduit.updateClientPolicy(HTTPConduit.java:338) at org.apache.cxf.transport.http.HTTPConduit.getClient(HTTPConduit.java:873) at org.apache.cxf.transport.http.HTTPConduit.configureConduitFromEndpointInfo(HTTPConduit.java:360) at org.apache.cxf.transport.http.HTTPConduit.finalizeConfig(HTTPConduit.java:440) at org.apache.cxf.transport.http.HTTPTransportFactory.getConduit(HTTPTransportFactory.java:242) at org.apache.cxf.binding.soap.SoapTransportFactory.getConduit(SoapTransportFactory.java:226) at org.apache.cxf.binding.soap.SoapTransportFactory.getConduit(SoapTransportFactory.java:233) at org.apache.cxf.endpoint.AbstractConduitSelector.createConduit(AbstractConduitSelector.java:145) at org.apache.cxf.endpoint.AbstractConduitSelector.getSelectedConduit(AbstractConduitSelector.java:107) at org.apache.cxf.endpoint.UpfrontConduitSelector.selectConduit(UpfrontConduitSelector.java:77) at org.apache.cxf.endpoint.ClientImpl.getConduit(ClientImpl.java:845) at pl.warta.connector.ufe.test.UFENTLM1Test.main(UFENTLM1Test.java:56) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) </code></pre>
2
Pango Color Glyphs
<p>I am working on a project that uses the following technology to render text:</p> <ul> <li>Freetype - Glyph mapping</li> <li>Pango - Text Layout</li> <li>Skia - Drawing (font color and graphics for rest of system)</li> </ul> <p>We are now trying to add the ability to render colored emoji. Right now it seems that Freetype added the support to specify color glyphs but we have been having issues getting Pango to layout colored font. Is it even possible to render color emoji this way? If we switched from Skia to Cairo would that help?</p> <p>Similarly, I have taken this small example <a href="https://developer.gnome.org/pango/stable/pango-Cairo-Rendering.html" rel="nofollow noreferrer">https://developer.gnome.org/pango/stable/pango-Cairo-Rendering.html</a> and tried to use emoji instead of text and I am not getting the glyph to show even though the font specified is "Apple Color Emoji".</p> <pre><code>#include &lt;math.h&gt; #include &lt;pango/pangocairo.h&gt; #include &lt;cairo.h&gt; static void draw_text (cairo_t *cr) { #define RADIUS 150 #define N_WORDS 10 #define FONT "Apple Color Emoji" PangoLayout *layout; PangoFontDescription *desc; int i; /* Center coordinates on the middle of the region we are drawing */ cairo_translate (cr, RADIUS, RADIUS); /* Create a PangoLayout, set the font and text */ layout = pango_cairo_create_layout (cr); pango_layout_set_text (layout, "", -1); desc = pango_font_description_from_string (FONT); pango_layout_set_font_description (layout, desc); pango_font_description_free (desc); /* Draw the layout N_WORDS times in a circle */ for (i = 0; i &lt; N_WORDS; i++) { int width, height; double angle = (360. * i) / N_WORDS; double red; cairo_save (cr); /* Gradient from red at angle == 60 to blue at angle == 240 */ red = (1 + cos ((angle - 60) * G_PI / 180.)) / 2; cairo_set_source_rgb (cr, red, 0, 1.0 - red); cairo_rotate (cr, angle * G_PI / 180.); /* Inform Pango to re-layout the text with the new transformation */ pango_cairo_update_layout (cr, layout); pango_layout_get_size (layout, &amp;width, &amp;height); cairo_move_to (cr, - ((double)width / PANGO_SCALE) / 2, - RADIUS); pango_cairo_show_layout (cr, layout); cairo_restore (cr); } /* free the layout object */ g_object_unref (layout); } int main (int argc, char **argv) { cairo_t *cr; char *filename; cairo_status_t status; cairo_surface_t *surface; surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, 2 * RADIUS, 2 * RADIUS); cr = cairo_create (surface); cairo_set_source_rgb (cr, 1.0, 1.0, 1.0); cairo_paint (cr); draw_text (cr); cairo_destroy (cr); status = cairo_surface_write_to_png (surface, "/home/mikeobrien/emojiRendering/TESTFILE"); cairo_surface_destroy (surface); if (status != CAIRO_STATUS_SUCCESS) { g_printerr ("Could not save png to '%s'\n", "/home/mikeobrien/emojiRendering/TESTFILE"); return 1; } return 0; } </code></pre> <p><a href="https://i.stack.imgur.com/TPCFT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TPCFT.png" alt="Yeilds this"></a></p>
2
Fill complex image with color
<p>Let's say I have a PNG image with transparency, like so: <a href="https://i.stack.imgur.com/hdZJv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hdZJv.png" alt="sword with transparent background"></a></p> <p>I want, in Java, to fill only the object with black, like so: <a href="https://i.stack.imgur.com/hCIhW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hCIhW.png" alt="sword filled with black"></a></p> <p>This is a fairly trivial process in Photoshop, but this is a process I'd like to repeat frequently, ideally without making a black fill picture for each object I'd like to do it for. I've tried several edge detecting classes but found no success.</p> <p>How would I accomplish this?</p> <p><em>Additional info: this is going to be a quick-and-dirty way to create shadows. If you can think of a better way, that would solve this problem completely.</em> </p>
2
iOS App rejected, how to get permission for downloading contents all over the Internet?
<p>Apple: <strong>- 2.3 LEGAL: INTELLECTUAL PROPERTY - AUDIO/VIDEO DOWNLOADING</strong> </p> <p>I'm building a video downloader app which basically use <em>UIWebView</em> and user can surf the internet and download videos from almost everywhere. <em>App review team</em> is asking me to provide a documentary evidence of rights to allow media downloading from third-party sources.</p> <p>How can I get such document?</p>
2
How to show the username on every page using Spring MVC, Spring Security and FreeMarker
<p>How can I show the username of a user that logged in on the header of every page, I try using the following methods </p> <p>1) this spring security tags like this: </p> <p>first I create a variable security like this </p> <pre><code>&lt;#assign security=JspTaglibs["http://www.springframework.org/security/tags"] /&gt; </code></pre> <p>and then I try to get the username using this <code>authentication</code> tag method that I investigated </p> <pre><code>&lt;@security.authentication property="principal.username"&gt; &lt;/@security.authentication&gt; </code></pre> <p>but I get this error</p> <pre><code> FreeMarker template error: org.springframework.beans.NotReadablePropertyException: Invalid property 'principal.username' of bean class [org.springframework.security.authentication.UsernamePasswordAuthenticationToken]: Bean property 'principal.username' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter? </code></pre> <p>2) I tried getting the username in the controllers and put it in the view like this </p> <pre><code> Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String name = auth.getName(); //get logged in username map.addAttribute("username" , name); </code></pre> <p>that worked but I have too many controllers and I don't want to update all my controllers and put those lines in all my controllers.</p> <p>those are my versions</p> <pre><code>&lt;spring.version&gt;4.2.5.RELEASE&lt;/spring.version&gt; &lt;spring.security.version&gt;4.1.0.RELEASE&lt;/spring.security.version&gt; &lt;artifactId&gt;spring-security-taglibs&lt;/artifactId&gt; &lt;version&gt;4.0.4.RELEASE&lt;/version&gt; &lt;artifactId&gt;freemarker&lt;/artifactId&gt; &lt;version&gt;2.3.21&lt;/version&gt; </code></pre> <p>Any solution is welcome thanks</p>
2
Why is my simple CSS transition animation jerky on smartphones?
<p>After <a href="https://stackoverflow.com/questions/30929040/mobile-menus-jerky-sliding-animation">being advised</a> to switch from jQuery animation to CSS animation in order to make my mobile menu animation smoother, I still find that the animation of the mobile menu opening on a smartphone is jerky and I don't know what to do to improve it.</p> <p>JS:</p> <pre><code>$( '.header__menu_icon' ).click(function() { var allClasses = 'right_0 right_280 right_minus_280'; $( '.mobile_menu, .wrap' ).removeClass( allClasses ); if ( $('.wrap' ).css( 'right' ) == '0px' ) { $( '.wrap' ).addClass( 'right_280' ); } else { $( '.wrap' ).addClass( 'right_0' ); } }); </code></pre> <p>CSS:</p> <pre><code>.mobile_menu { width: 280px; position: absolute; right: -280px; } .right_0 { right: 0 !important; } .right_280 { right: 280px !important; } .right_minus_280 { right: -280px !important; } body, .wrap, .mobile_menu { transition: all 0.2s ease-in-out; } </code></pre> <p>HTML:</p> <pre><code>&lt;body&gt; &lt;div class='wrap'&gt; &lt;div class='header'&gt; &lt;div class='mobile_menu'&gt; ... &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p>EDIT: New code based on @GaijinJim's answer below.</p> <p>JS:</p> <pre><code>$( '.header__menu_icon' ).toggle( function() { $( '.wrap' ).removeClass( 'mobile_menu_opening mobile_menu_closing' ); $( '.wrap' ).addClass( 'mobile_menu_opening' ); }, function() { $( '.wrap' ).removeClass( 'mobile_menu_opening mobile_menu_closing' ); $( '.wrap' ).addClass( 'mobile_menu_closing' ); }); </code></pre> <p>CSS:</p> <pre><code>@keyframes mobile_menu_opening { 0% { transform: translateX(0px); } 100% { transform: translateX(-280px); } } @keyframes mobile_menu_closing { 0% { transform: translateX(-280px); } 100% { transform: translateX(0px); } } .mobile_menu_opening { animation-name: mobile_menu_opening; animation-duration: 2s; } .mobile_menu_closing { animation-name: mobile_menu_closing; animation-duration: 1s; } .wrap { position: relative; } </code></pre>
2
How to check a file is already opened in CreateFile function in Windows
<p>I have to open a handle for a file, before opening the file I need to check whether the file is already opened by another entity. I read CREATE_NEW parameter fails to open the file if already exist. I am opening the file using the api and parameters <code>CreateFile(file_name, GENERIC_WRITE | GENERIC_READ, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);</code></p> <p>Another entity already opened the file, but when I try to open the same file by calling the above api it returns a proper handle and even the getLastError() returns SUCCESS. But expectation is FAILURE should be returned. </p>
2
Why broadcast receiver is not working in background after app closed in Android 6.0+?
<p>The problem is actually in broadcast receiver in Android marshmallow.</p> <pre><code>&lt;receiver android:name="CallReceiver" android:enabled="true" android:exported="true" android:stopWithTask="false" android:permission="android.permission.READ_PHONE_STATE" android:protectionLevel="signature"&gt; &lt;intent-filter&gt; &lt;action android:name="YouNeverKill"/&gt; &lt;/intent-filter&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.PHONE_STATE"/&gt; &lt;action android:name="android.intent.action.NEW_OUTGOING_CALL"/&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; </code></pre>
2
How to get Export buttons, records per page and serach textbox in a single horizontal row in jQuery datatables
<p>Hi am using jQuery datatables.</p> <p>I want all export buttons, records per page and search textbox in a single row above the table something like as shown below.</p> <p><a href="https://i.stack.imgur.com/MVSvX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MVSvX.jpg" alt="enter image description here"></a></p> <p>But I am getting the below output:-</p> <p><a href="https://i.stack.imgur.com/HEibX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HEibX.jpg" alt="enter image description here"></a></p> <p>I am using below function:- </p> <pre><code> $(".mydataTable").dataTable({ "pagingType": "full_numbers", "iDisplayLength": 5, bJQueryUI: true, "aLengthMenu": [[-1, 5, 10, 20, 50], ["All", 5, 10, 20, 50]], dom: 'Bflit', buttons: [ 'copyHtml5', 'excelHtml5', 'csvHtml5', 'pdfHtml5' ] }); </code></pre> <p>What should be the dom option for required result?</p>
2
Android toolbar custom layout element click event
<p>I have created a custom toolbar for my project . Toolbar is working fine and showing . Here is the code for toolbar </p> <p><strong>toolbar.xml</strong> <pre><code> android:elevation="4dp"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_weight="8" android:weightSum="8"&gt; &lt;LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" android:layout_gravity="center_vertical"&gt; &lt;ImageView android:id="@+id/imageToolbal" android:layout_width="0dp" android:layout_height="wrap_content" android:src="@drawable/alert_on" android:layout_weight="4"/&gt; &lt;TextView android:id="@+id/textToolbar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Test" android:layout_weight="4"/&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; &lt;/android.support.v7.widget.Toolbar&gt; </code></pre> <p>layout for main activity</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.app.MainActivity"&gt; &lt;include layout="@layout/toolbar" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>In my <code>onCreate</code> method of the code , I have set up toolbar like this</p> <pre><code> @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } </code></pre> <p>It is showing as expected , but I can't trigger a click event for the layout in toolbar . Like I want to show a <code>Toast</code> if click on the <code>textView</code> in the toolbar with the id <code>textToolbar</code> , or I want to hide and show it conditionally . How can I do it ?</p>
2
Adview from Admob shows blank box if no Internet connection
<p>I just tried to include an Adview in my layout. Works just fine, except that it shows a blank space if there is no Internet connection. As I have read so far, I understand that the standard behaviour for an admob is to take space only if the Ad is shown. Otherwise, eg. no Internet connection, it should take no layout space. I'm listing the code where I think I might have made a mistake and that's why I encounter this odd behaviour...</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" xmlns:ads="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#FFFFFF" android:weightSum="1"&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" android:theme="@style/AppTheme.AppBarOverlay" app:popupTheme="@style/AppTheme.PopupOverlay" /&gt; &lt;include layout="@layout/content_main" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" app:layout_behavior="@string/appbar_scrolling_view_behavior"/&gt; &lt;com.google.android.gms.ads.AdView android:id="@+id/adView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" ads:adSize="BANNER" ads:adUnitId="@string/banner_ad_unit_id"&gt; &lt;/com.google.android.gms.ads.AdView&gt; &lt;/LinearLayout&gt; </code></pre> <p>Then, in app gradle:</p> <pre><code>dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.android.support:design:23.4.0' compile 'com.google.firebase:firebase-core:9.2.0' compile 'com.google.firebase:firebase-ads:9.2.0' } apply plugin: 'com.google.gms.google-services' </code></pre> <p>And in module gradle:</p> <pre><code>dependencies { classpath 'com.android.tools.build:gradle:2.1.0' classpath 'com.google.gms:google-services:3.0.0' </code></pre> <p>I think I have done something wrong, so please help me with an advice. Thank you!</p>
2
How could I access the source code of a .one OneNote file?
<p>How could I access the source code of a .one OneNote file?</p> <p>I've tried to rename the .one file to .zip as what happens with .doc files in order to access their source code, but .one doesn't seem to work like that. Also, I've tried to open it with Notepad++, but it isn't in a plain-text format.</p> <hr> <p><em>I regard this as a programming question because: I'm using content-editing-automation scripts (e.g. RegEx-related find and replace scripts). Accessing the source code of .one files helps me apply bulky automated edits on their content Using RegEx.</em></p>
2
How can I get a detailed log of django csrf failure?
<p>I am troubleshooting a Django app. </p> <p>Recently the app seems to <em>Randomly</em> generate CSRF verification errors:</p> <p><code>CSRF verification failed. Request aborted.</code> (Resulting in a 403)</p> <p><strong>Where can I find detailed information on the cause of the verification failure?</strong></p>
2
LLDB 'thread return' command emits error in a Swift function
<p>I am reading the <a href="https://www.objc.io/issues/19-debugging/lldb-debugging/" rel="noreferrer">Dancing in the Debugger — A Waltz with LLDB</a> article. And I am trying the <code>thread return</code> command with Swift 2.2 as well as Swift 3.0.</p> <p>My code is pretty simple:</p> <pre class="lang-swift prettyprint-override"><code>class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let resust = test() print(resust) } func test() -&gt; Bool { return true } } </code></pre> <p>and I added a breakpoint at the beginning of the <code>test()</code> function with a <code>thread return false</code> action. However, after command+R, my program stops at the breakpoint as expect, but with the following error:</p> <p>"error: Error returning from frame 0 of thread 1: We only support setting simple integer and float return types at present.."</p> <p>Here's a screen shot:</p> <p><img src="https://i.stack.imgur.com/vUrQU.png" alt="codesnapshot1"></p> <p>Then I tried the same in Objective-C code; everything goes well. </p>
2
VB.NET - Salesforce POST Request returns 400 Bad Request Error
<p><strong>NOTE</strong>: I've never written vb.net code before this. I've googled for a solution but did not find anything that worked.</p> <p>I'm trying to get access token from Salesforce. <strong>Below code worked just yesterday</strong>. And I have no idea why it is not working today. I've tried adding content-type as <strong>application/x-www-form-urlencoded</strong> but it did not work either. When I use curl I'm able to get access token. Also I'm able to get access token using advanced rest client in google chrome. Any ideas why it is returning <em>400 Bad Request</em> <strong>unknown error retry your request</strong>?</p> <pre><code>Imports System.Collections.Specialized Imports System.Net Imports System.Text Module Module1 Sub Main() Dim clientId As String = "clientId" Dim clientSecret As String = "clientSecret" Dim redirectUri As String = "https://test.salesforce.com" Dim environment As String = "https://test.salesforce.com" Dim tokenUrl As String = "" Dim username As String = "[email protected]" Dim password As String = "passwordtoken" Dim accessToken As String = "" Dim instanceUrl As String = "" Console.WriteLine("Getting a token") tokenUrl = environment + "/services/oauth2/token" Dim request As WebRequest = WebRequest.Create(tokenUrl) Dim values As NameValueCollection = New NameValueCollection() values.Add("grant_type", "password") values.Add("client_id", clientId) values.Add("client_secret", clientSecret) values.Add("redirect_uri", redirectUri) values.Add("username", username) values.Add("password", password) request.Method = "POST" Try Dim client = New WebClient() Dim responseBytes As Byte() = client.UploadValues(tokenUrl, "POST", values) Dim response As String = Encoding.UTF8.GetString(responseBytes) Console.WriteLine(response) Console.ReadKey() Catch ex As Exception Console.WriteLine(ex.Message) Console.WriteLine("Press any key to close") Console.ReadKey() End Try End Sub End Module </code></pre>
2
Value of type has no member 'measure' when using XCTest on Xcode 8 beta
<p>I'm using Xcode 8 beta, when I create an iOS project with Unit Test included, I added the <code>cocoapods</code> on my <code>Podfile</code>:</p> <pre><code>source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' use_frameworks! pod 'RealmSwift' pod 'Reachability', '~&gt; 3.2' pod 'Alamofire', '~&gt; 3.0' pod 'ChameleonFramework/Swift' pod 'SwiftyBeaver' pod 'GMStepper' </code></pre> <p>Then I ran the command to init the <code>cocoapods</code>:</p> <pre><code>pod install </code></pre> <p>After that I open the <code>project.xcworkspace</code> file and then I get these errors:</p> <blockquote> <p>Swift Compiler Error</p> <p>Value of type '[ProjectName]Tests' has no member measure'</p> </blockquote> <p><a href="https://i.stack.imgur.com/iMGzT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iMGzT.png" alt="enter image description here" /></a></p> <blockquote> <p>Ditto Error</p> <p>Command /usr/bin/ditto failed with exit code 1</p> </blockquote> <p><a href="https://i.stack.imgur.com/BWpC8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BWpC8.png" alt="enter image description here" /></a></p> <p>I just did simple things to create my workspace like I use to do with Xcode 7.3 but this time I can't.</p> <p>And ideas to solve this?</p>
2
How to mock/stub activate() method in AngularJS application
<p>I'm currently working on a large AngularJS application, very much based on the excellent <a href="https://github.com/johnpapa/angular-styleguide/tree/master/a1" rel="nofollow">AngularJS Styleguide by John Papa</a>.</p> <p>One of his recommendations is the use of an <code>activate()</code> method as a sort of bootstrapper for every controller. This makes your code structure clear and you immediately know where bootstrapping begins. Often times, I use it to load data (I prefer this over route-resolves).</p> <p>The problem I'm facing is how should I unit-test the <code>methodUnderTest()</code>-method in the below code example without running the <code>activate()</code>-method.</p> <pre><code>(function() { 'use strict'; angular .module('myApp', []) .controller('ControllerUnderTest', ControllerUnderTest); ControllerUnderTest.$inject = []; /* @ngInject */ function ControllerUnderTest() { var vm = this; // attach functions to vm vm.activate = activate; vm.methodUnderTest = methodUnderTest; // activate activate(); function activate() { // controller start-up logic } function methodUnderTest() { // how to test this method, without running the activate() method } })(); </code></pre> <p>Below is the test-code I currently have, but as you would expect it will always run the <code>activate()</code> method (which is not what I want).</p> <pre><code>(function() { var scope, createController; beforeEach(module('myApp')); describe('ControllerUnderTest', function(){ beforeEach(inject(function($rootScope, $controller) { scope = $rootScope.$new(); createController = function() { return $controller('ControllerUnderTest', { 'scope': scope }); }; })); it('should be defined', function() { var controller = createController(); expect(controller).toBeDefined(); }); it('should have a methodUnderTest', function() { var controller = createController(); expect(controller.methodUnderTest).toBeDefined(); }); }); })(); </code></pre> <p>How do I test <code>ControllerUnderTest.methodUnderTest()</code> without running the <code>activate()</code> method?</p>
2
Fetching JSON data in protractor
<p>I am doing protractor testing where a JSON data must be fetched to do a comparison. A part of JSONArray is shown below,</p> <pre><code>"ATA_Chapter": [ { "@id": "01", "ATA_Chapter_Number": "Chapter 01", "ATA_Chapter_Title": "General Airplane Description" }, { "@id": "02", "ATA_Chapter_Number": "Chapter 02", "ATA_Chapter_Title": "Communications" }] </code></pre> <p>I tried using below code,</p> <pre><code>console.log(json.Root.Catalog.ATA_Chapter[index].ATA_Chapter_Title); </code></pre> <p>In the console ,it is printing the values as,</p> <pre><code>General Airplane Description Communications </code></pre> <p>but protractor is giving error as:</p> <pre><code> Message: Failed: Cannot read property 'ATA_Chapter_Title' of undefined </code></pre> <p>Pls find the portion of spec code where above functionality is written </p> <p><code>var number;var title ; console.log(json.Root.Catalog.ATA_Chapter[index].ATA_Chapter_Title); number = json.Root.Catalog.ATA_Chapter[index].ATA_Chapter_Number; title = json.Root.Catalog.ATA_Chapter[index].ATA_Chapter_Title; var chapterName = number+" "+title; element.all(by.repeater('chapter in chapters')).filter(function (ele,index) { return ele.getText().then(function(text){ console.log('text'+text); return text === chapterName; }); }).click();</code> </p>
2
Bind the progress of a query to a progressProperty of a ProgressBar for informing the user of download and upload time in javaFX?
<p>I got an app that upload and download images to a mysql database but this take like 5 secs and i want to tell the user the progress of this </p> <p>i do the transactions in a task here is the code</p> <pre><code> // progres bar indefinit progressBar.setProgress(-1); Task&lt;Void&gt; task = new Task&lt;Void&gt;() { @Override protected Void call() throws Exception { try { //i net to put to sleep the javafx thread for making a connection Thread.sleep(10); } catch (InterruptedException ex) { ex.printStackTrace(); } Platform.runLater(new Runnable(){ public void run(){ //Coneccts to the data base try(Connection conexionInterna = dbConn.conectarBD()) { //Get the object from the data base rayosVacio = imagenrayos.cargaSolaUnResultado(nuevo.getId_rayos(), conexionInterna); if (rayosVacio!=null) { //sets the image if exists imageView.setImage(rayosVacio.getIma__imaRay()); }else //sets the defauld image imageView.setImage(Nohay); } catch (SQLException e) { e.printStackTrace(); } } }); return null; } }; task.setOnSucceeded(new EventHandler&lt;WorkerStateEvent&gt;() { @Override public void handle(WorkerStateEvent event) { //sets the progress bar in the final to complete progressBar.setProgress(100); } }); Thread tt = new Thread(task); tt.setDaemon(false); tt.start(); </code></pre> <p>with that code i make a intermittent progressBar but this is not what i looking for, looking to have the best UX i think the best is for demonstrate the progress</p> <p>to do this it i think i have to know how many bytes are been transferred for the database to the pc but i dont know how to obtain this information</p> <p>here is how i download images from the database</p> <pre><code> public imagenrayos cargaSolaUnResultado(String dato, Connection conex){ imagenrayos im = null; String sqlSt = "SELECT `id_imaRay`,\n" + "`ima__imaRay`,\n" + "`id_rayos` \n"+ "FROM imagenrayos\n" + "WHERE id_rayos = '"+dato+"';"; try(PreparedStatement stta = conex.prepareStatement(sqlSt); ResultSet res = stta.executeQuery()){ if (res.next()) { byte[] data = res.getBytes("ima__imaRay"); BufferedImage img = ImageIO.read(new ByteArrayInputStream(data)); Image image = SwingFXUtils.toFXImage(img, null); im = new imagenrayos( res.getString ("id_imaRay"), image, res.getString ("id_rayos")); } } catch (SQLException | IOException ex) { ex.printStackTrace(); } return im; } </code></pre> <p>with this i believe i can obtain the size of image an set my 100% target</p> <pre><code>byte[] data = res.getBytes("ima__imaRay"); int sizeofImage = data.length; </code></pre> <p>but here is my doubt, how to track the progress of the data transferred? this is the way or there are better options for making the information available for the user ?</p> <p><strong>EDIT</strong></p> <p>I found a way in Android to do this but i don't see how to implement in my case here is the Android Solution </p> <pre><code>class DownloadFileAsync extends AsyncTask&lt;String, String, String&gt; { @Override protected void onPreExecute() { super.onPreExecute(); showDialog(DIALOG_DOWNLOAD_PROGRESS); } @Override protected String doInBackground(String... aurl) { int count; try { URL url = new URL(aurl[0]); URLConnection conexion = url.openConnection(); conexion.connect(); int lenghtOfFile = conexion.getContentLength(); Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile); InputStream input = new BufferedInputStream(url.openStream()); OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg"); byte data[] = new byte[1024]; long total = 0; while ((count = input.read(data)) != -1) { total += count; publishProgress(""+(int)((total*100)/lenghtOfFile)); output.write(data, 0, count); } output.flush(); output.close(); input.close(); } catch (Exception e) {} return null; } protected void onProgressUpdate(String... progress) { Log.d("ANDRO_ASYNC",progress[0]); mProgressDialog.setProgress(Integer.parseInt(progress[0])); } @Override protected void onPostExecute(String unused) { dismissDialog(DIALOG_DOWNLOAD_PROGRESS); } } } </code></pre> <p>the key here will be how to put the progress of the SQL query inside of a while and there use the <code>updateProgress();</code> method of task to bind this value to the progressProperty of the progressBar in something like this</p> <pre><code>progressBar.progressProperty().bind(task.progressProperty()); </code></pre>
2
Using PHP to Search and Replace POST vars in docx document
<p>I am trying to do a search and replace on a Microsoft Word docx document. The odd problem I am having is that, of the 7 posted vars, 1 and 5 do not replace. In checking Chrome Tools, they all appear in the posted form data. The names are all spelled correctly too. </p> <p>To explain this code, I am opening a template doc, copying it to another name (the named file which will be downloaded), replacing text in document.xml, then replacing text in the footer. Then I close the file and download it. It downloads, except, the vars $pname and $hca2name do not replace inside of the document. All other vars are properly replaced.</p> <p>Any thoughts are very much appreciated. Thank you. Here is the code:</p> <pre><code>&lt;?php $pname = (string) $_POST['pname']; $countyres = (string) $_POST['countyres']; $a1name = (string) $_POST['a1name']; $a2name = (string) $_POST['a2name']; $hca1name = (string) $_POST['hca1name']; $hca2name = (string) $_POST['hca2name']; $atty = (string) $_POST['atty']; $countyres = (string) $_POST['countyres']; $fn = 'POA-'.$pname.'.docx'; $s = "docs_archive/PA-poas2no.docx"; $wordDoc = "POA-".$pname.".docx"; copy($s, $wordDoc); $zip = new ZipArchive; //This is the main document in a .docx file. $fileToModify = 'word/document.xml'; if ($zip-&gt;open($wordDoc) === TRUE) { //Read contents into memory $oldContents = $zip-&gt;getFromName($fileToModify); //Modify contents: $newContents = str_replace('{pname}', $pname, $oldContents); $newContents = str_replace('{a1name}', $a1name, $newContents); $newContents = str_replace('{a2name}', $a2name, $newContents); $newContents = str_replace('{hca1name}', $hca1name, $newContents); $newContents = str_replace('{hca2name}', $hca2name, $newContents); $newContents = str_replace('{atty}', $atty, $newContents); $newContents = str_replace('{countyres}', $countyres, $newContents); //Delete the old... $zip-&gt;deleteName($fileToModify); //Write the new... $zip-&gt;addFromString($fileToModify, $newContents); //Open Footer and change vars there $ft = 'word/footer1.xml'; $oldft = $zip-&gt;getFromName($ft); $newft = str_replace('{pname}', $pname, $oldft); $zip-&gt;deleteName($ft); $zip-&gt;addFromString($ft, $newft); $zip-&gt;close(); header('Content-Description: File Transfer'); header("Content-Type: application/force-download"); header('Content-Type: application/msword'); header('Content-Disposition: attachment; filename="'.$fn.'"'); header('Content-Transfer-Encoding: binary'); header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); readfile($fn); unlink($fn); exit(); } ?&gt; </code></pre>
2
Use Calendar to get the number of days in February
<p>The question is to get day numbers of February of any year. My code is like this:</p> <pre><code>public static void main(String[] args) { System.out.println("2014-02 has " + getDaysOfFeb(2014) + "days"); System.out.println("2016-02 has " + getDaysOfFeb(2016) + "days"); } public static int getDaysOfFeb(int year) { Calendar c = Calendar.getInstance(); // set year-01-31 c.set(year, 0, 31); long lastDayofJan = c.getTimeInMillis(); // set year-03-01 c.set(year, 2, 1); long firstDayOfMar = c.getTimeInMillis(); int date = (int) ((firstDayOfMar - lastDayofJan) / 1000 / 60 / 60 / 24); } </code></pre> <p>I got <code>Jan 31st</code> and <code>Mar 1st</code>, I use the difference of time to calculate the day numbers. But the result is:</p> <pre><code>2014-02 has 29days 2016-02 has 30days </code></pre> <p>I don't understand why.</p> <p>When I do like this:</p> <pre><code>public static int getDaysOfFeb(int year) { Calendar c = Calendar.getInstance(); // set year-01-31 c.set(year, 2, 1); c.add(Calendar.DATE, -1); // last day of Feb int date = c.get(Calendar.DATE); return date; } </code></pre> <p>The result is right, as follow:</p> <pre><code>2014-02 has 28days 2016-02 has 29days </code></pre> <p>Does anyone know what the difference is here?</p>
2
Concatenate string members using Linq PredicateBuilder for text search
<p>I have a REST WebAPI using <code>EntityFramework</code> database first. All code is generated off the <code>EDMX</code> file, entities, repository classes and API controllers etc.</p> <p>I have added some filtering functionality which allows users to add conditions via the query string that translate to <code>LinqKit PredicateBuilder / Linq</code> expressions that filter results when hitting the db.</p> <pre><code>e.g. /api/Users?FirstName_contains=Rog </code></pre> <p>This will return all users with 'Rog' in the <code>User.FirstName</code> member. This uses <code>PredicateBuilder</code> to dynamically build an appropriate <code>Linq</code> expression to then use as a <code>Where</code> clause against the <code>DbSet</code>. </p> <p>For example:</p> <pre><code>var fieldName = "FirstName"; var value = "Rog"; var stringContainsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) }); var parameter = Expression.Parameter(typeof(User), "m"); var fieldAccess = Expression.PropertyOrField(parameter, fieldName); var fieldType = typeof(User).GetProperty(fieldName, BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public).PropertyType; var expression = Expression.Lambda&lt;Func&lt;User, bool&gt;&gt;(Expression.Call(fieldAccess, stringContainsMethod, Expression.Constant(value, fieldType)) , parameter) var andPredicate = PredicateBuilder.True&lt;User&gt;(); andPredicate = andPredicate.And(expression); var query = Db.Users .AsQueryable() .AsExpandable() .Where(andPredicate); </code></pre> <p>Now the problem. I want the client to be able to match results based on a composition of members. </p> <pre><code>e.g. /api/Users?api_search[FirstName,LastName]=Rog </code></pre> <p>i.e. search <code>first name + last name</code> for matches of 'Rog', so I could search for 'Roger Sm' and get a result for first name = Roger and last name = Smith.</p> <p>If I was to query the <code>DbSet</code> using fluent it would look like:</p> <pre><code>users.Where(u =&gt; (u.FirstName + " " + u.LastName).Contains("Rog")); </code></pre> <p>What I am struggling with is creating a <code>predicate / linq</code> expression that will handle the concatenation of string members <code>FirstName + " " + LastName</code> dynamically.</p>
2
pandas dataframe reshape after pivot
<p>The pivot code:</p> <pre><code>result = pandas.pivot_table(result, values=['value'], index=['index'], columns=['columns'], fill_value=0) </code></pre> <p>The result: </p> <pre><code> value value value columns col1 col2 col3 index idx1 14 1 1 idx2 2 0 1 idx3 6 0 0 </code></pre> <p>I tried:</p> <pre><code>result.columns = result.columns.get_level_values(1) </code></pre> <p>Then I got this:</p> <pre><code>columns col1 col2 col3 index idx1 14 1 1 idx2 2 0 1 idx3 6 0 0 </code></pre> <p>Actually what I would like is this one:</p> <pre><code>index col1 col2 col3 idx1 14 1 1 idx2 2 0 1 idx3 6 0 0 </code></pre> <p>Is there anyway to achieve this? Help really is appreciated. Thank you in advance.</p>
2
Api gateway 304 responses with Last-Modified header
<p>I want to response a 304 response with Last-Modified header.</p> <p>At first I use Error response to implement.</p> <p>Handler.js</p> <pre><code>module.exports.handler = function(event, context, cb) { const UpdateDate = new Date(); return cb("304 Not Modified", { "Last-Modified": UpdateDate, "body":{ "message": {} } }); }; </code></pre> <p>s-function.json in endpoints</p> <pre><code>"responses": { "304 Not Modified.*": { "statusCode": "304", "responseParameters": { "method.response.header.Last-Modified": "integration.response.body.Last-Modified" }, "responseModels": { "application/json;charset=UTF-8": "Empty" }, "responseTemplates": { "application/json;charset=UTF-8": "$input.json('$.body')" } }, "default": { "statusCode": "200", "responseParameters": { "method.response.header.Cache-Control": "'public, max-age=86400'", "method.response.header.Last-Modified": "integration.response.body.Last-Modified" }, "responseModels": { "application/json;charset=UTF-8": "Empty" }, "responseTemplates": { "application/json;charset=UTF-8": "$input.json('$.body')" } } } </code></pre> <p>However, I find it on Lambda doc.</p> <blockquote> <p>If an error is provided, callback parameter is ignored.</p> </blockquote> <p>So, this doesn't work. </p> <p>Is there any solution to response a 304 response with header?</p> <p>Updated:</p> <p>Is it possible to return a Error object and map responses 304 in s-function? Below code can't map to 304.</p> <p>s-funtion.json</p> <pre><code>"responses": { ".*304 Not Modified.*": { "statusCode": "304", "responseParameters": { "method.response.header.Cache-Control": "'public, max-age=86400'", "method.response.header.Last-Modified": "integration.response.body.errorMessage.Last-Modified" } } </code></pre> <p>Handler.js</p> <pre><code>return cb({ "status" : "304 Not Modified", "Last-Modified": UpdateDate ), null); </code></pre> <p>I also try this. It can mapping to 304 but header can't get "integration.response.body.errorMessage.Last-Modified"</p> <pre><code>return cb(JSON.stringify({ "status" : "304 Not Modified", "Last-Modified": UpdateDate }), null); </code></pre> <p>I try $util.parseJson but not working on responseParameter.</p> <blockquote> <p>Invalid mapping expression specified:$util.parseJson($input.path('$.errorMessage')).Last-Modified</p> </blockquote> <pre><code> "responseParameters": { "method.response.header.Cache-Control": "'public, max-age=86400'", "method.response.header.Last-Modified": "$util.parseJson($input.path('$.errorMessage')).Last-Modified" }, </code></pre>
2
Calico NetworkPlugin cni failed on the status hook for pod 'nginx' - invalid CIDR address: Device "eth0" does not exist
<p>I have the following kubelet error on my minions:</p> <pre><code>Jul 02 16:20:42 sc-minion-1 kubelet[46142]: E0702 16:20:42.899902 46142 manager.go:309] NetworkPlugin cni failed on the status hook for pod 'nginx' - invalid CIDR address: Device "eth0" does not exist. </code></pre> <p>My 10-calico.conf on all nodes looks like this:</p> <pre><code>{ "name": "calico-k8s-network", "type": "calico", "etcd_authority": "172.1.1.4:6666", "log_level": "info", "ipam": { "type": "calico-ipam" } } </code></pre> <p>I also ran: <code>calicoctl pool add 192.168.0.0/16 --ipip --nat-outgoing</code> on all nodes.</p>
2
Set breakpoint in Racket?
<p>Using Emacs/geiser with Racket (not DrRacket), how could I set a breakpoint and then step through the code, halting at breakpoint(s)? For example, I've got this code:</p> <pre><code>(define (powerset4 lst) (if (null? lst) '(()) (append-map (lambda (x) (begin (fprintf (current-output-port) "~s ~s ~s\n" x lst x) (list x (cons (car lst) x)))) (powerset4 (cdr lst))))) </code></pre> <p>and I want to stop inside the <code>begin</code> sequence to see what's happening and what the values are. It would also be nice to not rely on ye 'ol <code>printf</code> tricks either, i.e., track certain parameters as well. Again, I'm in Emacs and using Geiser. Actually, I'd switch to Guile or Chicken (Geiser languages) if I could do this better with them.</p>
2
Java: add to map of collections
<p>I'm trying to write a generic function that will add an element to a <code>Map</code> of <code>Collection</code>s. This works for a <code>Map</code> of <code>List</code>s:</p> <pre><code>public static &lt;TKey, TVal&gt; void addToMapOfLists(Map&lt;TKey, List&lt;TVal&gt;&gt; map, TKey key, TVal val) { List&lt;TVal&gt; list = map.get(key); if (list == null) { list = new ArrayList&lt;&gt;(); list.add(val); map.put(key, list); } else list.add(val); } </code></pre> <p>I want to make this function work on <code>Map&lt;TKey, Set&lt;TVal&gt;&gt;</code> as well as on <code>Map&lt;TKey, List&lt;TVal&gt;&gt;</code>. I expect this should be possible because both implement <code>Collection</code> that has the <code>add(TVal)</code> member that I call.</p> <p>My problem is that when I try change the parameter <code>Map&lt;TKey, List&lt;TVal&gt;&gt; map</code> to <code>Map&lt;TKey, ? extends Collection&lt;TVal&gt;&gt; map</code> - I need to somehow replace <code>new ArrayList&lt;&gt;();</code> with a call to the constructor of the implementer of <code>Collection</code>.</p>
2
Android Firebase createUser() is not Working
<p>I'm trying to create a user in the Firebase console using email and password but it doesn't work showing an error. Actually we can add users in the console by going to the dashboard and clicking on <code>add user</code> but I want to automate this process.</p> <p>Here's the full code:</p> <pre><code> import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.firebase.client.AuthData; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import java.util.Map; public class SignInActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener { private static final String TAG = "SignInActivity"; private static final int RC_SIGN_IN = 9001; private SignInButton mSignInButton; private Button but; private EditText email; private EditText password; private FirebaseAuth mAuth; private FirebaseUser mFirebaseUser; private GoogleApiClient mGoogleApiClient; private FirebaseAuth mFirebaseAuth; String user_id="",pass=""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_in); email=(EditText)findViewById(R.id.emails); password=(EditText)findViewById(R.id.passwords); but=(Button)findViewById(R.id.create); Firebase.setAndroidContext(getBaseContext()); mAuth = FirebaseAuth.getInstance(); but.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { user_id= email.getText().toString(); pass= password.getText().toString(); Firebase ref = new Firebase("https://final-6b828.firebaseio.com/auth"); ref.createUser(user_id, pass, new Firebase.ValueResultHandler&lt;Map&lt;String, Object&gt;&gt;() { @Override public void onSuccess(Map&lt;String, Object&gt; result) { System.out.println("Successfully created user account with uid: " + result.get("uid")); String a= result.get("uid").toString(); Log.i("Success",user_id); Log.i("Success",pass); Toast.makeText(getApplicationContext(), "Pass", Toast.LENGTH_LONG).show(); } @Override public void onError(FirebaseError firebaseError) { // there was an error System.out.println("Failed to create user account : "); Log.i("Failed","a"); Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show(); } }); } }); mSignInButton = (SignInButton) findViewById(R.id.sign_in_button); mSignInButton.setOnClickListener(this); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); // Initialize FirebaseAuth mFirebaseAuth = FirebaseAuth.getInstance(); } private void handleFirebaseAuthResult(AuthResult authResult) { if (authResult != null) { FirebaseUser user = authResult.getUser(); Toast.makeText(this, "Welcome " + user.getEmail(), Toast.LENGTH_SHORT).show(); startActivity(new Intent(this, MainActivity.class)); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.sign_in_button: signIn(); break; default: return; } } private void signIn() { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); if (result.isSuccess()) { GoogleSignInAccount account = result.getSignInAccount(); firebaseAuthWithGoogle(account); Log.e(TAG, "Google Sign In Successfull."); } else { Log.e(TAG, "Google Sign In failed."); } } } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d(TAG, "firebaseAuthWithGooogle:" + acct.getId()); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mFirebaseAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener&lt;AuthResult&gt;() { @Override public void onComplete(@NonNull Task&lt;AuthResult&gt; task) { Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); if (!task.isSuccessful()) { Log.w(TAG, "signInWithCredential", task.getException()); Toast.makeText(SignInActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } else { startActivity(new Intent(SignInActivity.this, MainActivity.class)); finish(); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Log.d(TAG, "onConnectionFailed:" + connectionResult); Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show(); } } } </code></pre> <p>The code used to create an user is :</p> <pre><code>but.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { user_id= email.getText().toString(); pass= password.getText().toString(); Firebase ref = new Firebase("https://final-6b828.firebaseio.com/auth"); ref.createUser(user_id, pass, new Firebase.ValueResultHandler&lt;Map&lt;String, Object&gt;&gt;() { @Override public void onSuccess(Map&lt;String, Object&gt; result) { System.out.println("Successfully created user account with uid: " + result.get("uid")); String a= result.get("uid").toString(); Log.i("Success",user_id); Log.i("Success",pass); Toast.makeText(getApplicationContext(), "Pass", Toast.LENGTH_LONG).show(); } @Override public void onError(FirebaseError firebaseError) { // there was an error System.out.println("Failed to create user account : "); Log.i("Failed","a"); Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show(); } }); } }); </code></pre>
2
Getting a Column on the next Row on excel with Macro
<p>i need as the title says to put the data from a column onto the next row. After a lot of research i learned that it can be done using macros and this is where i need your help.</p> <p>Example of what i need to do:</p> <p>What i mean is that i have an excel doc with 4 columns</p> <pre><code> A B C D 1 Data1 Data2 Data3 Data4 2 Data5 Data6 Data7 Data8 </code></pre> <p>I want every D column data to go to the next line like this.</p> <pre><code> A B C 1 Data1 Data2 Data3 2 Data4 // First Data of D column on below line moved on line 2 3 Data5 Data6 Data7 4 Data8 // Second Data of D column on below line moved on line 4. </code></pre> <p>So i recorded a macro of adding a line on "2" and cuttin-paste the first D on the new 2. The code is this:</p> <pre><code>Sub Data1() ' ' Data1 Macro ' ' ' ActiveCell.Offset(1, 0).Range("A1:D1").Select Selection.EntireRow.Insert , CopyOrigin:=xlFormatFromLeftOrAbove ActiveCell.Offset(-1, 3).Range("A1").Select Selection.Cut ActiveCell.Offset(1, -3).Range("A1").Select ActiveSheet.Paste End Sub </code></pre> <p>Result: </p> <p><a href="https://i.stack.imgur.com/Ez0Ni.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ez0Ni.png" alt="https://s32.postimg.org/xqofxu1lh/Work1.png"></a></p> <p>The thing is that with a lot of data that needs to be run a lot of times so a loop is really needed here.</p> <p>Tried using a loop but iam stack here and there is where i need your help</p> <p>Thats how far iam but it doesnt work now as it should.</p> <pre><code>Dim x As Integer Sub Data1() ' ' Data1 Macro ' ' ' x = 1 Do While x &lt;= 20 ' that i will change as how many columns i have. ActiveCell.Offset(x, 0).Range("A1:D1").Select Selection.EntireRow.Insert , CopyOrigin:=xlFormatFromLeftOrAbove ActiveCell.Offset(x - 2, x + 2).Range("A1").Select Selection.Cut ActiveCell.Offset(x, x - 4).Range("A1").Select ActiveSheet.Paste x = x + 2 ' if it starts from cell no1 and we have a blank to fill with Data4 or Data8 of D row then we need x+2 i believe and not x+1. Loop End Sub </code></pre> <p>Result with lots of data and 2nd modified (not working) code:</p> <p><a href="https://i.stack.imgur.com/LBAou.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LBAou.png" alt="https://s31.postimg.org/c1ffzj4nv/Notwork.png"></a></p> <p>thanks in advance.</p>
2
Change Simulator Location using Xcode's UITesting
<p>Just wondering if it is possible to use UITesting in xcode to somehow code in custom locations for the simulator. We have an app that involves a number of location changes and would be great if we could automate the changes in location as part of our UITesting suite.</p>
2
How to stop the mousemove event on clicking outside the window
<p>on clicking the outside the window the mousemove event has to be stopped`,i have detected the click outside the window on mouseleave,but how to prevent the default even?in Javascript</p> <pre><code>onTextContainerMouseLeave: function (e) { if (this.curDown == true) { var value; $(window).on('mouseup', function (e) { this.curDown = false; e.preventDefault(); e.stopPropagation(); return false; }); } </code></pre> <p>},</p>
2
Extension Methods and method overriding
<p>The other day I found this statement in a stackoverflow post relating to Extension Methods:</p> <blockquote> <p>The main thing there is ability to override different methods based on different generic’s parameters instantiation. This is similar to Haskell’s type classes</p> </blockquote> <p><a href="https://stackoverflow.com/questions/4359979/java-equivalent-to-c-sharp-extension-methods/27785184#27785184">Java equivalent to C# extension methods</a></p> <p>What's that supposed to mean? Can anybody give a significant example which clarifies this statement?</p>
2
QTcpSocket delay/buffering issue
<p>I have two instances of my Qt application communicating via QTcpSockets</p> <p>Some packets get stuck and are not received until the next packet is sent. This happens even if the next packet is sent several minutes after. So it seems there is some buffering which has no timeout.</p> <p>I have tried QTcpSocket::flush() on the sender, without success. This happens with one Qt build (5.6.1) and not with another (5.4.2). Both are built with MinGW-w64 (Windows platform)</p> <p>When I say the packet is not received, I mean that bytesAvailable() stays at zero (I have checked with a polling timer for debugging). readyRead() is never emitted as well.</p> <p>For instance, I'm sending packet A and packet B just after. Then, I send packet C two minutes later. The receiver gets a complete packet A, but no packet B, and the socket has no bytes available for reading. When packet C is sent, I receive packets B and C.</p>
2
How some apps track their own uninstall on android
<p>I found that <a href="https://play.google.com/store/apps/details?id=com.qihoo.security" rel="nofollow noreferrer">360 security app</a> after uninstall open their page in browser. </p> <p>They can do it on all android versions (4.<em>, 5.</em> and 6.*) and I don't understand how. </p> <p>Maybe someone have any ideas? I know about same questions <a href="https://stackoverflow.com/questions/5132472/can-code-be-called-when-my-android-application-is-uninstalled">here</a> and <a href="https://stackoverflow.com/questions/18692571/how-can-an-app-detect-that-its-going-to-be-uninstalled">here</a> and others but they still have no answers. </p> <p>It's not a bug with <code>inotify</code> because its works only on &lt; 4.4.2 android, there is no other processes which listen for same bug in new way, I checked. </p> <p>They had some magic in their lib <code>eternity.so</code></p>
2
JS: how to listen for function execution?
<p>I need to implement a listener which will perform a certain action if FunctionA is called on the page at any time (during or after page load).</p> <p>Or in other words I need to listen for an execution of FunctionA.</p> <p>How to achieve this?</p> <p>Thank you.</p>
2
Python 2.x - sleep call at millisecond level on Windows
<p>I was given some very good hints in this forum about how to code a clock object in Python 2. I've got some code working now. It's a clock that 'ticks' at 60 FPS:</p> <pre><code>import sys import time class Clock(object): def __init__(self): self.init_os() self.fps = 60.0 self._tick = 1.0 / self.fps print "TICK", self._tick self.check_min_sleep() self.t = self.timestamp() def init_os(self): if sys.platform == "win32": self.timestamp = time.clock self.wait = time.sleep def timeit(self, f, args): t1 = self.timestamp() f(*args) t2 = self.timestamp() return t2 - t1 def check_min_sleep(self): """checks the min sleep time on the system""" runs = 1000 times = [self.timeit(self.wait, (0.001, )) for n in xrange(runs)] average = sum(times) / runs print "average min sleep time:", round(average, 6) sort = sorted(times) print "fastest, slowest", sort[0], sort[-1] def tick(self): next_tick = self.t + self._tick t = self.timestamp() while t &lt; next_tick: t = self.timestamp() self.t = t if __name__ == "__main__": clock = Clock() </code></pre> <p>The clock does not do too bad, but in order to avoid a busy loop I'd like Windows to sleep less than the usual about 15 milliseconds. On my system (64-bit Windows 10), it returns me an average of about 15 / 16 msecs when starting the clock if Python is the only application that's running. That's way too long for a min sleep to avoid a busy loop.</p> <p>Does anybody know how I can get Windows to sleep less than that value?</p>
2
TableView change all the rows when I try to edit one column value in javafx
<p>I have a <code>TableView</code> that has its items property bound to a class <code>Group</code>'s <code>applications</code> property which is declared as :</p> <pre><code>ObjectProperty&lt;ObservableList&lt;Application&gt;&gt; applications = new SimpleObjectProperty(); </code></pre> <p>it is initialised as :</p> <pre><code>applications.set(new FXCollections.observableArrayList&lt;Application&gt;()); applications.get().add(new Application()); applications.get().add(new Application()); </code></pre> <p>The class <code>Application</code> class contains some properties and another class <code>Customer</code> declared and initialised as :</p> <pre><code>ObjectProperty&lt;Customer&gt; customer = SimpleObjectProperty&lt;&gt;(new Customer()); </code></pre> <p>Now there are four columns in the tableView that are editable they are 'ApplicationNo', 'ApplicationDate', 'CustomerId' and 'CustomerName'. The first 2 column's cell value factory is set to <code>Application</code> class's <code>applicationNo</code> and <code>applicationDate</code> properties. and the last 2 column's cell value factory are set to the <code>Application</code> class's <code>customer</code> property's <code>customerId</code> and <code>customerName</code> properties. All the four columns are editable with combobox control that are populated with values from the database.</p> <p>In addition to the above stated table view, I have a form in the FXML consisting of fields that are there in the <code>Application</code> class and the <code>Customer</code> class. This form is disabled when no table row is selected and is enabled with the values of the <code>Application</code> instance, when any of the table view row is selected.</p> <p>Now my problem is when I select any row and edit the values in the form or in the table, all the row attain the new value that I enter.</p> <p>I am not uploading the code because it is very lengthy.</p> <p><strong>the code for <code>updateItem</code> method of table cell editor</strong></p> <pre><code>protected void updateItem(T item, boolean empty) { super.updateItem(item, empty); if (isEmpty()) { setText(null); setGraphic(null); } else { if (isEditing()) { if (control != null) { updateControl(); } setGraphic(control); setContentDisplay(ContentDisplay.GRAPHIC_ONLY); } else { setText(getItemText()); setGraphic(null); setContentDisplay(ContentDisplay.TEXT_ONLY); } } </code></pre> <p>Code for cell factory and cell value factory of column <code>applicationNo</code></p> <pre><code> applicationNo.setCellValueFactory( new Callback&lt;TableColumn.CellDataFeatures&lt;GroupRow, ApplicationModel&gt;, ObservableValue&lt;ApplicationModel&gt;&gt;() { //GroupRow is the object that contains the Application object @Override public ObservableValue&lt;ApplicationModel&gt; call(CellDataFeatures&lt;GroupRow, ApplicationModel&gt; param) { return param.getValue().getApplicationProperty(); } }); applicationNo.setCellFactory( new Callback&lt;TableColumn&lt;GroupRow, ApplicationModel&gt;, TableCell&lt;GroupRow, ApplicationModel&gt;&gt;() { @Override public TableCell&lt;GroupRow, ApplicationModel&gt; call(TableColumn&lt;GroupRow, ApplicationModel&gt; param) { return new ApplicationTableCellEditor(); //ApplicationTableCellEditor is custom TableCell } }); applicationNo.setOnEditCommit(new EventHandler&lt;TableColumn.CellEditEvent&lt;GroupRow, ApplicationModel&gt;&gt;() { @Override public void handle(CellEditEvent&lt;GroupRow, ApplicationModel&gt; event) { event.getRowValue().setApplication(event.getNewValue()); tableChanged(); applicationChanged(event.getNewValue()); } }); </code></pre>
2
Making curved text on coord_polar
<p>I want make curved text around ggplot with coord_polar. I have data.frame:</p> <pre><code>z &lt;- data.frame( a=c("sensor 1","sensor 2","sensor 3","sensor 4","sensor 5","sensor 6","sensor 7","sensor 8"), b=c(50, 60, 70, 20,90,110,30,100)) </code></pre> <p>And here is code where I create my ggplot:</p> <pre><code>cxc &lt;- ggplot(z, aes(x=a, y=b, fill=factor(b))) + geom_bar(width = 1,stat="identity",colour = "black") cxc + coord_polar() + theme_linedraw() +theme(axis.ticks =element_blank(), axis.text.y =element_blank(), axis.title=element_blank(), axis.text.x=element_text(size = 12,angle = 45)) </code></pre> <p>Here is image from my result. I want making texts (x axis): sensor 1, sensor 2... making curved like I draw with red color around circle from coord_polar. Must fit with circle. <a href="https://i.stack.imgur.com/QgOoc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QgOoc.png" alt="enter image description here"></a></p>
2
Text should be printed in new line when text is longer than field width
<p>I am really new to JasperReports and have the following issue: </p> <p>I would like to print the date with time zone in some colum but the colum width is not enough for printing the date:</p> <p><a href="https://i.stack.imgur.com/nn81w.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nn81w.png" alt="enter image description here"></a></p> <p>How to tell jasper that it has to print the time zone in new line? something like this:</p> <pre><code>2016-07-07 16:32:35 +02:00 EUROPE/BERLIN </code></pre> <p>I use Jaspersoft iReport Desinger 4.7.0.</p> <p><strong>UPDATE:</strong></p> <p>the field looks like this: </p> <pre><code>&lt;field name="date" class="java.lang.String"/&gt; .. .. &lt;textField isStretchWithOverflow="true"&gt; &lt;reportElement uuid="6e3cbfd4-f1e9-453f-b3d8-39ae6231931d" key="element-1863" style="column details" stretchType="RelativeToBandHeight" x="626" y="0" width="216" height="12"/&gt; &lt;textElement textAlignment="Center"/&gt; &lt;textFieldExpression&gt;&lt;![CDATA[$F{date}]]&gt;&lt;/textFieldExpression&gt; &lt;/textField&gt; .. .... </code></pre>
2
Compress animated gif image size using c#
<p>I wanted to create animated gif image from several images using c#, so i have used below github solution to do so.</p> <p><a href="https://github.com/DataDink/Bumpkit" rel="noreferrer">https://github.com/DataDink/Bumpkit</a></p> <p>I am using below code to do it</p> <pre><code>using (var gif = File.OpenWrite(@"C:\IMG_TEST.gif")) using (var encoder = new GifEncoder(gif)) for (int i = 0, count = imageFilePaths.Length; i &lt; count; i++) { Image image = Image.FromFile(imageFilePaths[i]); encoder.AddFrame(image,0,0); } </code></pre> <p>it is working like a charm, but it is creating gif of size 45 MB. If i check my actual image size , then it is only 11MB with total 47 images. but somehow gif is generating with big size.</p> <p>Now i want to compress the size of gif image which is being created using c#.</p> <p>So is there any way i can compress the size of gif image?</p>
2
Xamarin.Android binding Spongy Castle / Bouncy Castle
<p>Anyone successfully bound <a href="https://rtyley.github.io/spongycastle/" rel="nofollow noreferrer">SpongyCastle</a> to Xamarin.Android? I bump into a bunch of warnings with my Metadata.xml in the binding project.</p> <p>So far I have:</p> <pre><code>&lt;remove-node path="/api/package[@name='org.spongycastle.x509']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.crypto']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.crypto.tls']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.cms']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.crypto.prng']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.openpgp']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.openssl']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.cert.ocsp']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jcajce']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jcajce.provider.asymmetric.dh']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jcajce.provider.asymmetric.ec']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jcajce.provider.digest']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jcajce.provider.keystore.bc']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jcajce.provider.symmetric']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jcajce.provider.asymmetric.dsa']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jcajce.provider.asymmetric.util']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jcajce.provider.symmetric.util']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jcajce.provider.asymmetric.gost']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jcajce.provider.asymmetric.ies']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jcajce.provider.asymmetric.rsa']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jcajce.provider.asymmetric.x509']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jce.provider']/class[@name='CertStoreCollectionSpi']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jce.provider']/class[@name='MultiCertStoreSpi']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jce.provider']/class[@name='X509CRLEntryObject']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jce.provider']/class[@name='X509CRLObject']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jce.provider']/class[@name='X509CertificateObject']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jce.provider']/class[@name='X509LDAPCertStoreSpi']"/&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.jce.provider']/class[@name='PKIXPolicyNode']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.pqc.jcajce.provider.rainbow']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.pqc.jcajce.provider.mceliece']"/&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.pqc.jcajce.provider.util']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.pqc.crypto.ntru']" /&gt; &lt;remove-node path="/api/package[@name='org.spongycastle.pqc.math.ntru.polynomial']" /&gt; </code></pre> <p>So it compiles, but when using the binding project in the Xamarin.Android project it takes several mins. to compile and then it fails complaining about the HEAP size of Java. </p> <p>When I set the heap size to 1GB, it completes, but debugging is then broken when running the app in debug mode on device.</p> <p>Is there a way to just use the ARRs without a binding library? I just need to invoke a wrapper method that I made in this ARR and get the output from that. I don't need to access the full library through C#. Or is there a better way?</p> <p>Update: And when I build the CPU looks like this (Look at Java): <a href="https://i.stack.imgur.com/u3lpJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u3lpJ.png" alt="enter image description here"></a></p>
2
Getting a Recursive Query to work in Access 2013
<p>After a day's worth of research, I thought I was just at the finish line with my problem. I got myself all schooled up on recursive queries and managed to get it to execute beautifully in SQL Server Management Studio 2014. However, I was immediately shot down when translating the query I wrote in SQL Server 2014 into my Access 2013 application. Reading other articles, I now understand that Access does not support recursive queries. With that, I need help finding a resource-efficient way to pull these records and put them into an array variable. My past efforts in emulating this in VBA were horrific; resulting in 30-60 seconds to process. Any advise on how to lean this process out would be greatly appreciated.</p> <p>The recursive query I would like to emulate is:</p> <pre><code>WITH MyCTE(BusinessUnitID, Active) AS( SELECT a.BusinessUnitID, a.Active FROM t_EMS_BM_BusinessUnits AS a WHERE BusinessUnitID = 7 UNION ALL SELECT d.BusinessUnitID, d.Active FROM MyCTE AS c INNER JOIN t_EMS_BM_BusinessUnits AS d ON c.BusinessUnitID = d.ParentUnit) SELECT * FROM MyCTE WHERE Active = 1 </code></pre> <p>My atrocious VBA script is:</p> <pre class="lang-vb prettyprint-override"><code>Private Sub LoadArray(intBU As Integer) 'set rollup data for business unit by adding all child units to intBUs array Dim sql As String Dim rs As Recordset Dim intCount As Integer sql = "SELECT BusinessUnitID, ParentUnit FROM t_EMS_BM_BusinessUnits WHERE Active = true ORDER BY BusinessUnitID" Set rs = currentdb.OpenRecordset(sql, dbOpenDynaset, dbSeeChanges) 'look for child units With rs intCount = 0 ReDim intBUs(1 To 1) As Integer If Not .EOF And Not .BOF Then .MoveLast .MoveFirst Do While Not .EOF If IsChild(intBU, !BusinessUnitID) = True Then 'add to array intCount = intCount + 1 If intCount &gt; 1 Then ReDim Preserve intBUs(1 To UBound(intBUs) + 1) As Integer intBUs(UBound(intBUs)) = !BusinessUnitID ElseIf intCount = 1 Then intBUs(UBound(intBUs)) = !BusinessUnitID End If End If .MoveNext Loop End If .Close End With Set rs = Nothing Private Function IsChild(TargetBU, CurrentBU As Integer) As Boolean 'check if unit is lowest level child 'is TargetBU a child of CurrentBU? Dim intX As Integer Dim intCount As Integer intX = 0 If TargetBU = CurrentBU Then 'return a value of true IsChild = True Else Do Until intX = -1 'find bottom level of heiarchy intCount = DCount("BusinessUnitID", "t_EMS_BM_BusinessUnits", "ParentUnit=" &amp; CurrentBU) If intCount = 0 Then intX = -1 Else CurrentBU = DLookup("BusinessUnitID", "t_EMS_BM_BusinessUnits", "ParentUnit=" &amp; CurrentBU) intX = 0 End If Loop 'reset sentinal value intX = 0 Do Until intX = -1 'tree up until the record matches the TargetBU or reaches the top "0" If CurrentBU = TargetBU Or CurrentBU = 0 Then IsChild = True intX = -1 Else 'move up to the next level CurrentBU = Nz(DLookup("ParentUnit", "t_EMS_BM_BusinessUnits", "BusinessUnitID = " &amp; CurrentBU), 0) IsChild = False intX = 0 End If Loop End If End Function </code></pre>
2
Security Exception While Running TestNG test in Eclipse
<p>Getting the below error while trying to run the TestNG test in Eclipse Neon . Seems like there is some sort signed content in jar dependency which is blocking this . have no idea what its though ..Any suggestions on how to fix this . Have never faced this before .</p> <pre><code>java.lang.SecurityException: Invalid signature file digest for Manifest main attributes at sun.security.util.SignatureFileVerifier.processImpl(SignatureFileVerifier.java:284) at sun.security.util.SignatureFileVerifier.process(SignatureFileVerifier.java:238) at java.util.jar.JarVerifier.processEntry(JarVerifier.java:273) at java.util.jar.JarVerifier.update(JarVerifier.java:228) at java.util.jar.JarFile.initializeVerifier(JarFile.java:383) at java.util.jar.JarFile.getInputStream(JarFile.java:450) at sun.net.www.protocol.jar.JarURLConnection.getInputStream(JarURLConnection.java:162) at java.net.URL.openStream(URL.java:1045) at org.testng.remote.RemoteTestNG.getTestNGVersion(RemoteTestNG.java:84) at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:39) [ServiceLoaderHelper] More than one working implementation for 'null', we will use the first one Exception in thread "main" java.lang.NoSuchMethodError: org.testng.internal.Utils.defaultIfStringEmpty(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; at org.testng.remote.AbstractRemoteTestNG.setHost(AbstractRemoteTestNG.java:59) at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:122) at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:58) </code></pre>
2
Bootstrap carousel full screen on every device
<p>so i want a carousel that should take full height and width of the display monitor and then scroll down. like <a href="https://www.yikyak.com/home" rel="nofollow">this</a>, and the images inside should fill its parent while maintaining ratio. the problem is either i have to provide fixed height or it will take the height of largest image. so how can i make a carousel of full screen for every device.</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>$(document).ready(function() { $("#my-slider").carousel({ interval : 3000, pause: false }); })</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container-fluid { padding-right: 0px; padding-left: 0px; margin-right: 0px; margin-left: 0px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous"&gt; &lt;script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;div class="container-fluid"&gt; &lt;div class="row" style="margin-right:0px; margin-left:0px;"&gt; &lt;div class="col-sm-12" style="padding:0px;"&gt; &lt;div id="my-slider" class="carousel slide" data-ride="carousel"&gt; &lt;div class="carousel-inner" role="listbox"&gt; &lt;div class="item active"&gt; &lt;img src="img/image1.jpg"/&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img src="img/image2.jpg"/&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img src="img/image3.jpg"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="container" style="margin-top:20px;"&gt; &lt;div class="row"&gt; &lt;div class="col-sm-12 col-md-12 col-xs-12"&gt; &lt;div class="thumbnail" style="border:none; background:white;"&gt; &lt;div class="col-sm-4 col-md-4 col-xs-12 image-container"&gt; &lt;center&gt;&lt;img src="img/image4.jpg" style="height:200px;" class="img-responsive" /&gt;&lt;/center&gt; &lt;/div&gt; &lt;div class="col-sm-8 col-md-8 col-xs-12"&gt; &lt;h2&gt;Sample heading&lt;/h2&gt; &lt;p style="font-size:15px;"&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed hendrerit adipiscing blandit. Aliquam placerat, velit a fermentum fermentum, mi felis vehicula justo, a dapibus quam augue non massa.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-12 col-md-12 col-xs-12"&gt; &lt;div class="thumbnail" style="border:none; background:white;"&gt; &lt;div class="col-sm-4 col-md-4 col-sm-push-8 col-xs-12 image-container"&gt; &lt;center&gt;&lt;img src="img/image4.jpg" style="height:200px;" class="img-responsive" /&gt;&lt;/center&gt; &lt;/div&gt; &lt;div class="col-sm-8 col-md-8 col-sm-pull-4 col-xs-12"&gt; &lt;h2&gt;Sample heading&lt;/h2&gt; &lt;p style="font-size:15px;"&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed hendrerit adipiscing blandit. Aliquam placerat, velit a fermentum fermentum, mi felis vehicula justo, a dapibus quam augue non massa.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-12 col-md-12 col-xs-12"&gt; &lt;div class="thumbnail" style="border:none; background:white;"&gt; &lt;div class="col-sm-4 col-md-4 col-xs-12 image-container"&gt; &lt;center&gt;&lt;img src="img/image4.jpg" style="height:200px;" class="img-responsive" /&gt;&lt;/center&gt; &lt;/div&gt; &lt;div class="col-sm-8 col-md-8 col-xs-12"&gt; &lt;h2&gt;Sample heading&lt;/h2&gt; &lt;p style="font-size:15px;"&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed hendrerit adipiscing blandit. Aliquam placerat, velit a fermentum fermentum, mi felis vehicula justo, a dapibus quam augue non massa.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-12"&gt; &lt;h2&gt;Contact Us&lt;/h2&gt; &lt;form action="" method="" class="form-horizontal"&gt; &lt;div class="form-group"&gt; &lt;label for="name" class="col-sm-2 control-label"&gt;Name&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input id ="name" type="name" name="" class="form-control"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="email" class="col-sm-2 control-label"&gt;Email Address&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input id ="email" type="email" name="" class="form-control"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="message" class="col-sm-2 control-label"&gt;Message&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input id ="message" type="message" name="" class="form-control"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;div class="col-sm-10 col-sm-push-2"&gt; &lt;input id ="submit" type="submit" name="" class="btn btn-default"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
2
How to use (Cordova) plugin with Ionic 2 / TypeScript?
<p>I would like to use <code>cordova-plugin-fcm</code> with Ionic2/TypeScript. The wrapper FCMPlugin.js looks real simple but I'm used to Angular2/TypeScript working with import statements and don't know how to get such a plugin to work with Ionic2.</p> <p>If I use the code to get a token (<code>FCMPlugin.getToken()</code>) I get:</p> <blockquote> <p>Cannot find name 'FCMPlugin'</p> </blockquote> <p>When I try this <a href="https://stackoverflow.com/questions/25684371/cordova-plugins-not-working-with-ionic">suggested answer</a></p> <p>I get:</p> <blockquote> <p>Require is not defined</p> </blockquote>
2
TailTruncation - Ellipsize the text of a picker control in Xamarin Forms
<p>Is it possible to truncate long texts with ellipsis in a picker control. I have already created a custom renderer to set a fontsize and no border in order to achieve the following result.</p> <p><a href="https://i.stack.imgur.com/Ql0lx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ql0lx.png" alt="enter image description here"></a></p> <p>Also tried to set <code>Control.Ellipsize = TextUtils.TruncateAt.End;</code> but nothing happens</p> <pre><code>[assembly: ExportRenderer(typeof(NoBorderPicker), typeof(CustomPicker))] namespace Prj.Droid.Renderers { public class CustomPicker : PickerRenderer { protected override void OnElementChanged(ElementChangedEventArgs&lt;Picker&gt; e) { base.OnElementChanged(e); if (Control != null) { var customBG = new GradientDrawable(); customBG.SetColor(Android.Graphics.Color.Transparent); customBG.SetCornerRadius(3); Control.SetBackground(customBG); Control.Ellipsize = TextUtils.TruncateAt.End; var custdatepicker = (NoBorderPicker) this.Element; this.Control.TextSize = (float)custdatepicker.FontSize; } } } } </code></pre>
2
eventReactive two action buttons Shiny
<p>I'm trying to trigger different function on the same output with two action buttons. <code>interests_data</code> and <code>interests_data_refresh</code> are eventReactive depending on two different output. </p> <p>Isolate may not take more than one action button. I tried to keep track on the first input but I'm afraid refreshing the page may cause problem on the tracking. I haven't seen any example about how to do this problem ie having different behavior on the same output depending on the button pressed. Here is my attempt :</p> <pre><code>output$mytable2 &lt;- DT::renderDataTable({ input$insert input$delete isolate({ if (input$insert == 0) { start_interests &lt;- dbReadTable(db, "Interests") DT::datatable(start_interests[], options = list( lengthMenu = c(10, 25, 50, 100, 150, 200), order = list(list(7, 'desc')), pageLength = 25 )) } else if (input$insert == x+1) { #updated_interests() DT::datatable(interests_data(), options = list( lengthMenu = c(10, 25, 50, 100, 150, 200), order = list(list(7, 'desc')), pageLength = 25 )) } else { DT::datatable(interests_data_refresh(), options = list( lengthMenu = c(10, 25, 50, 100, 150, 200), order = list(list(7, 'desc')), pageLength = 25 )) } x &lt;&lt;- as.numeric(input$insert) }) </code></pre> <p>})</p>
2
Create a container in win32 API
<p>I am a beginner in Win32 API. I am trying to create a little application that requires a container, but I have problems doing it.</p> <p>In HTML, I will show you what I want. Its the following code:</p> <pre class="lang-css prettyprint-override"><code>div{width:120px; height:300px; display:block; overflow-y:auto;} button{display:list-item;list-style:none; margin-bottom:3px;} </code></pre> <pre class="lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;button&gt;button 1&lt;/button&gt; &lt;button&gt;button 2&lt;/button&gt; &lt;button&gt;button 3&lt;/button&gt; &lt;button&gt;button 4&lt;/button&gt; &lt;button&gt;button 5&lt;/button&gt; &lt;button&gt;button 6&lt;/button&gt; &lt;button&gt;button 7&lt;/button&gt; &lt;button&gt;button 8&lt;/button&gt; &lt;button&gt;button 9&lt;/button&gt; &lt;button&gt;button 10&lt;/button&gt; &lt;button&gt;button 11&lt;/button&gt; &lt;button&gt;button 12&lt;/button&gt; &lt;button&gt;button 13&lt;/button&gt; &lt;button&gt;button 14&lt;/button&gt; &lt;/div&gt; </code></pre> <p>I have tried to repeat the same display in C++ using this code:</p> <pre><code>#include &lt;windows.h&gt; #include &lt;string&gt; #include &lt;vector&gt; const char *ClsName = "classname"; const char *WndName = "Windows"; HINSTANCE hInst; LRESULT CALLBACK WndProcedure(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MSG Msg; HWND hWnd; WNDCLASSEX WndClsEx; hInst = hInstance; // Create the application window WndClsEx.cbSize = sizeof(WNDCLASSEX); WndClsEx.style = CS_HREDRAW | CS_VREDRAW; WndClsEx.lpfnWndProc = WndProcedure; WndClsEx.cbClsExtra = 0; WndClsEx.cbWndExtra = 0; WndClsEx.hIcon = LoadIcon(NULL, IDI_QUESTION); WndClsEx.hCursor = LoadCursor(NULL, IDC_ARROW); WndClsEx.hbrBackground = (HBRUSH)GetStockObject(WHITE_PEN); WndClsEx.lpszMenuName = MAKEINTRESOURCEA(109); WndClsEx.lpszClassName = ClsName; WndClsEx.hInstance = hInst; WndClsEx.hIconSm = LoadIcon(NULL, IDI_QUESTION); // Register the application RegisterClassEx(&amp;WndClsEx); // Create the window object hWnd = CreateWindow(ClsName, WndName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInst, NULL); // Find out if the window was created successfully if (!hWnd) // If the window was not created, return 0; // stop the application // Display the window to the user ShowWindow(hWnd, SW_SHOWNORMAL); UpdateWindow(hWnd); // Decode and treat the messages // as long as the application is running while (GetMessage(&amp;Msg, NULL, 0, 0)) { TranslateMessage(&amp;Msg); DispatchMessage(&amp;Msg); } return Msg.wParam; }; //classname //classname using namespace std; LRESULT CALLBACK WndProcedure(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { static HWND ws[50], st, sd; switch (msg) { case WM_DESTROY: PostQuitMessage(0); break; case WM_CREATE: sd = CreateWindow(ClsName, NULL, WS_CHILD | WS_VSCROLL |WS_HSCROLL| WS_BORDER | WS_VISIBLE, 10, 10, 200, 600, hwnd, NULL, hInst, NULL);//Container for (int i = 0; i &lt; 114; i++) { ws[i] = CreateWindow("Button", ("Button" + to_string(i)).c_str(), WS_VISIBLE | WS_BORDER | WS_CHILD, 10, 25*i + 10, 150, 20, sd, (HMENU)(i + 1), hInst, NULL); //Buttons }; break; default: return DefWindowProc(hwnd, msg, wparam, lparam); break; } } </code></pre> <p>With this code, I get a container that is infinitely repeated in the the main window.</p> <p>This is a screenshot of the result;</p> <p><a href="https://i.stack.imgur.com/MQpff.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MQpff.png" alt="image"></a></p> <p>I do not understand the result. It seems I have used a loop but I did not.</p>
2
How do I get a python script filename as title for a plot correctly shown from Jupyter?
<p>I like to use a python script to generate a figure. That figure should have the script filename (with full path) as part of the title. For example:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt plt.rcParams['text.usetex'] = True x = np.linspace(0, 10, 10) titleString = __file__.replace('_', '\_') plt.plot(x, x) plt.title(titleString) plt.show() </code></pre> <p>The IPython console in Spyder shows the title correctly:</p> <p><a href="https://i.stack.imgur.com/Vlfa5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vlfa5.png" alt="enter image description here"></a></p> <p>However, if I run the script (on Windows 7, using Anaconda with Jupyter Notebook 4.2.1 and Spyder 2.3.9) from within a Jupyter Notebook via</p> <pre><code>%matplotlib inline %run 'H:/Python/Playground/a_test' </code></pre> <p>I get the following result:</p> <p><a href="https://i.stack.imgur.com/Qty0c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qty0c.png" alt="enter image description here"></a></p> <p>Note that the scripts path and filename is not correct. Is there a way to fix this?</p>
2
Consuming a WSDL/Web service in C#/VisualStudio 2015
<p>While there are many other topics that provide great information on the topic posted here already, I've not yet been able to find the answer to my dilemma.</p> <p>While I'm somewhat competent with PowerShell, I am completely new with C#/VisualStudio. I have some PowerShell code that consumes a Web service that works perfectly well:</p> <pre><code>function Modify-SPMLObject() { param( [string]$Uri , [string]$ObjectDN , [PSCredential]$Creds , [hashtable]$Attributes ) $MyService = New-WebServiceProxy -Uri $Uri -Credential $Creds $Type = $MyService.GetType().Namespace $ModifyRequest = New-Object -TypeName ($Type + ".CModifyRequest") $CPSOID = New-Object -TypeName ($Type + ".CPSOID") $CPSOID.ID = $ObjectDN $ModifyRequest.psoID = $CPSOID $Modifications = @() foreach ($Attribute in $Attributes.Keys) { $Modification = New-Object -TypeName ($Type + ".modification") $Modification.Name = $Attribute $Modification.Value = $Attributes.$Attribute $Modification.Operation = "replace" $Modifications += $Modification } $ModifyRequest.modification = $Modifications $MyService.modify($ModifyRequest) } </code></pre> <p>My challenge is converting this to C# in VisualStudio. In lieu of the call to <em>New-WebServiceProxy</em>, I've included a reference in my project to the Web service. The reference is named <em>MyService</em>. Hence, the code I've created thus far:</p> <pre><code>var ModifyRequest = new MyService.CModifyRequest(); var CPSOID = new MyService.CPSOID(); CPSOID.ID = "a hard-coded value for now"; ModifyRequest.psoID = CPSOID; var modifications = new MyService.modification[1]; var modification = new MyService.modification(); modification.name = "another hard-coded value for the moment"; modification.operation = "replace"; modification.value = new string[1] { "This is a test" }; modifications[0] = modification; ModifyRequest.modification = modifications; </code></pre> <p>The one thing that I haven't been able to figure out, however, is how, in C#, to accomplish the task that the PowerShell version accomplishes thus:</p> <pre><code>$MyService.modify($ModifyRequest) </code></pre> <p>In VS, if I try to call:</p> <pre><code>MyService.modify(ModifyRequest); </code></pre> <p>I get the message</p> <blockquote> <p>Error CS0234 The type or namespace name 'modify' does not exist in the namespace 'WebApplication2.MyService' (are you missing an assembly reference?)</p> </blockquote> <p>Any tips are most appreciated!</p> <p>EDIT: Found the solution. In answer to LachlanB, typing "MyService" provided a list of methods and classes - but <strong>not</strong> the <em>modify</em> operation that I was seeking and defined in the WSDL thus:</p> <pre><code>&lt;wsdl:operation name="modify"&gt; &lt;wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"&gt;Changes the specified object on the target.&lt;/wsdl:documentation&gt; &lt;wsdl:input message="tns:modifySoapIn"/&gt; &lt;wsdl:output message="tns:modifySoapOut"/&gt; &lt;/wsdl:operation&gt; </code></pre> <p>What I needed to include was, first, the reference:</p> <pre><code>using WebApplication2.MyService; </code></pre> <p>With that, I could then call:</p> <pre><code>MyApplicationClassName webService = new MyApplicationClassName(); CModifyResponse response = webService.modify(ModifyRequest); </code></pre> <p>where "MyApplicationClassName" was automatically generated as was listed in References.cs in the following statement:</p> <pre><code>public partial class MyApplicationClassName : System.Web.Services.Protocols.SoapHttpClientProtocol { </code></pre> <p>Thanks to those that tried to help!</p>
2
How to add splash screen
<p>i'm a newwbie in java, and i want to add splash screen to a code. so i have created a layout XML named splash.xml :</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/splash" &gt; &lt;/RelativeLayout&gt; </code></pre> <p>and i have created a java classe named splash.java :</p> <pre><code>package com.test.test; import android.app.Activity; import android.content.Intent; import android.os.Handler; import android.os.Bundle; import android.view.Window; import com.test.test.R; public class Splash extends Activity { private boolean backbtnPress; private static final int SPLASH_DURATION = 3000; private Handler myHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getActionBar().hide(); setContentView(R.layout.splash); myHandler = new Handler(); myHandler.postDelayed(new Runnable() { @Override public void run() { finish(); if(!backbtnPress) { Intent intent = new Intent(Splash.this,MainActivity.class); Splash.this.startActivity(intent); } } }, SPLASH_DURATION); } @Override public void onBackPressed() { // TODO Auto-generated method stub backbtnPress = true; super.onBackPressed(); } } </code></pre> <p>but it does not work, when i run the app i find two app icons on device.</p> <p>can you help me please</p> <p>Thank you in advance!</p>
2
Maven resource folder
<p>Hy, I want to get the resource folder (ex: C:\Users\Raul\workspace\Serial\src\test\resources) in a Maven project but every time I run this java code:</p> <pre><code>System.out.println(getClass().getResource("").getPath()); </code></pre> <p>it returns me this path: C:/Users/Raul/workspace/Serial/target/test-classes/</p> <p>The last time I used Maven, worked that way without any changes from me. Thx in advance.</p>
2
Pop view controller using Screen edge pan gesture recogniser not following the thumb
<p>As soon as I've added custom bar navigation bar button item I've lost the ability to use the default function to go back. I'd like to have the ability to use "swipe from edge" to go back.</p> <p>I've added the Edge Pan Gesture Recogniser and connected it to @IBAction, but the dismissing action happens completely as soon as the pan gesture is recognised.</p> <p>Instead of slowly following my thumb (as seen in other apps), the current view moves out with predefined animation.</p> <p>How to make the animation following my thumb using Edge Pan Gesture Recogniser?</p> <pre><code>@IBAction func edgeSwipe(sender: AnyObject) { navigationController?.popViewControllerAnimated(true) } </code></pre> <p><a href="https://i.stack.imgur.com/ZP1NH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZP1NH.png" alt="enter image description here"></a></p>
2
Azure Web App doesn't start node server
<p>I am publishing my typescript node.js/express azure app via bitbucket, and it appears that everything is compiling properly, however azure doesn't start the app.</p> <p>A reproable repository is <a href="https://bitbucket.org/somkun/azureexample" rel="nofollow">here</a>. I tried cloning the app to a fresh local directory, then running the deploy.cmd and calling node start in the output folder, and that worked fine.</p>
2
Should I use Cocoa Bindings in Swift?
<p>I am not too sure about the fundamental difference between Cocoa Bindings and IBOutlets/IBActions. I am currently migrating an Obj-C project to Swift 3 and I want to know whether it is common practice to use bindings, especially in Swift? There is very little community discussion on bindings in general and I am CS student new to Cocoa/CocoaTouch dev, so I would appreciate verbose answers.</p>
2
Remotely deactivate an excel file via vba
<p>I would like to know if there is a way to remotely deactivate an excel file via vba.</p> <p>The problem:<br> My company uses an excel file for sales to provide quotations to the customer. Now when there is an update to our pricing scheme I send a new version of the Excel file to the sales team. The obvious thing that happens next is that they don't use the most current version of the file to give a quote => the customer gets a wrong price.</p> <p>What I tried so far:<br> I implemented a time bomb that lets the file expire at a defined date. The problem with this is that updates to the excel file happen irregularly.</p> <p>What I have in mind:<br> Once the excel file starts a VBA script queries a web server for the most current version number. If the version number in the currently opening Excel file is lower than the one provided by the server, the file locks up.</p> <p>Is this something one can realize with Excel and VBA? I could imagine that this causes some problem with Windows Security etc. because it may look like a trojan or virus.</p> <p>You help is much appreciated!</p>
2
Nothing happens when I try to import a project in Android Studio
<p>There is my problem: I tried to import Google Maps API samples in android studio. But when I select directory in "Import project"s menu, nothing happens. There are no errors, just silence. Same situation when I try to import any google sample or opensource project. I have Android Studio 2.1.2</p> <p><strong>UPDATE:</strong></p> <blockquote> <p>Unable to save '/home/antonid/Android_Projects/android-ActionBarCompat-ShareActionProvider/local.properties'/home/antonid/Android_Projects/android-ActionBarCompat-ShareActionProvider/local.properties (Permission denied)'</p> </blockquote>
2