input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Finding the 5 most common words in a text <p>I have a school task where a part of the task asks us to make a method that finds the 5 most commons words in a .txt file. </p>
<p>The task asks us to put all the words in an ArrayList, which i have already done. The real problem is making the program print out the top 5 words in the text file.
The only "clue" i have is the method name which is:</p>
<p>public Words[] common5(){
}</p>
| <p>Iterate through the ArrayList, for each word in the list, put the word into a HashMap where the key is the word and the value is an Integer which you will increase every time you find the word again. At the end iterate through the HashSet and find the top 5 integers. Print those found words.</p>
|
D3.js SVG image bounding box offset <p>I am attempting to fill a div with an svg image using D3.js. So far I have been able to center my image and watch it scale as I grow and shrink the browser window. However when attempting to dynamically find the bounding box of image I can only find the top,left properties of the canvas and the width of all the space no just my original image.</p>
<p>Here is a basic mock up of my problem:
<a href="http://jsfiddle.net/wnwfn/79/" rel="nofollow">http://jsfiddle.net/wnwfn/79/</a></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>d3.select("#svgEmbed").append("image")
.attr("xlink:href","http://www.clipartkid.com/images/32/square-clip-art-black-and-white-clipart-panda-free-clipart-images-UkJ6sF-clipart.png")
.attr("width", "100%")
.attr("height", "100%")
</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.12/d3.min.js"></script>
<p>
<svg id="svgEmbed" height="100%" width="100%" ></svg>
</p></code></pre>
</div>
</div>
</p>
<p>So my question is how can I find the top left position of the square image in this example? I've had a play using the .offset(), .getBBox() but I can't seem to get the values I am looking for.</p>
| <p>Your approach isn't going to work. By setting the image width/height to <code>100%</code>, the image element will always be positioned at <code>[0,0]</code>. If you know the pixel size of how you want the image to display, you can do something like this:</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>var imgSize = 150;
var img = d3.select("#svgEmbed")
.append("image")
.attr("xlink:href", "http://www.clipartkid.com/images/32/square-clip-art-black-and-white-clipart-panda-free-clipart-images-UkJ6sF-clipart.png")
.attr("x", "50%")
.attr("width", imgSize)
.attr("height", imgSize)
.attr("transform", "translate(" + (-imgSize / 2) + ", 0)");
d3.select(window).on("resize", function(){
console.log(img.node().getBBox());
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<p>
<svg id="svgEmbed" height="100%" width="100%"></svg>
</p></code></pre>
</div>
</div>
</p>
|
How to bind dropdown list in angularjs from JSON string array <p>I am trying to bind a dropdown list from JSON string attach below but my last value of JSON is getting override with all values . I have tried to console and I have received individual values in console but while binding i m unable to do it. I have used select option and different select ng-change option but still stuck. Please help me as you can.</p>
<p>My html Code :</p>
<pre><code> <ion-list>
<div ng-repeat="group in groups">
<ion-item class="item-stable" ng-click="toggleGroup(group)" ng-class="{active: isGroupShown(group)}">
<i class="icon" ng-class="isGroupShown(group) ? 'ion-minus' : 'ion-plus'"></i>
&nbsp;
{{group.name}}
</ion-item>
<ion-item class="item-accordion item-button-right" ng-repeat="item in group.items track by $id(item)" ng-show="isGroupShown(group)" style="height: 50px;">
{{item.name}}
<select> <option selected>Select</option>
<option ng-repeat="itm in qty track by qty.id" value="{{itm.id}}">{{itm.price}}</option>
</select>
</ion-item> </div>
</ion-list>
</code></pre>
<p>JSOn String :</p>
<pre><code> "category_name":{
"1":{
"menu_category_id":"1",
"category_name":"Beverage Black Coffee",
"itemname":{
"1":{
"menu_item_id":"1",
"item_name":"Frespresso",
"qty":{
"50.00":{
"full":"50.00",
"half":null,
"quater":null
}
}
},
</code></pre>
<p>Controller code :</p>
<pre><code> var i =0;
angular.forEach(response.data.category_name, function(menu,key){
$scope.groups[i] = {
name: menu.category_name,
items: [],
qty:[],
rate:[],
show: false
};
angular.forEach(menu.itemname, function(itemid,key){
$scope.groups[i].items.push({id:itemid.menu_item_id,name:itemid.item_name});
angular.forEach(itemid.qty, function(qty,key){
if(qty.fullqty!==null){
$scope.groups[i].qty.push({type:'full',qty:qty.full});
console.log("full : "+itemid.full +" Item Id "+itemid.menu_item_id);
console.log(qty.item_name + " fullqty " + qty.full_qty + " fullrate "+ qtyu.full_rate);
}
});
});
i++;
});
} else{
$ionicLoading.hide();
msg = [];
msg.push("- Something went Wrong!!! <br />");
msg.push("- Plz try again! <br />");
var alertPopup = $ionicPopup.alert({
title: 'OOPS!!!',
template: msg
});
}
}).error(function(error) {
console.log("Server error: " + error);
});
});
</code></pre>
| <p>solved this I was foolish to form another array which is running out of sync that's why it was not binding properly so bind it to $scope.groups[i].items.push({id:itemid.menu_item_id,name:itemid.item_name}); instead of forming one more foreach</p>
|
Inno Setup installator has wrong text encoding <p>My installator (Inno Setup) has a bad Russian text encoding for the some Windows installations. All machines have Windows XP SP3 (English version), but on some this works, some does not have. </p>
<p>There are any settings on Windows to fix it?<br>
Thanks</p>
| <p>My guess is that you are using the Non-Unicode version of Inno Setup. The machines, where the installer has wrong encoding, probably do not have the Russian set as the legacy (non-Unicode) encoding.</p>
<p>In Windows XP Control panel, check the <em>"Regional and Language Options"</em>. There on the <em>Advanced</em> tab check, what is the <em>"Language for non-Unicode programs"</em> set to. This can be a different language than the Windows UI language. If I'm correct, the working machines have this set to <em>Russian</em> and the non-working machines have this set to <em>English</em> (or other).</p>
<hr>
<p>Anyway, always use the <a href="http://www.jrsoftware.org/ishelp/index.php?topic=unicode" rel="nofollow">Unicode version of Inno Setup</a> and you won't have this kind of problems.</p>
<p>No one should be developing non-Unicode applications in the 21st century!</p>
|
Inline SVG background image does not work in React.js <p>I have a component that should provide a div with a dot grid pattern. </p>
<p>The function that should do the work looks like this:</p>
<pre><code>drawSquareDotGrid(distance, unit, colour){
var newGrid = "data:image/svg+xml;utf8,<svg width=\""+distance+unit+"\" height=\""+distance+unit+"\"><circle cx=\"4mm\" cy=\"4mm\" r=\"0.3mm\" fill=\""+colour+ "\"/></svg>"
this.setState({grid: newGrid })
}
</code></pre>
<p>and this is my render function:</p>
<pre><code> render() {
const windowHeight = window.innerHeight - 105
const sx = {width: "100%",
height: windowHeight,
backgroundImage: 'url('+ this.state.grid +')'}
return (
<div style={sx}></div>
)
}
</code></pre>
<p>The string with SVG does not appear in generated HTML however it somewhat works if I use simpler SVG like this:</p>
<pre><code>var newGrid = "data:image/svg+xml;utf8,<svg><circle></svg>"
</code></pre>
<p>Any idea how to fix this?</p>
<p>Thank you!</p>
<p>Rosta</p>
| <p>As @Kaiido pointed out URI should be encoded with <code>window.encodeURIComponent</code>. Also there were missing xlmns and viewPort information in the SVG header.</p>
<p>Fixed code looks like this:</p>
<pre><code>drawSquareDotGrid(distance, unit, colour){
var prefix = "data:image/svg+xml;charset=UTF-8,"
var grid = "<svg width=\""+distance+unit+"\" height=\""+distance+unit+"\" viewPort=\"0 0 5mm 5mm\" xmlns=\"http://www.w3.org/2000/svg\"><circle cx=\"4mm\" cy=\"4mm\" r=\"0.3mm\" fill=\""+colour+ "\"/></svg>"
var newGrid = prefix + window.encodeURIComponent(grid)
this.setState({grid: newGrid })
}
</code></pre>
|
Passing dynamic argument on onClick inside for does not work <p>Following react code does not work.'select' function is always called with 10 instead of assigned values.</p>
<pre><code> select( x ) {
alert( x ); // Always alerts 10.
}
render() {
var AllData = [];
for( var i = 0; i<10 ;i++ ) {
AllData.push(
<div key={i} onClick={() => this.select(i)} >{i}</div>
);
}
return (
<div>
{AllData}
</div>
);
}
</code></pre>
<p>How do I pass dynamic value in for loop correctly?</p>
| <p>Since you are using ES2015 <em>arrow function</em> notation, I'd suggest to just replace <code>var</code> by <code>let</code> for your loop variable initialization. That way you have a true <em>block scope</em>, otherwise you have to deal with <em>function scope</em> which is the root of your trouble here.</p>
<pre><code>for( let i = 0; i<10 ;i++ ) {
AllData.push(
<div key={i} onClick={() => this.select(i)} >{i}</div>
);
}
</code></pre>
|
Multiple NullPointerExceptions with ResourceBundleEditor in Eclipse Neon <p>Fresh Spring Tool Suite 3.8.2 (Eclipse Neon 4.6.1) with ResourceBundleEditor installed.</p>
<p>When opening <code>.properties</code> files, multiple <code>NullPointerException</code>s pop up.</p>
<blockquote>
<p>java.lang.NullPointerException
at org.eclipse.wst.jsdt.chromium.debug.core.model.BreakpointAdapterFactory.getAdapter(BreakpointAdapterFactory.java:25)
at org.eclipse.core.internal.adapter.AdapterFactoryProxy.getAdapter(AdapterFactoryProxy.java:82)
at org.eclipse.core.internal.runtime.AdapterManager.getAdapter(AdapterManager.java:294)
at org.eclipse.ui.part.WorkbenchPart.getAdapter(WorkbenchPart.java:143)
at org.eclipse.ui.texteditor.AbstractTextEditor.getAdapter(AbstractTextEditor.java:6185)
at com.essiembre.eclipse.rbe.ui.editor.i18n.I18nPageEditor.getAdapter(I18nPageEditor.java:90)
at org.eclipse.core.runtime.Adapters.adapt(Adapters.java:59)
at org.eclipse.core.runtime.Adapters.adapt(Adapters.java:100)
at org.eclipse.ui.part.MultiPageEditorPart.getAdapter(MultiPageEditorPart.java:1199)
at com.essiembre.eclipse.rbe.ui.editor.ResourceBundleEditor.getAdapter(ResourceBundleEditor.java:208)
at org.eclipse.debug.internal.ui.actions.ToggleBreakpointsTargetManager$ToggleBreakpointsTargetAdapterFactory.canGetToggleBreakpointsTarget(ToggleBreakpointsTargetManager.java:318)
at org.eclipse.debug.internal.ui.actions.ToggleBreakpointsTargetManager$ToggleBreakpointsTargetAdapterFactory.isEnabled(ToggleBreakpointsTargetManager.java:361)
at org.eclipse.debug.internal.ui.actions.ToggleBreakpointsTargetManager.getEnabledFactories(ToggleBreakpointsTargetManager.java:502)
at org.eclipse.debug.internal.ui.actions.ToggleBreakpointsTargetManager.getPreferredToggleBreakpointsTargetID(ToggleBreakpointsTargetManager.java:542)
at org.eclipse.debug.internal.ui.actions.ToggleBreakpointsTargetManager.getToggleBreakpointsTarget(ToggleBreakpointsTargetManager.java:549)
at org.eclipse.debug.internal.ui.actions.breakpoints.RetargetBreakpointAction.getAdapter(RetargetBreakpointAction.java:49)
at org.eclipse.debug.internal.ui.actions.RetargetAction.partActivated(RetargetAction.java:169)
at org.eclipse.ui.internal.PartService$1.run(PartService.java:84)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.ui.internal.PartService.partActivated(PartService.java:81)
at org.eclipse.ui.internal.WorkbenchWindow$WWinPartService.partActivated(WorkbenchWindow.java:3002)
at org.eclipse.ui.internal.WorkbenchPage$14.run(WorkbenchPage.java:4977)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.ui.internal.WorkbenchPage.firePartActivated(WorkbenchPage.java:4974)
at org.eclipse.ui.internal.WorkbenchPage.access$19(WorkbenchPage.java:4962)
at org.eclipse.ui.internal.WorkbenchPage$E4PartListener.partActivated(WorkbenchPage.java:210)
at org.eclipse.e4.ui.internal.workbench.PartServiceImpl$3.run(PartServiceImpl.java:250)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.firePartActivated(PartServiceImpl.java:247)
at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.activate(PartServiceImpl.java:757)
at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.activate(PartServiceImpl.java:682)
at org.eclipse.e4.ui.internal.workbench.swt.AbstractPartRenderer.activate(AbstractPartRenderer.java:95)
at org.eclipse.e4.ui.workbench.renderers.swt.ContributedPartRenderer$1.handleEvent(ContributedPartRenderer.java:63)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4410)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088)
at org.eclipse.swt.widgets.Shell.setActiveControl(Shell.java:1542)
at org.eclipse.swt.widgets.Shell.setActiveControl(Shell.java:1505)
at org.eclipse.swt.widgets.Control.sendFocusEvent(Control.java:2940)
at org.eclipse.swt.widgets.Widget.wmSetFocus(Widget.java:2437)
at org.eclipse.swt.widgets.Control.WM_SETFOCUS(Control.java:5438)
at org.eclipse.swt.widgets.Tree.WM_SETFOCUS(Tree.java:7195)
at org.eclipse.swt.widgets.Control.windowProc(Control.java:4861)
at org.eclipse.swt.widgets.Tree.windowProc(Tree.java:6074)
at org.eclipse.swt.widgets.Display.windowProc(Display.java:5102)
at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method)
at org.eclipse.swt.internal.win32.OS.CallWindowProc(OS.java:2446)
at org.eclipse.swt.widgets.Tree.callWindowProc(Tree.java:1552)
at org.eclipse.swt.widgets.Tree.WM_LBUTTONDOWN(Tree.java:6759)
at org.eclipse.swt.widgets.Control.windowProc(Control.java:4827)
at org.eclipse.swt.widgets.Tree.windowProc(Tree.java:6074)
at org.eclipse.swt.widgets.Display.windowProc(Display.java:5102)
at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method)
at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3814)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022)
at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150)
at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:687)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:604)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610)
at org.eclipse.equinox.launcher.Main.run(Main.java:1519)</p>
</blockquote>
<p>How do I get rid of the exceptions?</p>
| <p>Remove the JSDT Chromium debugger, more specifically, remove files <code>org.eclipse.wst.jsdt.chromium.debug.*</code> from Eclipse plugins directory.</p>
|
How can I get the same result as java function getBytes() use PHP? <p>My Java code is like this:</p>
<pre><code>public void trans() {
try {
byte[] test = "æµè¯".getBytes("utf-8");
for(byte b:test){
System.out.println(b);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
</code></pre>
<p>And this prints:</p>
<pre><code>-26
-75
-117
-24
-81
-107
</code></pre>
<p>Now I want to get the same result using PHP, my code is like this:</p>
<pre><code>function getUnicodeFromOneUTF8($word) {
$arr = str_split($word);
foreach ($arr as $value)
echo hexdec(ord($value)). '</br>';
}
getUnicodeFromOneUTF8('æµè¯');
</code></pre>
<p>But it prints this:</p>
<pre><code>230
181
139
232
175
149
</code></pre>
<p>How can I get the same result?</p>
| <p>In PHP you might want to use this function for that</p>
<pre><code>$result = mb_encode_numericentity('æµè¯test', [0, 0x10FFFF, 0, 0x10FFFF], 'UTF-8');
echo htmlentities($result);
</code></pre>
<p><a href="http://php.net/manual/en/function.mb-encode-numericentity.php" rel="nofollow">http://php.net/manual/en/function.mb-encode-numericentity.php</a></p>
|
MapReduce java.lang.ArrayIndexOutOfBoundsException: 0 <p>I try to run a mapreduce in java, but get this error.</p>
<pre><code>Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at com.mapreduce.WordCount.run(WordCount.java:23)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
at com.mapreduce.WordCount.main(WordCount.java:18)
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:147)
</code></pre>
<p>WordCount.java</p>
<pre><code>package com.mapreduce;
import java.io.IOException;
import java.util.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.*;
import org.apache.hadoop.mapreduce.lib.output.*;
import org.apache.hadoop.util.*;
public class WordCount extends Configured implements Tool {
public static void main(String args[]) throws Exception {
int res = ToolRunner.run(new WordCount(), args);
System.exit(res);
}
public int run(String[] args) throws Exception {
Path inputPath = new Path(args[0]);
Path outputPath = new Path(args[1]);
Configuration conf = getConf();
Job job = new Job(conf, this.getClass().toString());
FileInputFormat.setInputPaths(job, inputPath);
FileOutputFormat.setOutputPath(job, outputPath);
job.setJobName("WordCount");
job.setJarByClass(WordCount.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setMapperClass(Map.class);
job.setCombinerClass(Reduce.class);
job.setReducerClass(Reduce.class);
return job.waitForCompletion(true) ? 0 : 1;
}
public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
@Override
public void map(LongWritable key, Text value,
Mapper.Context context) throws IOException, InterruptedException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
context.write(word, one);
}
}
}
public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {
@Override
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable value : values) {
sum += value.get();
}
context.write(key, new IntWritable(sum));
}
}
}
</code></pre>
<p>I undarstand that it means there are no elements in the array, but what do I need to do run it? I'm using Maven to import all the necessary libraries. I'm running it on Windows. The code is an example from <a href="http://www.macalester.edu/~shoop/sc13/hadoop/html/hadoop/wc-detail.html" rel="nofollow">http://www.macalester.edu/~shoop/sc13/hadoop/html/hadoop/wc-detail.html</a></p>
| <p>You need to launch your program <strong>with arguments</strong> corresponding to the input path and the output path, so your launch command should be of the next format:</p>
<pre><code>java -cp <my-classpath-here> com.mapreduce.WordCount <input-path> <output-path>
</code></pre>
|
LINQ retrieve statement didn't return latest updated result <p>I have a table called Organization and a table called Staff. </p>
<p>Inside the Staff table I've got 2 fields which are </p>
<ul>
<li>StaffStatus to indicate whether he/she is available for the organization and </li>
<li>ParentStatus to inidicate whether the organization of the user is still available or not (I didn't link them due to several reasons). </li>
</ul>
<p>I allow the owner to recover the staff (update the StaffStatus to "Available") if the ParentStatus of the staff is "Available". </p>
<p>There was a weird situation in my system. I first remove the staff (update StaffStatus to "Unavailable"), then I remove the organization (update staff.ParentStatus to "Unavailable"). In this condition, the owner is not allowed to recover the user. However, the ParentStatus I retrieve is "Available" (so it's still allow to recover the user), but in the database the ParentStatus is already changed to "Unavailable".</p>
<p>The code I used to removeUser:</p>
<pre><code>Friend Sub removeUser(strInput As String)
Try
objUser = (From userDB In db.Staffs Where userDB.UserID = strInput).FirstOrDefault()
objUser.UserStatus = "Unavailable"
db.SubmitChanges(ConflictMode.ContinueOnConflict)
Catch ex As Exception
For Each occ As ObjectChangeConflict In db.ChangeConflicts
occ.Resolve(RefreshMode.KeepChanges)
Next
db.SubmitChanges()
End Try
End Sub
</code></pre>
<p>The code I used to removeOrganization:</p>
<pre><code>Friend Sub removeOrganization(strInput As String)
Try
objOrganization = (From organizationDB In db.Organizations
Where organizationDB.OrganizationID = strInput).FirstOrDefault()
objOrganization.OrganizationStatus = "Unavailable"
Dim objCompany = From companyDB In db.Companies
Where companyDB.OrganizationID = strInput
For Each mem In objCompany
mem.ParentStatus = "Unavailable"
Dim objDepartment = From DepartmentDB In db.Departments
Where DepartmentDB.CompanyID = mem.CompanyID
For Each record In objDepartment
record.ParentStatus = "Unavailable"
Next
Next
Dim objUser = From UserDB In db.Staffs
Where UserDB.OrganizationID = strInput
For Each mem In objUser
mem.ParentStatus = "Unavailable"
Next
db.SubmitChanges(ConflictMode.ContinueOnConflict)
Catch ex As Exception
For Each occ As ObjectChangeConflict In db.ChangeConflicts
occ.Resolve(RefreshMode.KeepChanges)
Next
db.SubmitChanges()
End Try
End Sub
</code></pre>
<p>How I called the recoverUser (I used a MsgBox() to test the ParentStatus I retrieve):</p>
<pre><code>Private Sub btnViewUserRecover_Click(sender As Object, e As EventArgs) Handles btnViewUserRecover.Click
MsgBox(helperUserCKJ.getUserByID(strUserID).ParentStatus)
If dgvUser.RowCount > 0 Then
strUserID = dgvUser.SelectedRows.Item(0).Cells(0).Value
If (helperUserCKJ.getUserByID(strUserID).ParentStatus.Equals("Unavailable")) Then
MessageBox.Show("The Organization or Company or Department of the User is unavailable now." & vbNewLine & "You need to recover the Organization or Company or Department of the User first before you can recover the User.", "User Recovery Error", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
Dim respond = MessageBox.Show("Are you sure want to recover the user?", "User Recovery Comfirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If respond = DialogResult.Yes Then
helperUserCKJ.recoverUser(strUserID)
End If
End If
End If
End Sub
</code></pre>
<p>The query I used to retrieve user:</p>
<pre><code>Friend Function getUserByID(strInput As String) As Staff
getUserByID = (From userDB In db.Staffs
Where userDB.UserID = strInput).FirstOrDefault()
End Function
</code></pre>
<p>I can verify that the ParentStatus field in the database is already changed.</p>
<p>If I didn't remove the user and directly remove the organization only, then it become normal(disallow to recover user). If I remove the user and then remove the organization, when I click to recover the user, the parentStatus is "Available". </p>
<p>It's a weird situation. I'm using LINQ, vb.net and Microsoft Azure database.</p>
| <p>So I find the solution to refresh my database with the current value.</p>
<pre><code>Friend Function getUserByID(strInput As String) As Staff
objUser = (From userDB In db.Staffs
Where userDB.UserID = strInput).FirstOrDefault()
db.Refresh(RefreshMode.OverwriteCurrentValues, objUser)
getUserByID = objUser
End Function
</code></pre>
|
How to update only status on a Button click using in SQLite in android <p>I am developing a SQLite database. I created a table which schema is: name, image, isselected.<br>
The initial status of a message is 0.<br>
I am updating the status on a Button click by using the <code>setStatus()</code> method on the database.<br>
But the status does not change.<br>
I want to click my Button once and set the status to 1 and then click it once again to re-set the status to 0. </p>
<p>The <code>setStatus()</code> function is shown below:</p>
<pre><code> public int setStatus(People people) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues values = new ContentValues();
people.setStatus(1);
values.put(STATUS, people.getStatus());
return sqLiteDatabase.update(TABLE_PEOPLE, values, ID + "=?",
new String[]{String.valueOf(people.getId())});
}
</code></pre>
<p>My Button click event</p>
<pre><code> btnBuildNow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
peopleListSelected = new ArrayList<>();
for (People people : peopleList) {
if (people.getStatus()==1) {
db.setStatus(people);
peopleListSelected.add(people);
}
}
if (peopleListSelected.size() > 0) {
Intent intent = new Intent(BulidActivity.this, AlertList.class);
intent.putExtra("arrayList", (Serializable) peopleListSelected);
startActivity(intent);
}
}
});
</code></pre>
| <p>You did not pass the id which row you want to update (or you want to update all rows?), ISSELECTED variable is not declared. I mean this line:</p>
<pre><code>sqldb.update(TABLE_PEOPLE, cv, "id=" + ISSELECTED, null);
</code></pre>
<p>I would write like this (now I can't test it). I would pass the selected id to the update method's third parameter (that is the where clause, see the documentation: <a href="https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html" rel="nofollow">https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html</a>):</p>
<pre><code>public String setStatus(String selected) {
SQLiteDatabase sqldb = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("isselected", 1);
sqldb.update(TABLE_PEOPLE, cv, "id=" + selected, null);
sqldb.close();
return "Anything you want";
}
</code></pre>
<p>Another possible solution is to write your query directly:</p>
<pre><code>public String setStatus(String selected) {
SQLiteDatabase sqldb = this.getWritableDatabase();
sqldb.execSQL("UPDATE TABLE_PEOPLE SET ISSELECTED=1 WHERE id=" + selected);
sqldb.close();
return "Anything you want";
}
</code></pre>
<p><strong>EDIT:</strong>
Sorry, I forget to tell to modify the button click event, where <code>db.setStatus();</code> is called: use <code>db.setStatus(people.getId());</code>, or something like this (people.id, or something which represents the id of the people object, if it have any. If it don't have id, somehow you should acquire the id from the database.)</p>
|
make a sum of variable cells <p>i need your help with writhing a code. Below you can find an example of my sheet.<br>
I need to add the values of the totals from the subs and the result needs to come in the cell next to subtotaal in the main block. But here is the catch, the number of subs are not always the same. That also means the cells are variable. and below this main is another main with his subcategories.
the subs are added with another code. in this example there are only 2 subs, but in real the real sheet can be close to 20 subs. </p>
<p>I hope you guys understand what i'm trying to ask.
Grts</p>
<p><a href="http://i.stack.imgur.com/17cA0.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/17cA0.jpg" alt="enter image description here"></a></p>
| <p>I'm assuming your first Main block is in row 3; if not, modify this as appropriate:<br>
<code>=SUM(OFFSET($K4,0,0,MATCH("Main",$B4:$B1000,-1),1))</code></p>
<p>This formula will sum all the values in a particular range; the <code>OFFSET</code> function builds the range. It starts from a defined reference cell - K4, in this case - then creates a range by moving down a specified number of rows, then right a specified number of columns - 0 rows, 0 columns for us - and returns a range of a specified height and 1 column in width.</p>
<p>We get the height from the <code>MATCH</code> function. This function looks for the first cell that starts with the word "Main" anywhere in the next 1,000 rows. The 1,000 here is more or less arbitrary, it can be any value that you're certain will find the next "Main" header.</p>
<p>The disadvantage of this formula is that if there isn't a match found - say if this is used on the last "Main" block and there's no Main header below it - it will return an error. We can control for that by adding an <code>IFERROR</code> function to get:<br>
<code>=SUM(OFFSET($K4,0,0,IFERROR(MATCH("Main",$B$4:$B$1000,-1),50),1))</code>, which will assume a range of 50 cells if a match isn't found.</p>
|
Find out the letter frequency in from a list in Python <p>I'm trying to code a program that will count the occurence of different chars in a list. I want to find the 7 most common once and also want to count the % of the occurence of that letter of the total amount of letters.</p>
<pre><code>fileOpen = open("lol.txt", 'r')
savedWordData = fileOpen.read()
fileOpen.close()
#To split into chars and function to clear the string from faulty chars
savedWordData = cleanString(savedWordData)
savedWordData = savedWordData.replace(" ", "")
#print(savedWordData)
#Use this to count the total number of chars and find the 7 most common once
from collections import Counter
data = Counter(savedWordData)
print("The 7 most common letters: " + str(data.most_common(7)))
sumOfAll = sum(data.values())
</code></pre>
<p>But not sure how I should continue from here. How do I access the values from the data dict so I can see the occurrence of each letter?</p>
| <p>You can use <a href="https://docs.python.org/2/library/collections.html#collections.Counter.most_common" rel="nofollow"><code>most_common</code></a>, and then loop on the list to get the values :</p>
<pre><code>In [35]: s = 'ieufisjhfkdfhgdfkjvwoeiweuieanvszudadyuieafhuskdjfhdviurnawuevnskzjdvnziurvzdkjHFiuewhksjnvviuzsdiufwekfvnxkjvnsdv'
In [36]: l = list(s)
In [37]: from collections import Counter
In [38]: data = Counter(l)
In [39]: data.most_common()
Out[39]:
[('u', 11),
('v', 11),
('d', 10),
('i', 10),
('k', 8),
('e', 8),
('f', 8),
('s', 7),
('j', 7),
('n', 7),
('z', 5),
('w', 5),
('h', 5),
('a', 4),
('r', 2),
('g', 1),
('H', 1),
('y', 1),
('x', 1),
('o', 1),
('F', 1)]
In [40]: for i in range(0, 7):
...: print(data.most_common()[i])
...:
('u', 11)
('v', 11)
('d', 10)
('i', 10)
('k', 8)
('e', 8)
('f', 8)
</code></pre>
<p>The first value is the letter, the second one is the number of occurrence.</p>
|
Reading another Clojure program as a list of S-Expressions <p>Suppose I have a very simple <code>.clj</code> file on disk with the following content:</p>
<pre><code>(def a 2)
(def b 3)
(defn add-two [x y] (+ x y))
(println (add-two a b))
</code></pre>
<p>From the context of separate program, I would like to read the above program as a list of S-Expressions, <code>'((def a 2) (def b 3) ... (add-two a b)))</code>.</p>
<p>I imagine that one way of doing this involves 1. Using <code>slurp</code> on <code>(io/file file-name.clj)</code> to produce a string containing the file's contents, 2. passing that string to a parser for Clojure code, and 3. injecting the sequence produced by the parser to a list (i.e., <code>(into '() parsed-code)</code>).</p>
<p>However, this approach seems sort of clumsy and error prone. <strong>Does anyone know of a more elegant and/or idiomatic way to read a Clojure file as a list of S-Expressions?</strong></p>
<p><strong>Update:</strong> Following up on feedback from the comments section, I've decided to try the approach I mentioned on an actual source file using aphyr's <a href="https://github.com/aphyr/clj-antlr" rel="nofollow">clj-antlr</a> as follows:</p>
<pre><code>=> (def file-as-string (slurp (clojure.java.io/file "src/tcl/core.clj")))
=> tcl.core=> (pprint (antlr/parser "src/grammars/Clojure.g4" file-as-string))
{:parser
{:local
#object[java.lang.ThreadLocal 0x5bfcab6 "java.lang.ThreadLocal@5bfcab6"],
:grammar
#object[org.antlr.v4.tool.Grammar 0x5b8cfcb9 "org.antlr.v4.tool.Grammar@5b8cfcb9"]},
:opts
"(ns tcl.core\n (:gen-class)\n (:require [clj-antlr.core :as antlr]))\n\n(def foo 42)\n\n(defn parse-program\n \"uses antlr grammar to \"\n [program]\n ((antlr/parser \"src/grammars/Clojure.g4\") program))\n\n\n(defn -main\n \"I don't do a whole lot ... yet.\"\n [& args]\n (println \"tlc is tcl\"))\n"}
nil
</code></pre>
<p><strong>Does anyone know how to transform this output to a list of S-Expressions as originally intended?</strong> That is, how might one go about squeezing valid Clojure code/data from the result of parsing with clj-antlr?</p>
| <pre><code>(import '[java.io PushbackReader])
(require '[clojure.java.io :as io])
(require '[clojure.edn :as edn])
;; adapted from: http://stackoverflow.com/a/24922859/6264
(defn read-forms [file]
(let [rdr (-> file io/file io/reader PushbackReader.)
sentinel (Object.)]
(loop [forms []]
(let [form (edn/read {:eof sentinel} rdr)]
(if (= sentinel form)
forms
(recur (conj forms form)))))))
(comment
(spit "/tmp/example.clj"
"(def a 2)
(def b 3)
(defn add-two [x y] (+ x y))
(println (add-two a b))")
(read-forms "/tmp/example.clj")
;;=> [(def a 2) (def b 3) (defn add-two [x y] (+ x y)) (println (add-two a b))]
)
</code></pre>
|
Printing out 500 random triangles in java <p>I have a problem with printing 500 triangles in window.</p>
<p>The code I created shows one traingle and it only changes while I'm resizing window, and I have to make all 500 traingles appear at once. Any idea how to do this?</p>
<pre><code>import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class BoringTriangle extends Canvas {
public void paint(Graphics g){
Random nmb = new Random();
//Colours
int x1 = nmb.nextInt(200) + 1;
int x2 = nmb.nextInt(200) + 1;
int x3 = nmb.nextInt(200) + 1;
int x4 = nmb.nextInt(500) + 1;
int x5 = nmb.nextInt(500) + 1;
int x6 = nmb.nextInt(500) + 1;
int x7 = nmb.nextInt(500) + 1;
int x8 = nmb.nextInt(500) + 1;
int x9 = nmb.nextInt(500) + 1;
for(int z = 1; z<=500; z++) {
g.setColor(new Color(x1, x2, x3));
g.fillPolygon(new int[]{x4, x5, x6}, new int[]{x7, x8, x9}, 3);
}
}
public static void main( String[] args )
{
// You can change the title or size here if you want.
JFrame win = new JFrame("Boring Traingle lul");
win.setSize(800,600);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BoringTriangle canvas = new BoringTriangle();
win.add( canvas );
win.setVisible(true);
}
}
</code></pre>
| <p>Move the generation of the random numbers to the body of the loop. Otherwise you'll draw the same triangle 500 times:</p>
<pre><code>for(int z = 0; z < 500; z++) {
int x1 = nmb.nextInt(200) + 1;
int x2 = nmb.nextInt(200) + 1;
int x3 = nmb.nextInt(200) + 1;
int x4 = nmb.nextInt(500) + 1;
int x5 = nmb.nextInt(500) + 1;
int x6 = nmb.nextInt(500) + 1;
int x7 = nmb.nextInt(500) + 1;
int x8 = nmb.nextInt(500) + 1;
int x9 = nmb.nextInt(500) + 1;
g.setColor(new Color(x1, x2, x3));
g.fillPolygon(new int[]{x4, x5, x6}, new int[]{x7, x8, x9}, 3);
}
</code></pre>
<p>In case you also want to keep the triangles the same when repainting, save the values to a suitable data structure:</p>
<pre><code>private Color[] colors;
private int[][][] coordinates;
BoringTriangle() {
Random nmb = new Random();
colors = new Color[500];
coordinates = new int[500][2][];
for (int i = 0; i < 500; i++) {
colors[i] = new Color(nmb.nextInt(200) + 1, nmb.nextInt(200) + 1, nmb.nextInt(200) + 1);
coordinates[i][0] = new int[] {nmb.nextInt(500) + 1, nmb.nextInt(500) + 1, nmb.nextInt(500) + 1};
coordinates[i][1] = new int[] {nmb.nextInt(500) + 1, nmb.nextInt(500) + 1, nmb.nextInt(500) + 1};
}
}
public void paint(Graphics g) {
for(int i = 0; i < colors.length; i++) {
g.setColor(colors[i]);
g.fillPolygon(coordinates[i][0], coordinates[i][1], 3);
}
}
</code></pre>
|
cocos2d-x v3 c++ Drop shadow cocos2d::Sprite <p>As far as I've found out, cocos doesn't offer a simple filter handling like AS3 for example does.</p>
<p>My situation:
I want to add a realtime shadow to an cocos2d::Sprite.</p>
<p>For example I would like to do something like this (similar to AS3):</p>
<pre><code>auto mySprite = Sprite::createWithSpriteFrameName("myCharacter.png");
DropShadowFilter* dropShadow = new DropShadowFilter();
dropShadow->distance = 0;
dropShadow->angle = 45;
dropShadow->color = 0x333333;
dropShadow->alpha = 1;
dropShadow->blurX = 10;
dropShadow->blurY = 10;
dropShadow->strength = 1;
dropShadow->quality = 15;
mySprite->addFilter(dropShadow);
</code></pre>
<p>This should add a shadow to my Sprite to achieve an result like this:
<a href="http://help.adobe.com/en_US/as3/mobile/images/or_sample_shadow.png" rel="nofollow">Adobe Drop Shadow Example</a></p>
<p>Could you help me please?</p>
| <p>There isn't any built in support for shadows on <code>Sprites</code> in Cocos2D-X.</p>
<p>The best option, performance-wise, would be to place your shadows in your sprite images already, instead of calculating and drawing them in the code.</p>
<p>Another option is to sub-class <code>Sprite</code> and override the <code>draw</code> method so that you duplicate the sprite and apply your effects and draw it below the original.</p>
<p>One possible way to achieve that is with this snippet from <a href="http://discuss.cocos2d-x.org/t/shadow-sprites/1214/2" rel="nofollow">this thread on the Cocos forum</a>. I can't say that I completely follow what this code does with the GL transforms, but you can use this as a starting point to experiment.</p>
<pre><code>void CMySprite::draw()
{
// is_shadow is true if this sprite is to be considered like a shadow sprite, false otherwise.@
if (is_shadow)
{
ccBlendFunc blend;
// Change the default blending factors to this one.
blend.src = GL_SRC_ALPHA;
blend.dst = GL_ONE;
setBlendFunc( blend );
// Change the blending equation to thi in order to subtract from the values already written in the frame buffer
// the ones of the sprite.
glBlendEquationOES(GL_FUNC_REVERSE_SUBTRACT_OES);
}
CCSprite::draw();
if (is_shadow)
{
// The default blending function of cocos2d-x is GL_FUNC_ADD.
glBlendEquationOES(GL_FUNC_ADD_OES);
}
}
</code></pre>
|
Select value with check if between two values <p>I have the following table in excel:</p>
<pre><code> 0 1150 0.27
1151 1200 0.26
1201 1250 0.24
1251 1300 0.24
1301 1350 0.23
1351 1400 0.22
1401 1450 0.21
1451 1500 0.2
1501 1550 0.2
1551 1600 0.19
</code></pre>
<p>Now I am looking for a formula which is taking a value from a cell (I24), looks if it between the first and second value of the table and returns the third value. For example when the value of I24 is 1275 the formula should return 0.24</p>
| <p>Assuming your table starts on <code>Column A</code> and the value you mentioned is in <code>I24</code>:</p>
<pre><code>=IF(AND(I24>A24,I24<B24),C24, "")
</code></pre>
|
Undefined reference to 'testing::UnitTest::GetInstance()" <p>I am migrating from the makefile automatically created by Eclipse to a manual makefile. It does work with Eclipse's, but not with mine. This is the compiler output:</p>
<pre><code>13:54:30 **** Incremental Build of configuration Debug for project MY_PROJECT ****
make -f ../build/makefile all
Building file: ../src/TestLauncher.cpp
g++ -std=c++11 -I"../src" -I"../src/Common" -I"../src/Common/COMPUTATION" -I"../src/Common/DATA_ACQUISITION" -I"/usr/include/mysql" -I"/usr/include/gtest" -O0 -g3 -pg -Wall -Wextra -fmessage-length=0 --coverage -fPIC -MMD -MP -MF"../bin/objs/TestLauncher.d" -MT"../bin/objs/TestLauncher.o" -o "../bin/objs/TestLauncher.o" "../src/TestLauncher.cpp"
/tmp/ccrDQ0Bm.o: In function `main':
/home/user/workspace/MY_PROJECT/build/../src/TestLauncher.cpp:13: undefined reference to `testing::InitGoogleTest(int*, char**)'
../build/makefile:165: recipe for target '../bin/objs/TestLauncher.o' failed
/tmp/ccrDQ0Bm.o: In function `RUN_ALL_TESTS()':
/usr/include/gtest/gtest.h:2288: undefined reference to `testing::UnitTest::GetInstance()'
/usr/include/gtest/gtest.h:2288: undefined reference to `testing::UnitTest::Run()'
collect2: error: ld returned 1 exit status
make: *** [../bin/objs/TestLauncher.o] Error 1
13:54:31 Build Finished (took 989ms)
</code></pre>
<p>I have looked for this error and it always seems to be related to not being using -lgtest among linker flags. I am, but anyway this error is not happening at the linker but at the compilation phase. Therefore, I don't understand why this problem is being raised.</p>
<p>I also have compiled <code>gtest</code> library, which is in <code>/usr/lib/</code>: as I said, it works with Eclipse's makefile.</p>
<p>This is my makefile:</p>
<pre><code>-include ../makefile.init
RM := rm -rf
EXECUTABLE_NAME := MY_PROJECT
FLAGS := -O0 -g3 -pg -Wall -Wextra -fmessage-length=0 --coverage -fPIC #-v
C++_DEPS :=
C_DEPS :=
CC_DEPS :=
CPP_DEPS :=
CXX_DEPS :=
C_UPPER_DEPS :=
EXECUTABLES := ../bin/$(EXECUTABLE_NAME)
LIBS_SERVER := -ldl -lpthread -lgtest -lboost_date_time -lmysqlclient -lboost_filesystem -lboost_system
INCLUDES_LIB_SERVER := -L /usr/lib/mysql -L /usr/lib/boost
CPP_SRCS += \
../src/TestLauncher.cpp \
../src/Common/DATA_ACQUISITION/DATA_ACQUISITION_test.cpp
OBJS += \
../bin/objs/TestLauncher.o \
../bin/objs/DATA_ACQUISITION_test.o
CPP_DEPS += \
../bin/objs/TestLauncher.d \
../bin/objs/DATA_ACQUISITION_test.d
INCLUDES_SERVER += \
-I"../src" \
-I"../src/Common" \
-I"../src/Common/COMPUTATION" \
-I"../src/Common/DATA_ACQUISITION" \
-I"/usr/include/mysql" \
-I"/usr/include/gtest"
ifneq ($(MAKECMDGOALS),clean)
ifneq ($(strip $(C++_DEPS)),)
-include $(C++_DEPS)
endif
ifneq ($(strip $(CC_DEPS)),)
-include $(CC_DEPS)
endif
ifneq ($(strip $(C_DEPS)),)
-include $(C_DEPS)
endif
ifneq ($(strip $(CPP_DEPS)),)
-include $(CPP_DEPS)
endif
ifneq ($(strip $(CXX_DEPS)),)
-include $(CXX_DEPS)
endif
ifneq ($(strip $(C_UPPER_DEPS)),)
-include $(C_UPPER_DEPS)
endif
endif
-include ../makefile.defs
###############################################################################
# TARGETS
###############################################################################
# All Target
all: $(EXECUTABLES)
test: FLAG=-DTEST
test: all
../bin/$(EXECUTABLE_NAME): $(OBJS)
@echo 'Building target: $@'
@echo 'Invoking: Cygwin C++ Linker'
g++ $(FLAGS) -o"../bin/$(EXECUTABLE_NAME)" $(OBJS) $(INCLUDES_LIB_SERVER) $(LIBS_SERVER)
@echo 'Finished building target: $@'
@echo ' '
# Other Targets
clean:
-$(RM) $(OBJS) $(OBJS_RT) $(C++_DEPS) $(EXECUTABLES)$(CC_DEPS)$(C_DEPS)$(CPP_DEPS)$(CXX_DEPS)$(C_UPPER_DEPS) ../bin/MY_PROJECT
-@echo ' '
.PHONY: all clean dependents
.SECONDARY:
###############################################################################
# COMPILE --> OBJS
###############################################################################
../bin/objs/%.o: ../src/%.cpp
@echo 'Building file: $<'
g++ -std=c++11 $(INCLUDES_SERVER) $(FLAGS) -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
../bin/objs/%.o: ../src/Common/%.cpp
@echo 'Building file: $<'
g++ -std=c++11 $(INCLUDES_SERVER) $(FLAGS) -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
../bin/objs/%.o: ../src/Common/COMPUTATION/%.cpp
@echo 'Building file: $<'
g++ -std=c++11 $(INCLUDES_SERVER) $(FLAGS) -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
../bin/objs/%.o: ../src/Common/DATA_ACQUISITION/%.cpp
@echo 'Building file: $<'
g++ -std=c++11 $(INCLUDES_SERVER) $(FLAGS) -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
</code></pre>
<p>Any idea of what's wrong?</p>
| <p>Keep in mind that for -l flags, the order is very important. Are you sure the -lgtest is in the correct position ?</p>
<p>Also, the linker expects a libgtest.so file for -lgtest, not just gtest.</p>
<p>Hope it helped. </p>
|
ASP.NET DefaultButton is focused on page load <p>I'm setting the propriety <code>DefaultButton</code> on my asp form, in order to send the form on the key <code>Enter</code>.</p>
<p>Everything is working fine, but my button has the focus state on the page load which is bothering because of some CSS styles applied on the page.</p>
<pre><code><form id="loginForm" runat="server" DefaultButton="btnLogin">
...
</form>
</code></pre>
<p>I would like the button to not be focused on the page load.</p>
<p>Thank you for your help</p>
| <p>This is the default behavior of default button in ASP.NET. What you can do to override that is to set default focus manually on some other control. To do so, call <code>Page.SetFocus</code>:</p>
<pre><code>Page.SetFocus(SomeOtherControlID);
</code></pre>
<p>This will set focus control on the form like that:</p>
<pre><code><form id="loginForm" runat="server"
DefaultFocus="SomeOtherControlID"
DefaultButton="btnLogin">
</code></pre>
|
How to return Any from a function? <p>I am working on type system for a database project. One problem is mapping a type id to a reader that given an type id and address, a function can return given any data type from built in <code>u32</code>, <code>String</code>, to defined structs. </p>
<p>I don't have any problem on writers, like such macro</p>
<pre><code> fn set_val (data: &Any, id:i32, mem_ptr: usize) {
match id {
$(
$id => $io::write(*data.downcast_ref::<$t>().unwrap(), mem_ptr),
)*
_ => (),
}
}
</code></pre>
<p>But for the reader <code>Any</code> seems not comfortable to be used as return value because the <code>the trait bound "std::any::Any + 'static: std::marker::Sized" is not satisfied</code>. I also tried to return as a reference, but I am stuck at a lifetime</p>
<pre><code> fn get_val (id:i32, mem_ptr: usize) -> Option<& Any> {
match id {
$(
$id => Some(&$io::read(mem_ptr)),
)*
_ => None,
}
}
</code></pre>
<p>which complains <code>missing lifetime specifier</code>. If <code>'static</code> won't work here due to the return value not live long enough, how can I specify the lifetime here?</p>
<p>PS. The read function from $io returns any kinds of types.</p>
| <p><a href="https://doc.rust-lang.org/std/any/trait.Any.html"><code>Any</code></a> is a trait, which means that it is unsized and thus cannot be returned by a function as is.</p>
<p>However, you can try boxing it:</p>
<pre><code>fn get_val (id:i32, mem_ptr: usize) -> Option<Box<Any>> {
match id {
$(
$id => Some(Box::new($io::read(mem_ptr))),
)*
_ => None,
}
}
</code></pre>
<p>An example <a href="https://play.rust-lang.org/?code=use%20std%3A%3Aany%3A%3AAny%3B%0A%0Astatic%20DATA%3A%20%5Bu8%3B%202%5D%20%3D%20%5B1%2C%202%5D%3B%0A%0Afn%20fun(numbers%3A%20bool)%20-%3E%20Box%3CAny%3E%20%7B%0A%20%20%20%20if%20numbers%20%7B%0A%20%20%20%20%20%20%20%20Box%3A%3Anew(%26DATA)%0A%20%20%20%20%7D%20else%20%7B%0A%20%20%20%20%20%20%20%20Box%3A%3Anew(String%3A%3Afrom(%22Heya!%22))%0A%20%20%20%20%7D%0A%7D%0A%0Afn%20main()%20%7B%0A%20%20%20%20let%20smth%20%3D%20fun(true)%3B%0A%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%20smth.downcast_ref%3A%3A%3C%26%5Bu8%3B%202%5D%3E())%3B%0A%20%20%20%20let%20smth%20%3D%20fun(false)%3B%0A%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%20smth.downcast_ref%3A%3A%3CString%3E())%3B%0A%7D&version=stable&backtrace=0">playpen</a>.</p>
|
Making a countdown timer that doesn't interrupt the entire program? <p>So I'm trying to make a reaction game where you press start button, a hidden timer that will countdown to zero from a random number between 1 & 10 seconds. Most answer regarding java timers recommend using </p>
<blockquote>
<p>Thread.sleep(1000);</p>
</blockquote>
<p>However this interrupts the entire program while I just wants it to countdown. How should I solve this? </p>
<p>After pressing start and the program has counted down from a random number. The blue icon (entire code below) will turn red and then you're supposed to press it and it will display the time it took for you to press it. </p>
<p>Code is focus:</p>
<pre><code> public void countDown() throws InterruptedException {
int random = r.nextInt((10000 - 1000) + 1) + 1000;
while(random >= 0){
Thread.sleep(1000);
random -= 1000;
}
if (random <= 0) {
button_1.setIcon(img_react);
repaint();
}
}
</code></pre>
<hr>
<p>Image files used: </p>
<p><a href="http://imgur.com/DjI8Udr" rel="nofollow">http://imgur.com/DjI8Udr</a></p>
<p><a href="http://imgur.com/XKQW6DI" rel="nofollow">http://imgur.com/XKQW6DI</a></p>
<p>Entire code: </p>
<pre><code> import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
import java.util.*;
public class Interface extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
ImageIcon img_idle = new ImageIcon("img_idle.png");
ImageIcon img_react = new ImageIcon("img_react.png");
JButton button_1 = new JButton(img_idle);
JButton start = new JButton("Start");
Random r = new Random();
public Interface() {
super("Simple Reaction Game");
setSize(180, 350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
Container contentArea = getContentPane();
contentArea.setBackground(Color.white);
FlowLayout flowManager = new FlowLayout();
contentArea.setLayout(flowManager);
button_1.addActionListener(this);
start.addActionListener(this);
contentArea.add(button_1);
contentArea.add(start);
setContentPane(contentArea);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == start) {
try {
countDown();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
public void countDown() throws InterruptedException {
Thread t = new Thread();
int random = r.nextInt((10000 - 1000) + 1) + 1000;
while(random >= 0){
t.sleep(1000);
random -= 1000;
}
if (random <= 0) {
button_1.setIcon(img_react);
repaint();
}
}
public static void main(String args[]) {
new Interface();
}
}
</code></pre>
| <p>You can't just use <code>Thread.sleep()</code>, it won't work as you think it does. Instead, you can use <a href="https://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html" rel="nofollow"><code>javax.swing.Timer</code></a> which is made to do what you're trying to do.</p>
<p>Some notes from the docs (if you didn't bother reading it):</p>
<ul>
<li>Timers perform their waiting using a single, shared thread.</li>
<li>Timers can safely perform operations on Swing components. </li>
<li>Timers can safely perform operations on Swing components. </li>
<li>The javax.swing.Timer has two features that can make it a little easier to use with GUIs.</li>
</ul>
<p>I've modified an example from <a href="http://stackoverflow.com/a/28338476/4195825">here</a> to show how you can adapt it to your needs. It's using your random generated number which is generated each time the timer is finished and you press "start".</p>
<pre><code>import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import javax.swing.*;
import javax.swing.UnsupportedLookAndFeelException;
import java.util.Random;
public class Interface {
public static void main(String[] args) {
new Interface();
}
public Interface() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Timer timer;
private long startTime = -1;
private long duration;
private JLabel label;
private JButton start;
public TestPane() {
start = new JButton("Start");
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (startTime < 0) {
startTime = System.currentTimeMillis();
}
long now = System.currentTimeMillis();
long clockTime = now - startTime;
if (clockTime >= duration) {
clockTime = duration;
timer.stop();
}
SimpleDateFormat df = new SimpleDateFormat("mm:ss:SSS");
label.setText(df.format(duration - clockTime));
}
});
timer.setInitialDelay(0);
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!timer.isRunning()) {
duration = new Random().nextInt((10000 - 1000) + 1) + 1000;
startTime = -1;
timer.start();
}
}
});
label = new JLabel("...");
add(label);
add(start);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 250);
}
}
}
</code></pre>
|
How Do I Implement a Popover in a Rails Partial Using Bootstrap 3? <p>I currently have a Rails 4 application running Bootstrap 2 (gem twitter-bootstrap-rails 2.2.8). I was successful in implementing a popover using partials where a map is displayed when a link is clicked. Here is the code that I have.</p>
<p>application.js</p>
<pre><code>//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require_tree .
</code></pre>
<p>bootstrap.js.coffee</p>
<pre><code>jQuery ->
$(".popover-map").popover({ html : true })
</code></pre>
<p>_map</p>
<pre><code><div class="row-fluid">
<div class="span4" align="center" id="text-bold"><%= link_to("#{t :map_marfa_head}" , '#', class: "popover-map", rel: "popover", title: "#{t :map_marfa_head}", :"data-placement" => "bottom", :"data-content" => "#{render 'pages/map_marfa'}") %></div>
<div class="span4" align="center" id="text-85"><%= "#{t :map_msg_click}" %></div>
<div class="span4" align="center" id="text-bold"><%= link_to("#{t :map_bigbend_head}" , '#', class: "popover-map", rel: "popover", title: "#{t :map_bigbend_head}", :"data-placement" => "bottom", :"data-content" => "#{render 'pages/map_bigbend'}") %></div>
</div>
</code></pre>
<p>_map_marfa</p>
<pre><code><p align="center"><%= image_tag("map-marfa.jpg", alt: "#{t :map_marfa_head}") %></p>
</code></pre>
<p>_map_bigbend</p>
<pre><code><p align="center"><%= image_tag("map-bigbend.jpg", alt: "#{t :map_bigbend_head}") %></p>
</code></pre>
<p>When I click either link the map display below and stays there until the person clicks the link again to close the map. I have copied the code to my new Rails 5 Bootstrap 3 application. Here are the code changes for Bootstrap 3.</p>
<p>application.js</p>
<pre><code>//= require bootstrap-sprockets
</code></pre>
<p>bootstrap.js.coffee was renamed to bootstrap.coffee</p>
<pre><code>//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
//= require bootstrap-sprockets
</code></pre>
<p>_map</p>
<pre><code><div class="row">
<div class="col-md-4" align="center" id="text-bold"><%= link_to("#{t :map_marfa_head}" , '#', class: "popover-map", rel: "popover", title: "#{t :map_marfa_head}", :"data-placement" => "bottom", :"data-content" => "#{render 'pages/map_marfa'}") %></div>
<div class="col-md-4" align="center" id="text-85"><%= "#{t :map_msg_click}" %></div>
<div class="col-md-4" align="center" id="text-bold"><%= link_to("#{t :map_bigbend_head}" , '#', class: "popover-map", rel: "popover", title: "#{t :map_bigbend_head}", :"data-placement" => "bottom", :"data-content" => "#{render 'pages/map_bigbend'}") %></div>
</div>
</code></pre>
<p>Now when I click either link the map displays and immediately disappears instead of staying until the link is clicked.</p>
| <p>I kept looking at this and realized that in <code>application.js</code> I required turbolinks. For whatever reason it messes up things I try to do. I removed <code>//= require turbolinks</code> and my scripts work again. Go figure.</p>
|
vba to get email senders details from GAL <p>I am trying to get the email senders's details (eg. name, job title, dept etc) from a folder. I am able to get required details for the conacts in my address book, however I am not getting details about the contacts in GAL.</p>
<p>My code is as below:</p>
<pre><code>Public Sub DisplaySenderDetails()
Dim Sender As Outlook.AddressEntry
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim rCount As Long
Dim bXStarted As Boolean
Dim enviro As String
Dim strPath As String
Dim strColB, strColC, strColD, strColE, strColF, strColG As String
Dim objOL As Outlook.Application
Dim objItems As Outlook.Items
Dim objFolder As Outlook.MAPIFolder
Dim obj As Object
Dim objNS As Outlook.NameSpace
Dim olItem As Outlook.MailItem
Dim strdate As String
Dim oExUser As Outlook.ExchangeUser
Dim olGAL As Outlook.AddressList
Dim olEntry As Outlook.AddressEntries
' Get Excel set up
enviro = CStr(Environ("USERPROFILE"))
'the path of the workbook
strPath = enviro & "\Documents\test2.xlsx"
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Application.StatusBar = "Please wait while Excel source is opened ... "
Set xlApp = CreateObject("Excel.Application")
bXStarted = True
End If
On Error GoTo 0
'Open the workbook to input the data
Set xlWB = xlApp.Workbooks.Open(strPath)
Set xlSheet = xlWB.Sheets("Sheet1")
Set objNS = GetNamespace("MAPI")
Set olGAL = objNS.GetGlobalAddressList()
Set objFolder = objNS.GetDefaultFolder(olFolderInbox).Folders("Abc")
Set objItems = objFolder.Items
Set olEntry = olGAL.AddressEntries
For Each obj In objItems
With obj
Set Sender = obj.Sender
Set olItem = obj
If TypeName(obj) = "MailItem" Then
On Error Resume Next
Dim i As Long
For i = 1 To olEntry.Count
If olEntry.Item.Address = Sender.Address Then
Set oExUser = Sender.GetExchangeUser
rCount = xlSheet.Range("B" & xlSheet.Rows.Count).End(-4162).Row
rCount = rCount + 1
strdate = DateValue(olItem.ReceivedTime)
If strdate >= #7/1/2016# Then
strColB = Sender.Name
strColC = oExUser.JobTitle
strColD = oExUser.Department
strColE = oExUser.PrimarySmtpAddress
strColF = olItem.Subject
strColG = olItem.ReceivedTime
xlSheet.Range("B" & rCount) = strColB
xlSheet.Range("C" & rCount) = strColC
xlSheet.Range("D" & rCount) = strColD
xlSheet.Range("E" & rCount) = strColE
xlSheet.Range("F" & rCount) = strColF
xlSheet.Range("G" & rCount) = strColG
strColB = ""
strColC = ""
strColD = ""
strColE = ""
strColF = ""
trColG = ""
Else
Exit For
End If
End If
Next i
End If
End With
Next
Set obj = Nothing
Set objItems = Nothing
Set objFolder = Nothing
Set objOL = Nothing
</code></pre>
<p>End Sub</p>
| <p>I am using the following function</p>
<pre><code>Private Function getSmtpMailAddress(sMail As Outlook.mailItem) As String
Dim strAddress As String
Dim strEntryId As String
Dim objRecipient As Outlook.Recipient
Dim objSession As Outlook.NameSpace
Dim objAddressentry As Outlook.AddressEntry
Dim objExchangeUser As Outlook.ExchangeUser
Dim objReply As Outlook.mailItem
On Error GoTo ErrHandler
If sMail.SenderEmailType = "SMTP" Then
strAddress = sMail.SenderEmailAddress
Else
Set objReply = sMail.reply()
Set objRecipient = objReply.recipients.item(1)
strEntryId = objRecipient.EntryID
objReply.Close OlInspectorClose.olDiscard
Set objSession = getMapiSession
strEntryId = objRecipient.EntryID
Set objAddressentry = objSession.GetAddressEntryFromID(strEntryId)
Set objExchangeUser = objAddressentry.GetExchangeUser()
strAddress = objExchangeUser.PrimarySmtpAddress()
End If
getSmtpMailAddress = strAddress
Exit Function
ErrHandler:
Err.Clear
On Error GoTo 0
getSmtpMailAddress = "???"
End Function
</code></pre>
<p>Helper routines in a separate module:</p>
<pre><code>Private objNameSpace As NameSpace
Private Sub logonMapiSession()
Set objNameSpace = Application.GetNamespace("MAPI")
objNameSpace.Logon Profile:="", Password:="", ShowDialog:=False, NewSession:=False
End Sub
Public Sub logoffMapiSession()
If Not (objNameSpace Is Nothing) Then
objNameSpace.Logoff
Set objNameSpace = Nothing
End If
End Sub
Public Function getMapiSession() As NameSpace
If objNameSpace Is Nothing Then
logonMapiSession
End If
Set getMapiSession = objNameSpace
End Function
</code></pre>
|
Is not less than "value" vb.net <p>I want to add another logical condition. Which is "is not less than 1".</p>
<pre><code>If DataGridView1.Item(6, i).Value <= 90 Then
</code></pre>
| <p>"Is Not less than" you mean "Greater than or equal to?" i.e., `>='</p>
<p>So:</p>
<p><code>If DataGridView1.Item(6, i).Value <= 90
And DataGridView1.Item(6, i).Value >= 1 Then</code></p>
|
Apache POI generating document and sorting inside <p>I am trying to '<em>group</em>' my transactions by a 'transactionBatch' parameter. I see that my HashMap is successful in gathering unique batches. When I debug the below code everything seems to be done correctly. Although when I check the excel file, transactions are not grouped accordingly. They should be grouped:</p>
<pre><code>batch # 1:
- transaction with batch # 1
- transaction with batch # 1
batch # 2:
- transaction with batch # 2
- transaction with batch # 2
</code></pre>
<p>The result excel file contains:</p>
<pre><code>batch # 1:
- transaction with batch # 1
- transaction with batch # 2
batch # 2:
- transaction with batch # 4
- transaction with batch # 1
</code></pre>
<p>This is the code:</p>
<pre><code>HashMap<String, String> hashMap = new HashMap<>();
for (int i = 0; i < nodeList.getLength(); i++) {
hashMap.put(((Element) (nodeList.item(i))).getElementsByTagName("transactionBatch").item(0)
.getFirstChild().getNodeValue(), ((Element) (nodeList.item(i))).getElementsByTagName("transactionBatchDate").item(0)
.getFirstChild().getNodeValue());
}
for (Map.Entry<String, String> entry : hashMap.entrySet()) {
for (int i = 0; i < nodeList.getLength(); i++) {
String transactionBatch = ((Element) (nodeList.item(i))).getElementsByTagName("transactionBatch").item(0)
.getFirstChild().getNodeValue();
String key = entry.getKey();
if (transactionBatch.equals(key)) {
HSSFRow dynamicRow = spreadSheet.createRow(i + 2);
if (nodeList.getLength() != 0) {
cell = dynamicRow.createCell((short) 0);
cell.setCellValue(((Element) (nodeList.item(i))).getElementsByTagName("transactionNumber").item(0)
.getFirstChild().getNodeValue());
cell.setCellStyle(styleWithDataCentered);
...
cell = dynamicRow.createCell((short) 8);
cell.setCellValue(((Element) (nodeList.item(i))).getElementsByTagName("transactionBatch").item(0)
.getFirstChild().getNodeValue());
cell.setCellStyle(styleWithDataCentered);
}
}
}
}
</code></pre>
| <p>The problem was in this line: </p>
<pre><code>HSSFRow dynamicRow = spreadSheet.createRow(i + 2);
</code></pre>
<p>I had to assign another variable outside of the for method to keep a int:</p>
<pre><code>int rowNumber = 2;
</code></pre>
<p>and then just increase its value with each row. </p>
<pre><code>HSSFRow dynamicRow = spreadSheet.createRow(rowNumber += 1);
</code></pre>
|
Google Chart IE9 Issue (undefined) <p>I'm developing some charts for use across all supported browsers and am getting an error only in IE9. Console states either: gvjs_wa is undefined, gvjs_t is undefined or gvjs_uz is undefined.</p>
<p>Thanks!</p>
<pre><code><HTML>
<head>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function drawGLine() {
var bin =JSON.parse('[0.65, 0.78, 1.16, 1.68, 2.0, 2.56, 3.03, 3.65, 4.51, 5.16, 6.0, 6.58, 7.47, 8.57, 9.58, 10.38, 11.28, 12.25, 13.03, 13.78, 14.8, 15.69, 16.49, 17.33, 18.06, 18.96, 20.49, 21.85, 22.94, 24.14, 25.31, 26.27, 27.22, 28.12, 29.87, 31.56, 32.58, 33.67, 35.14, 37.33, 38.41, 40.02, 41.87, 43.31, 44.98, 46.03, 47.84, 49.1, 50.81, 52.38, 54.17, 55.37, 57.3, 59.13, 61.14, 63.39, 64.43, 65.92, 67.53, 69.04, 70.82, 72.07, 73.17, 74.9, 76.63, 78.16, 79.2, 80.33, 81.09, 82.36, 83.34, 84.35, 85.27, 86.48, 87.58, 88.37, 89.25, 89.89, 90.68, 91.24, 92.2, 92.83, 93.87, 94.82, 95.38, 95.94, 96.58, 97.21, 97.45, 97.85, 98.25, 98.57, 98.81, 98.81, 99.28, 99.44, 99.44, 99.6, 99.84, 100.0, 100.0]');
var culmativeData =JSON.parse('[0.0, 7.0, 14.0, 21.0, 28.0, 34.0, 41.0, 48.0, 55.0, 62.0, 69.0, 76.0, 83.0, 89.0, 96.0, 103.0, 110.0, 117.0, 124.0, 131.0, 138.0, 144.0, 151.0, 158.0, 165.0, 172.0, 179.0, 186.0, 193.0, 200.0, 206.0, 213.0, 220.0, 227.0, 234.0, 241.0, 248.0, 255.0, 261.0, 268.0, 275.0, 282.0, 289.0, 296.0, 303.0, 310.0, 316.0, 323.0, 330.0, 337.0, 344.0, 351.0, 358.0, 365.0, 372.0, 378.0, 385.0, 392.0, 399.0, 406.0, 413.0, 420.0, 427.0, 433.0, 440.0, 447.0, 454.0, 461.0, 468.0, 475.0, 482.0, 488.0, 495.0, 502.0, 509.0, 516.0, 523.0, 530.0, 537.0, 544.0, 550.0, 557.0, 564.0, 571.0, 578.0, 585.0, 592.0, 599.0, 605.0, 612.0, 619.0, 626.0, 633.0, 640.0, 647.0, 654.0, 660.0, 667.0, 674.0, 681.0, 688.0]');
var dataArray = [['X','Test']];
for(i = 0; i < bin.length; i++){
dataArray.push([culmativeData[i], bin[i]]);
}
var data = new google.visualization.arrayToDataTable(dataArray);
var options = {
title: 'Test',
curveType: 'function',
legend: { position: 'bottom' },
vAxis:{ title:'Probability (%)',
viewWindow:{ min:0, max: 100}
},
hAxis:{ title:'Cost',
format: 'currency'}
};
var chart = new google.charts.Line(document.getElementById('chart'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
$( document ).ready(function(){
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawGLine);
});
</script>
</head>
<body>
<div id="chart"></div>
</Body>
</HTML>
</code></pre>
| <p>i've seen questions in the past where jquery conflicts with google charts,<br>
specifically with the <code>setOnLoadCallback</code> method </p>
<p><a href="http://stackoverflow.com/q/35304392/5090771">google.setOnLoadCallback not able to get the document elements</a><br>
<a href="http://stackoverflow.com/q/35454099/5090771">GoogleChart not working in MVC</a> </p>
<p>to rule these out, suggest removing jquery </p>
<p>google's <code>callback</code> can be referenced directly in the <code>load</code> statement<br>
and you can depend on the <code>callback</code> to know when the page is ready<br>
so really no need for <code>$( document ).ready</code> anyway </p>
<p>recommend trying the following snippet... </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function drawGLine() {
var bin =JSON.parse('[0.65, 0.78, 1.16, 1.68, 2.0, 2.56, 3.03, 3.65, 4.51, 5.16, 6.0, 6.58, 7.47, 8.57, 9.58, 10.38, 11.28, 12.25, 13.03, 13.78, 14.8, 15.69, 16.49, 17.33, 18.06, 18.96, 20.49, 21.85, 22.94, 24.14, 25.31, 26.27, 27.22, 28.12, 29.87, 31.56, 32.58, 33.67, 35.14, 37.33, 38.41, 40.02, 41.87, 43.31, 44.98, 46.03, 47.84, 49.1, 50.81, 52.38, 54.17, 55.37, 57.3, 59.13, 61.14, 63.39, 64.43, 65.92, 67.53, 69.04, 70.82, 72.07, 73.17, 74.9, 76.63, 78.16, 79.2, 80.33, 81.09, 82.36, 83.34, 84.35, 85.27, 86.48, 87.58, 88.37, 89.25, 89.89, 90.68, 91.24, 92.2, 92.83, 93.87, 94.82, 95.38, 95.94, 96.58, 97.21, 97.45, 97.85, 98.25, 98.57, 98.81, 98.81, 99.28, 99.44, 99.44, 99.6, 99.84, 100.0, 100.0]');
var culmativeData =JSON.parse('[0.0, 7.0, 14.0, 21.0, 28.0, 34.0, 41.0, 48.0, 55.0, 62.0, 69.0, 76.0, 83.0, 89.0, 96.0, 103.0, 110.0, 117.0, 124.0, 131.0, 138.0, 144.0, 151.0, 158.0, 165.0, 172.0, 179.0, 186.0, 193.0, 200.0, 206.0, 213.0, 220.0, 227.0, 234.0, 241.0, 248.0, 255.0, 261.0, 268.0, 275.0, 282.0, 289.0, 296.0, 303.0, 310.0, 316.0, 323.0, 330.0, 337.0, 344.0, 351.0, 358.0, 365.0, 372.0, 378.0, 385.0, 392.0, 399.0, 406.0, 413.0, 420.0, 427.0, 433.0, 440.0, 447.0, 454.0, 461.0, 468.0, 475.0, 482.0, 488.0, 495.0, 502.0, 509.0, 516.0, 523.0, 530.0, 537.0, 544.0, 550.0, 557.0, 564.0, 571.0, 578.0, 585.0, 592.0, 599.0, 605.0, 612.0, 619.0, 626.0, 633.0, 640.0, 647.0, 654.0, 660.0, 667.0, 674.0, 681.0, 688.0]');
var dataArray = [['X','Test']];
for(i = 0; i < bin.length; i++){
dataArray.push([culmativeData[i], bin[i]]);
}
var data = new google.visualization.arrayToDataTable(dataArray);
var options = {
title: 'Test',
curveType: 'function',
legend: { position: 'bottom' },
vAxis:{ title:'Probability (%)',
viewWindow:{ min:0, max: 100}
},
hAxis:{ title:'Cost',
format: 'currency'}
};
var chart = new google.charts.Line(document.getElementById('chart'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
google.charts.load('current', {
callback: drawGLine,
packages: ['line']
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div></code></pre>
</div>
</div>
</p>
<p><strong>EDIT</strong> </p>
<p>in addition to the above, using a previous or <em>frozen</em> version might also help<br>
instead of using the <code>'current'</code> version </p>
<p>the latest <em>frozen</em> version, <em>at this time</em>, is <code>'45'</code><br>
you can go back to <code>'41'</code> </p>
<p><strong>in this specific case</strong>, version <code>'44'</code> corrects the problem, i.e. </p>
<pre><code>google.charts.load('44', {
callback: drawGLine,
packages: ['line']
});
</code></pre>
<p>recommend using <em>frozen</em> versions anyway,<br>
to ensure something doesn't break when the <code>'current'</code> <a href="https://developers.google.com/chart/interactive/docs/release_notes" rel="nofollow">release</a> is updated...</p>
|
add a loading animation until a specific javascript finish loading <p>I have an external JavaScript src which I want to add a loading animation until it's finish loading:</p>
<pre><code><script src="https://xxxx.domain.com/xxx.js" type="text/javascript"></script>
</code></pre>
<p>I'm currently using jQuery (window).load, but its waiting until all page is fully loaded, I want to wait only for that specific code:</p>
<pre><code><script>$(window).load(function(){$(".loadingif").hide();});</script>
</code></pre>
<p><strong>Update:</strong>
This is my code as you have suggested, it's is not working, what I'm doing wrong---</p>
<pre><code>some text.....
<span class="loading-gif"></span>
<script src="https://xxxx.domain.com/xxx.js" type="text/javascript"></script>
<script>hideLoading();</script>
some text.....
<script>function hideLoading(){$(".loading-gif").hide();}</script>
</code></pre>
| <p>Hopefully this works:</p>
<pre><code><script src="https://xxxx.domain.com/xxx.js" type="text/javascript"></script>
<script type="text/javascript">
hideLoadingThingy();
</script>
</code></pre>
<p>The second script should run after the first one finishes loading. This is because it is included after the first one, so the first one is loaded first.</p>
<p>Unless the methods in <code>xxx.js</code> are called asynchronously, your browser will only execute one task at a time. Read more about that <a href="https://en.wikipedia.org/wiki/Von_Neumann_architecture" rel="nofollow">here</a></p>
<p><strong>Update:</strong></p>
<p>Use this:</p>
<pre><code>some text 2.....
<span class="loading-gif"></span>
<script src="https://xxxx.domain.com/xxx.js" type="text/javascript"></script>
<script type="text/javascript">$(".loading-gif").hide();</script>
some text 2.....
</code></pre>
|
Custom message on completed order status email notification only for customer user role <p>I would like to improve this code from <a href="http://stackoverflow.com/questions/38975742/displaying-a-coupon-message-on-emails-for-completed-order-status-only/38976146#38976146"><strong>this answer</strong></a>, to display a message on completed order status emails only for customers, but not for other user roles (as subscribers, etc...).</p>
<p>Here is that code:</p>
<pre><code>add_action( 'woocommerce_email_before_order_table', 'completed_order_mail_message', 20 );
function completed_order_mail_message( $order ) {
if ( empty( $order->get_used_coupons() ) && $order->post_status == 'wc-completed' )
echo '<h2 id="h2thanks">Get 20% off</h2><p id="pthanks">Thank you for making this purchase! Come back and use the code "<strong>Back4More</strong>" to receive a 20% discount on your next purchase! Click here to continue shopping.</p>';
}
</code></pre>
<p>How can I achieve it?</p>
<p>Thanks</p>
| <p>To enable this custom message on email notification for complete order status and <strong>just for 'customer' user role</strong>, you have to get the user data related to the order, to get the user role. Then you will use it in your conditional.</p>
<p>Here is the code:</p>
<pre><code>add_action( 'woocommerce_email_before_order_table', 'completed_order_mail_message', 20 );
function completed_order_mail_message( $order ) {
// Getting order user data to get the user roles
$user_data = get_userdata($order->customer_user);
if ( empty( $order->get_used_coupons() ) && $order->post_status == 'wc-completed' && in_array('customer', $user_data->roles) )
echo '<h2 id="h2thanks">Get 20% off</h2><p id="pthanks">Thank you for making this purchase! Come back and use the code "<strong>Back4More</strong>" to receive a 20% discount on your next purchase! Click here to continue shopping.</p>';
}
</code></pre>
<p><em>This code goes in function.php file of your active child theme (or theme) or also in any plugin file.</em></p>
<p>This code is tested and fully functional.</p>
|
Android: get displayed text from textview in signle line only available <p>I have single line textview. I am setting string in it. Sometimes full string not possible to display. So I just want that string which is displayed. </p>
<pre><code>TextView valueTV = new TextView(context);
// valueTV.setEllipsize(TextUtils.TruncateAt.MIDDLE);
valueTV.setText(list.get(i).getTitle());
valueTV.setTag(i);
valueTV.setBackgroundColor(Color.parseColor(clr));
valueTV.setTextColor(Color.parseColor(txtclr));
if(dt1.equals(startdt))
{
valueTV.setTextColor(Color.parseColor(txtclr));
}else {
valueTV.setTextColor(Color.TRANSPARENT);
}
valueTV.setTypeface(type_thin);
valueTV.setId(list.get(i).getId());
valueTV.setMaxLines(1);
LinearLayout.LayoutParams ll=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ll.setMargins(0,1,0,0);
valueTV.setLayoutParams(ll);
valueTV.setOnClickListener(this);
lladd.addView(valueTV);
</code></pre>
<p>For Example</p>
<p>Full String : I am Android Developer
RIght now it displays:</p>
<p>I am And</p>
<p>So How can I get </p>
<p>I am And?</p>
<p>Thanks</p>
| <p>I thanks both @Andriy and Sujith for helping. Mix of both answers worked for me.</p>
<pre><code>ViewTreeObserver vto = valueTV.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int end = valueTV.getOffsetForPosition(valueTV.getWidth(), 0) + 1;
String displayed = valueTV.getText().toString().substring(0, end);
System.out.println("i---displayed--" + displayed);
}
});
</code></pre>
|
Eclipse Neon + JBossTools + Maven results on error: No compiler is provided in this environment <p>I'm having some problems when trying to install <code>wildfly.swarm</code> addon (<a href="https://github.com/forge/wildfly-swarm-addon" rel="nofollow">https://github.com/forge/wildfly-swarm-addon</a>) through <code>JBoss Tools</code> on <code>Eclipse</code></p>
<p><code>Maven</code> keep telling me that java compiler was not found despite I have JDK correctly set on Eclipse.</p>
<p>But ok, first things first:</p>
<p>I installed <code>Java 8</code> + <code>Maven v3.3.9</code> + <code>Eclipse Neon</code> + <code>JBoss Tools</code>. Everything went fine...
Then, I tried to install <code>wildfly.swarm</code> addon (<a href="https://github.com/forge/wildfly-swarm-addon" rel="nofollow">https://github.com/forge/wildfly-swarm-addon</a>) through <code>JBoss Tools</code>.</p>
<p><code>Forged Console</code> prompted me the following error:</p>
<p><a href="http://i.stack.imgur.com/8WeQt.png" rel="nofollow"><img src="http://i.stack.imgur.com/8WeQt.png" alt="enter image description here"></a></p>
<p>Trying to solve this problem, I checked if JDK path is correct on Eclipse. It is:</p>
<p><a href="http://i.stack.imgur.com/JAGTB.png" rel="nofollow"><img src="http://i.stack.imgur.com/JAGTB.png" alt="enter image description here"></a>
I've also checked if system variables for Maven and Java home are correct. Also, everything seems fine:</p>
<p><a href="http://i.stack.imgur.com/DOOer.png" rel="nofollow"><img src="http://i.stack.imgur.com/DOOer.png" alt="enter image description here"></a></p>
<p>At last, I went to <code>Windows > Preferences > Maven > Installations</code> on <code>Eclipse</code>
and added a new entry that point's to current Maven directory:</p>
<p><a href="http://i.stack.imgur.com/ZjH8p.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZjH8p.png" alt="enter image description here"></a></p>
<p>I've been looking some solutions on Stackoverflow and, between some sugestions, someone told to add tools.jar on <code>JRE Definition</code>. So, I did it, then restarted Eclipse, tried again to install <code>wildfly-swarm</code> through <code>Forge Console</code> but again... same error.</p>
<p><a href="http://i.stack.imgur.com/VqaXg.png" rel="nofollow"><img src="http://i.stack.imgur.com/VqaXg.png" alt="enter image description here"></a></p>
<p>Did someone faced this problem as well?</p>
<p>Plus: I also tried to build Widlfly Swarm's example through <code>mv package</code> command and everything went fine:</p>
<p><a href="https://i.stack.imgur.com/LKUdP.png" rel="nofollow"><img src="https://i.stack.imgur.com/LKUdP.png" alt="enter image description here"></a></p>
| <p>I'm facing the same problem. I can run mvn install on command line, but not in eclipse. You can temporarily fix this problem by adding this in pom.xml</p>
<pre><code> <plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<fork>true</fork>
<executable>C:\Program Files\Java\jdk1.8.0_101\bin\javac.exe</executable>
</configuration>
</plugin>
</code></pre>
|
Modeless Dialog in App::InitInstance() <p>My application needs to create some expensive stuff in <code>InitInstance()</code>. I want to inform the user about the progress so i decided to create a modeless dialog in the <code>InitInstance()</code> method. </p>
<p>My problem is, the dialog is not drawn. It updates just after </p>
<pre><code>CStartStopDlg dlg(_T("Start"));
dlg.Create(IDD_START_STOP_DLG);
dlg.ShowWindow(SW_SHOW);
// expensive stuff
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
</code></pre>
<p>Even when i put a sleep after this lines it updates the dialog. The problem is, the MainFrame uses my created resources, so i can't rearrange this lines.</p>
<p>How to solve this issue?</p>
<hr>
<p>EDIT:
The expensive stuff is connection to cameras, connection to io hardware, connection to databases and creating worker threads. The application object owns all this stuff and the mainframe and its views etc use this. As this stuff is not document related its in the application.</p>
<p>Depending on the ethernet load, it takes different time to connect. </p>
<p>The modal dialog does not need to be responsive. I just want something like the start dialog of adobe reader.</p>
<p>The hint with <code>UpdateWindow()</code> was the right direction and i added a call to this function as i updated the status. This solved my issue.</p>
| <p>It sounds like your âexpensive stuffâ is compute bound and not allowing the update of any UI thread(s). These types of problems are typically resolved by utilizing a separate thread to provide the progress feedback. You may want to have a look at <a href="http://www.codeproject.com/Articles/552/Using-Worker-Threads" rel="nofollow">Using Worker Threads</a> for some background on using threads to resolve this type of problem.</p>
|
Error 2762 when executing installer (WixCloseApplications) - worked with WiX 3.10.0.2103 <p>I have a problem with my installer that uses WiX.</p>
<p>I updated to WiX 3.10.3.3007 some time before and if I try to build an installer with VS 2015. I now get strange errors during the installation. The build itself works and doesn't show any errors. </p>
<p>The old installer, that was build with WiX 3.10.0.2103, still works as expected. I used the same sourcecode both times.</p>
<p>The installation log says this:</p>
<pre><code>Action ended 12:19:13: InstallValidate. Return value 1.
MSI (s) (58:F0) [12:19:13:127]: Doing action: RemoveExistingProducts
MSI (s) (58:F0) [12:19:13:127]: Note: 1: 2205 2: 3: ActionText
Action start 12:19:13: RemoveExistingProducts.
MSI (s) (58:F0) [12:19:13:128]: Skipping RemoveExistingProducts action: current configuration is maintenance mode or an uninstall
Action ended 12:19:13: RemoveExistingProducts. Return value 0.
MSI (s) (58:F0) [12:19:13:129]: Doing action: WixCloseApplications
MSI (s) (58:F0) [12:19:13:129]: Note: 1: 2205 2: 3: ActionText
Action start 12:19:13: WixCloseApplications.
MSI (s) (58:EC) [12:19:13:131]: Invoking remote custom action. DLL: C:\Windows\Installer\MSI9A67.tmp, Entrypoint: WixCloseApplications
MSI (s) (58!B0) [12:19:13:137]: PROPERTY CHANGE: Adding WixCloseApplicationsDeferred property. Its value is 'DisplayQ-Daily.exe3350002'.
MSI (s) (58!B0) [12:19:13:138]: Doing action: WixCloseApplicationsDeferred
MSI (s) (58!B0) [12:19:13:138]: Note: 1: 2205 2: 3: ActionText
Action start 12:19:13: WixCloseApplicationsDeferred.
MSI (s) (58!B0) [12:19:13:139]: Note: 1: 2762
MSI (s) (58!B0) [12:19:13:139]: Note: 1: 2205 2: 3: Error
MSI (s) (58!B0) [12:19:13:139]: Note: 1: 2228 2: 3: Error 4: SELECT `Message` FROM `Error` WHERE `Error` = 2762
DEBUG: Error 2762: Unable to schedule operation. The action must be scheduled between InstallInitialize and InstallFinalize.
MSI (c) (60:68) [12:19:13:146]: Font created. Charset: Req=0, Ret=0, Font: Req=MS Shell Dlg, Ret=MS Shell Dlg
The installer has encountered an unexpected error installing this package. This may indicate a problem with this package. The error code is 2762. The arguments are: , ,
MSI (s) (58!B0) [12:19:15:071]: Note: 1: 2205 2: 3: Error
MSI (s) (58!B0) [12:19:15:071]: Note: 1: 2228 2: 3: Error 4: SELECT `Message` FROM `Error` WHERE `Error` = 1709
MSI (s) (58!B0) [12:19:15:071]: Product: DisplayQDaily -- The installer has encountered an unexpected error installing this package. This may indicate a problem with this package. The error code is 2762. The arguments are: , ,
Action ended 12:19:15: WixCloseApplicationsDeferred. Return value 3.
WixCloseApplications: Error 0x80070643: Failed MsiDoAction on deferred action
WixCloseApplications: Error 0x80070643: failed to schedule WixCloseApplicationsDeferred action
CustomAction WixCloseApplications returned actual error code 1603 (note this may not be 100% accurate if translation happened inside sandbox)
Action ended 12:19:15: WixCloseApplications. Return value 3.
</code></pre>
<p>I don't have defined the <code>WixCloseApplications</code> or <code>WixCloseApplicationsDeferred</code>.</p>
<p>Part of my <code>Product.wxs</code>:</p>
<pre><code><Product Id="*" Name="DDQD" Language="1033" Version="!(bind.fileVersion.Exe)" Manufacturer="HipHipHura" UpgradeCode="931619FF-BB02-475F-8853-D0623F3FF0CB">
<Package InstallerVersion="405" Compressed="yes" InstallScope="perMachine" />
<MajorUpgrade DowngradeErrorMessage="A newer version of [ProductName] is already installed." />
<MediaTemplate />
<Feature Id="ProductFeature" Title="Installer" Level="1">
<ComponentGroupRef Id="ProductComponents" />
<ComponentGroupRef Id="AutoGeneratedComponents"/>
<ComponentRef Id="UninstallShortcutComponent"/>
<ComponentRef Id="CreateAppDataFolder" />
<ComponentRef Id="Permission.AppDataFolder" />
</Feature>
<PropertyRef Id="WIX_IS_NETFRAMEWORK_452_OR_LATER_INSTALLED"/>
<Condition Message=".NetFramework nicht installiert">
<![CDATA[Installed OR WIX_IS_NETFRAMEWORK_452_OR_LATER_INSTALLED]]>
</Condition>
<Feature Id="VCRedist" Title="Visual C++ 13.0 Runtime" AllowAdvertise="no" Display="hidden" Level="1">
<MergeRef Id="VCRedist"/>
</Feature>
<Component Id="CreateAppDataFolder" Directory="AppDataFolder" Guid="{78EDDF6C-110E-4020-97B8-5E55E3FFFA48}" KeyPath="yes">
<CreateFolder />
</Component>
<Binary Id="CustomAction.CA.dll" SourceFile="..\CustomAction\bin\$(var.Configuration)\CustomAction.CA.dll" />
<CustomAction Id="CloseApp" Return="check" Execute="immediate" BinaryKey="CustomAction.CA.dll" DllEntry="CloseApplicationAction" />
<CustomAction Id="LaunchApp" Directory="INSTALLFOLDER" ExeCommand="[SystemFolder]cmd.exe /C start myapp.exe --fromInstaller" Return="asyncNoWait" />
<InstallExecuteSequence>
<Custom Action="CloseApp" Before="LaunchConditions"/>
<Custom Action="LaunchApp" OnExit="success">NOT Installed</Custom>
</InstallExecuteSequence>
<!--<util:CloseApplication Id="CloseApp" Target="myapp.exe" RebootPrompt="no" />/-->
</Product>
</code></pre>
<p>It doesn't work whether or not I have the line <code><util:CloseApplication Id="CloseApp" Target="myapp.exe" RebootPrompt="no" /></code> active.</p>
<p>I also tried to change the Ids and some other things... But had no luck. I tried to build the setup on different machines, but it didn't work also. And I tried it on a fresh Virtual Machine, where it worked...</p>
<p>Any idea why the installation fails on some machines and how I can fix this?</p>
| <p>The code with:</p>
<p>util:CloseApplication Id="CloseApp" Target="myapp.exe" RebootPrompt ="no"</p>
<p>is generally the right way to do it, depending on the options you want to use. That's the issue that needs analyzing, but it appears that you went ahead and tried to create your own custom action to call, and that's where you get the 2762 error from, which is as the log and Brian describe. All you need do is declare the element and let WiX do the rest. If that correct use of the element doesn't work (and what does that mean exactly?) then that's what needs debugging. </p>
<p>That failing custom action <em>is</em> associated with CloseApp. Internally, the custom action will try to close down the target app, but also will schedule a deferred custom action to make sure that app goes away. Because you're not using it in the documented way you're getting undefined results. </p>
<p>Also note that the log has a line "MSI (s) (58:F0) [12:19:13:128]: Skipping RemoveExistingProducts action: current configuration is maintenance mode or an uninstall". In other words you are NOT doing a fresh install of your MSI. The MSI product (as defined by its ProductCode) is already on the system. When you try to install the same MSI twice it does not install it again - it goes into maintenance mode for the currently installed product, so none of the changes you make to your MSI are relevant because it's always doing maintenance repair on the one that is already installed, complete with its erroneous custom action. You must uninstall that before trying your modified MSI. </p>
|
Populate jQuery array with contents of CSV using PHP <p>I'd like to populate my <code>data</code> array with the contents of a CSV file using PHP.</p>
<p>My current code:</p>
<pre><code><script src="http://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
<?php
$file = fopen('food.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
print_r($line);
}
fclose($file);
?>
<script type="text/javascript">
var data = <?php echo json_encode($line); ?>;
document.write(data);
</script>
</code></pre>
<p>However, when I run this, I get the following output:</p>
<pre><code>Array
(
[0] => McDonalds
[1] => Fast Food
[2] => London
)
Array
(
[0] => Marios
[1] => Italian
[2] => Manchester
)
<script type="text/javascript">
var data = false;
document.write(data);
</script>
</code></pre>
<p>I'm guessing the <code>$line</code> variable is my issue here.</p>
<hr>
<p>My <code>food.csv</code> file: </p>
<pre><code>McDonalds,Fast Food,London
Marios,Italian,Manchester
</code></pre>
<p>The plan is to incorporate the <code>data</code> array into something like the demo below:</p>
<p><strong><a href="http://jsfiddle.net/1nj2wofp/" rel="nofollow">JSFiddle Demo</a></strong></p>
| <p>each time you print a line you override the previous one. Also you're using jsonencode with a nonarray I think thats why it gives you false, try this:</p>
<pre><code>$file = fopen('food.csv', 'r');
$allfile = [];
while (($line = fgetcsv($file)) !== FALSE) {
print_r($line);
$allfile[] = $line;
}
fclose($file);
?>
<script type="text/javascript">
var data = <?php echo json_encode($allfile); ?>;
document.write(data);
</script>
</code></pre>
|
Can redux be seen as a pub/sub or observer pattern? <p>I just try to get my head around react.js, that being said, I just finished a few tutorials on the web. I am completely new to redux, wich is part of some videotutorials I watched. The more I dive into it, the less it makes sense to me in terms of redux replacing the initial idea of react.js. In react a component has its own state which can be passed down via props, to keep the worflow from top to bottom. With redux we now try to make the hole application state global and we have to define actions to manipulate that (global) state so what are these actions other than a "normal" javascript pub/sub or observer pattern ? Or maybe I am getting it wrong ? - Clarification would be highly appreceated.</p>
| <p>Redux is not supposed to "replace the initial idea of react.js", think of it more like a library to managed shared state between components and to coordinate state mutations.
Redux does use a pub/sub pattern indeed, see the store methods here:
<a href="http://redux.js.org/docs/api/Store.html#store-methods" rel="nofollow">http://redux.js.org/docs/api/Store.html#store-methods</a>
You'll find a <code>subscribe</code> method that is used by components to subscribe to changes in the state tree. Normally you don't use store.subscribe directly, as the Redux-React bindings (Redux <code>connect</code> basically) do that for you. You can check out the actual implementation here, it's not that complicated to follow (in fact to me that's the main benefit of Redux over other Flux implementations): <a href="https://github.com/reactjs/react-redux/blob/master/src/components/connect.js#L199" rel="nofollow">https://github.com/reactjs/react-redux/blob/master/src/components/connect.js#L199</a></p>
<p>That code, apart from subscribing to the changes emitted by the store, it also perform some optimisations, such as passing new props to the component (and hence triggering a re-render) only if it's really needed.</p>
<p>Consider also that it's perfectly fine to keep using the components internal state together with Redux. You can use the internal state to store state you don't need/want to share with other components.</p>
<p>You see the need of something like Redux when you have a more complicated application, with top-level components that need to talk to each other (actions) and somehow share some state.</p>
<p>Actions in Redux are by default just POJO (plain old javascript objects), you can think of them as "events" that you often dispatch in response to user-triggered actions (e.g. user clicked on a button), but you're not limited to that, you can dispatch an action from wherever you want). The Redux store listens for these actions and call the reducers (pure functions) passing the action object you dispatched. Reducers see all the actions and if needed they can return a new, updated state for the slice of state they manage. In this sense, a reducer is a function that processes the actions and updates the state as needed.
In turn, when a reducer updates the state (by returning a new copy of the state), connected components (subscribed to the changes in the state) will be passed new props and will re-render to reflect the changes.</p>
<p>Sometimes, dispatching just plain js objects is not enough and you need more control. That becomes clear when you need to perform more complicated logic, let's say you need to update a counter in the state based on the response from an AJAX call.
With redux-thunk you can dispatch functions (as opposed to just plain objects). By dispatching a function, you're effectively implementing the inversion of control pattern in a very simple way. You action becomes a "recipe" (contained in the function) and not just a simple statement (with a POJO action).</p>
<p>Why just POJOs supported "out of the box", for actions, why isn't there a base Action class or something? Mainly because there's no need for that. A simple object (considered as a bag for values basically) with a <code>type</code> property is all you really need, it's basically the simplest possible interface. You can consider this to be programming against an interface (the action) instead of an implementation.</p>
<p>Why a global state is better, instead of each component managing its own state? Mainly because managing the state is actually the hardest part of a non-trivial js app. By using Redux, you extract all that logic from the UI layer, making it easier to test. In fact, you should ideally be able test all the real "business logic" of a Redux app without even rendering a single component.</p>
<p>Components become "dumber" and "purer" as they just render what they are told to do. "Purer" here means that because they don't hold any state, what you see rendered just depends on the inputs (read "props") at any given point in time, and not by any history, hence "stateless".</p>
<p>Having the state as a single, json serialisable object also makes it easy to debug, to snapshot it and send/restore from a server or local storage.</p>
|
Display data from SQLiteDatabase in a listView <p>I can currently display my data from the databas in a normal TextView. But I now want to display the rows in the database in a listview, I've tried to do this with a cursor I can't seem to figure it out.</p>
<pre><code>public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "ekonomi.db";
public static final String TABLE_UTGIFTER = "utgifter";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TITEL = "_titel";
public static final String COLUMN_KATEGORI = "_kategori";
public static final String COLUMN_PRIS = "_pris";
public static final String COLUMN_DATUM = "_datum";
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_UTGIFTER + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_TITEL + " TEXT, " +
COLUMN_KATEGORI + " TEXT, " +
COLUMN_PRIS + " INTEGER, " +
COLUMN_DATUM + " TEXT" +
");";
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS");
onCreate(db);
}
public void addUtgifter(Utgift utgift){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_TITEL, utgift.get_titel());
values.put(COLUMN_KATEGORI, utgift.get_kategori());
values.put(COLUMN_PRIS, utgift.get_pris());
values.put(COLUMN_DATUM, utgift.get_datum());
db.insert(TABLE_UTGIFTER, null, values);
db.close();
}
public String databaseToString() {
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_UTGIFTER + " WHERE 1";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("_titel")) != null) {
dbString += c.getString(c.getColumnIndex("_titel"));
dbString += ", ";
// dbString += "\n";
}if(c.getString(c.getColumnIndex("_kategori"))!=null){
dbString += c.getString(c.getColumnIndex("_kategori"));
dbString += ", ";
}
if(c.getString(c.getColumnIndex("_pris"))!=null){
dbString += c.getString(c.getColumnIndex("_pris"));
dbString += ", ";
}
if(c.getString(c.getColumnIndex("_datum"))!=null){
dbString += c.getString(c.getColumnIndex("_datum"));
dbString += "\n";
}
c.moveToNext();
}
db.close();
return dbString;
}
}
public class VisaUtgiftFragment extends Fragment {
private MainActivity ui;
private TextView tvDatabase;
private MyDBHandler dbHandler;
private ListView lvUtgift;
public VisaUtgiftFragment() {
// Required empty public constructor
}
public void setActivity(MainActivity ui){
this.ui = ui;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_visa_utgift, container, false);
tvDatabase = (TextView)view.findViewById(R.id.tvDatabaseTest);
dbHandler = new MyDBHandler(getActivity(), null, null, 1);
tvDatabase.setText(dbHandler.databaseToString());
lvUtgift = (ListView)view.findViewById(R.id.lvUtgift);
lvUtgift.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, [the rows in the database]));
lvUtgift.setOnItemClickListener(new ListViewClicked());
return view;
}
private class ListViewClicked implements android.widget.AdapterView.OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
}
</code></pre>
| <p>You can use something like the <a href="https://developer.android.com/guide/topics/ui/layout/listview.html" rel="nofollow">sample code in this guide here</a>.</p>
<p>The example uses a <code>CursorLoader</code> which may be used with a <code>ContentProvider</code> ideally, but you can use just the <code>SimpleCursorAdapter</code> passing in the cursor from your query without the <code>CursorLoader</code>. It will show the content of the cursor in a ListView all on its own.</p>
<p>Your code will look like:</p>
<pre><code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_visa_utgift, container, false);
tvDatabase = (TextView)view.findViewById(R.id.tvDatabaseTest);
dbHandler = new MyDBHandler(getActivity(), null, null, 1);
tvDatabase.setText(dbHandler.databaseToString());
lvUtgift = (ListView)view.findViewById(R.id.lvUtgift);
lvUtgift.setAdapter(new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_1,
dbHandler().getAllItemsInCursor(),
new String[]{"_titel"},
new int[]{android.R.id.text1},
0));
lvUtgift.setOnItemClickListener(new ListViewClicked());
return view;
}
</code></pre>
<p>And you will additionally have to add the below method in your <code>MyDBHandler</code> class:</p>
<pre><code>public Cursor getAllItemsInCursor() {
return getWritableDatabase()
.rawQuery("SELECT * FROM " + TABLE_UTGIFTER, null);
}
</code></pre>
<p><code>android.R.layout.simple_list_item_1</code> is the resource ID of a predefined layout that has just one <code>TextView</code> with resource ID <code>android.R.id.text1</code>.</p>
<p>You can replace <code>android.R.layout.simple_list_item_1</code> with a layout of your own that probably has more <code>TextView</code> to be able to show all the details in your table. Your own layout may look like:</p>
<p>utgifter_item.xml in <code>res/layout</code> directory:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/item_id"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/item_category"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/item_price"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/item_datum"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</code></pre>
<p>And call to the constructor of <code>SimpleCursorAdapter</code> will be changed to:</p>
<pre><code>lvUtgift.setAdapter(new SimpleCursorAdapter(getActivity(),
R.layout.utgifter_item,
dbHandler().getAllItemsInCursor(),
new String[]{"_id", "_titel", "_kategori", "_pris", "_datum"},
new int[]{R.id.item_id, R.id.item_title, R.id.item_category, R.id.item_price, R.id.item_datum},
0));
</code></pre>
|
Is it possible to submit multiple records at once in Access? <p>I need to figure out a way for a user to input around 150 data points collected easily and quickly. I have no experience with Access so I don't know if it is possible to do this, but I need a way for a user to input a table like this:</p>
<p><a href="https://i.stack.imgur.com/3WAQs.png" rel="nofollow">Table</a></p>
<p>Preferably all in one form without going record by record.</p>
| <p>You layout is not really different then say a typical invoice, or say a purchase order in which âmanyâ rows of data are attached to a given order, event or whatever.</p>
<p>So if you were entering data points for a given day, or test, then you would create a main table that outlines the details of the test (date, who did the test etc.). You then would build a table with the data points, and relate that table to the âtestâ event.</p>
<p>You then build a form, and drop in a sub form that displays the many rows in a table like format (you could even use a datasheet). The end result is a form in which they can enter data and simply hit tab to jump to the next column â when they are on the last column, the hitting tab would jump to the next row thus facilitation data entry with relative ease.</p>
<p>Here is a screen shot of âshiftâ work for a given employee, but the concept is the same for an invoice, an order, timesheet hours, or in your case a set of data points. The top part is "one" record that is the employee, and then the "many" rows are a sub form (a continues sub for in this example).</p>
<p><a href="https://i.stack.imgur.com/Huxbp.png" rel="nofollow"><img src="https://i.stack.imgur.com/Huxbp.png" alt="enter image description here"></a></p>
|
SQL BigQuery: fatal error when using PHP string variable in query <p>I am puzzled by this error:</p>
<blockquote>
<p>"invalidQuery", "message": "Field 'QLD' not found in table 'medicare.medicareTable'.", "locationType": "other", "location": "query" } ], "code": 400</p>
</blockquote>
<p>because the field QLD is most definitely in that table.</p>
<p>I am trying to get a response from BigQuery using the following query in a php file:</p>
<pre><code>$qld = 'QLD';
$request = new Google_Service_Bigquery_QueryRequest();
$request->setQuery("SELECT Gender, SUM(Cost) AS Cost
FROM [medicare.medicareTable]
WHERE State = $qld
GROUP BY Gender");
$response = $bigquery->jobs->query($projectId, $request);
</code></pre>
<p>I have played around with the query and found that if I replace $qld with a string, e.g.:</p>
<pre><code>WHERE State = 'QLD'
</code></pre>
<p>Then it works.
I am at a loss. What is going wrong here?</p>
<p>Here's the full error, in case it's needed:</p>
<blockquote>
<p>Fatal error: Uncaught exception 'Google_Service_Exception' with message '{ "error": { "errors": [ { "domain": "global", "reason": "invalidQuery", "message": "Field 'QLD' not found in table 'medicare.medicareTable'.", "locationType": "other", "location": "query" } ], "code": 400, "message": "Field 'QLD' not found in table 'medicare.medicareTable'." } } ' in /base/data/home/apps/s~s3449107-assign2/1.396261573977805792/php/google-api-php-client/src/Google/Http/REST.php:118 Stack trace: #0 /base/data/home/apps/s~s3449107-assign2/1.396261573977805792/php/google-api-php-client/src/Google/Http/REST.php(94): Google_Http_REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #1 [internal function]: Google_Http_REST::doExecute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #2 /base/data/home/apps/s~s3449107-assign2/1.396261573977805792/php/google-api-php-client/src/Google/Task/Runner.php(181): call_user_ in /base/data/home/apps/s~s3449107-assign2/1.396261573977805792/php/google-api-php-client/src/Google/Http/REST.php on line 118</p>
</blockquote>
| <p>Not</p>
<pre><code>WHERE State = $qld
</code></pre>
<p>But</p>
<pre><code>WHERE State = '$qld'
</code></pre>
<p>Text is text ;)</p>
|
Anchor link on another page after page load <p>Right now, I am linking to an anchor link that is on another page. When I get to the page, it takes me to where the anchor link is before the page fully loads. The problem is that after the page fully loads, the anchor link is at another position on the page than where it initially was. </p>
<p>Do any of you know how to fix this with Javascript? Thanks! </p>
| <p>This sounds like you have race condition. You have to wait for the page to render to then scroll using a method such as</p>
<p><a href="http://stackoverflow.com/questions/17733076/smooth-scroll-anchor-links-without-jquery">Smooth scroll anchor links WITHOUT jQuery</a></p>
<p>But it depends on what the page is waiting for. Does it just take a while for the html to render? Is it waiting for data from the API?</p>
|
Cypher query that will return only 1 relation of each type between two nodes <p>How can I craft a query that will return only one relation of a certain type between two nodes?</p>
<p>For example:</p>
<pre><code>MATCH (a)-[r:InteractsWith*..5]->(b) RETURN a,r,b
</code></pre>
<p>Because (a) may have interacted with (b) many times, the result will contain many relations between the two. However, the relations are not identical. They have different properties because they occurred at different points in time. </p>
<p>But what if you're only interested in the fact that they have interacted <strong>at least once</strong>?</p>
<p>Instead of the <a href="https://i.stack.imgur.com/V5oNk.png" rel="nofollow">result as it appears currently</a> I'd like to receive a result that has either:</p>
<ul>
<li>Only one random relation from the set of relations between (a) and (b)</li>
<li>Only those relations that fit to some criteria (e.g. "newest" or one of each type, ...)</li>
</ul>
<p>One approach I have thought of is creating new relations of the type "hasEverInteractedWith". But there should be another way, right?</p>
| <p>Use <code>shortestPath()</code> to get the quickest single result.</p>
<pre><code>MATCH (a)-[:InteractsWith*..5]->(b)
WITH DISTINCT a, b
MATCH p = shortestPath((a)-[:InteractsWith*..5]->(b))
RETURN a, b, RELATIONSHIPS(p) AS r
</code></pre>
<p>If you want to get a specific one, you'll have to get all of the <code>r</code> and then filter them down, which will be slower (but provide more context).</p>
<pre><code>MATCH (a)-[r:InteractsWith*..5]->(b)
WITH a, b, COLLECT(r) AS rs
RETURN a, b, REDUCE(s = HEAD(rs), r IN TAIL(rs)|CASE WHEN s.date > r.date THEN s ELSE r END)
</code></pre>
|
Twisted threading and Thread Pool Difference <p>What is the difference between using</p>
<pre><code>from twisted.internet import reactor, threads
</code></pre>
<p>and just using</p>
<pre><code>import thread
</code></pre>
<p>using a thread pool?</p>
<p>What is the twisted thing actually doing? Also, is it safe to use twisted threads?</p>
| <blockquote>
<p>What is the difference</p>
</blockquote>
<p>With <code>twisted.internet.threads</code>, Twisted will manage the thread and a thread pool for you. This puts less of a burden on devs and allows devs to focus more on the business logic instead of dealing with the idiosyncrasies of threaded code. If you <code>import thread</code> yourself, then you have to manage threads, get the results from threads, ensure results are synchronized, make sure too many threads don't start up at once, fire a callback once the threads are complete, etc.</p>
<blockquote>
<p>What is the twisted thing actually doing?</p>
</blockquote>
<p>It depends on what "thing" you're talking about. Can you be more specific? Twisted has various thread functions you can leverage and each may function slightly different from each other.</p>
<blockquote>
<p>And is it safe to use twisted threads.</p>
</blockquote>
<p>It's absolutely safe! I'd say it's more safe than managing threads yourself. Take a look at all the functionality that Twisted's thread provides, then think about if you had to write this code yourself. If you've ever worked with threads, you'll know what it starts off simple enough, but as your application grows and if you didn't make good decisions about threads, then your application can become very complicated and messy. In general, Twisted will handle the threads in a uniform way and in a way that devs would expect a well behaved threaded app to behave.</p>
<h1>References</h1>
<ul>
<li><a href="https://twistedmatrix.com/documents/current/core/howto/threading.html" rel="nofollow">https://twistedmatrix.com/documents/current/core/howto/threading.html</a></li>
</ul>
|
How to check if used paginate in laravel <p>I have a custom view and in some functions, I used <code>paginate</code> and other functions I don't use <code>paginate</code>. now how can I check if I used <code>paginate</code> or not ?</p>
<pre><code>@if($products->links())
{{$products->links()}}
@endif // not work
</code></pre>
<p>of course that I know I can use a variable as true false to will check it, But is there any native function to check it ?</p>
| <p>Try like this</p>
<pre><code>@if($products instanceof \Illuminate\Pagination\AbstractPaginator)
{{$products->links()}}
@endif
</code></pre>
<p>You need to check wheater the <code>$products</code> is instance of <code>Illuminate\Pagination\AbstractPaginator</code>. It can be an array or Laravel's <code>Collection</code> as well.</p>
|
Don't use serialize for the user role Symfony <p>I have a project and a Symfony3 Silex 2 API that is based on the database created with SF3.
The problem arises because of the ROLE field in the database, in effect symfony3 stores in the database the user roles via serialize, flint or using a string.</p>
<p>Why Symfony serialize and flint right?
How to solve the problem because Silex does not manage the roles serialize?</p>
<p>Role field BDD:
Silex:</p>
<pre><code>ROLE_MODO,ROLE_SUPER_ADMIN
</code></pre>
<p>SF:</p>
<pre><code>a:2:{i:0;s:9:"ROLE_MODO";i:1;s:16:"ROLE_SUPER_ADMIN";}
</code></pre>
<p>Thank you.</p>
| <p>Make sure in SF3 platform, map the <code>roles</code> field with <code>simple_array</code> DBAL type instead of <code>array</code> (i.e. <code>@ORM\Column(name="roles", type="simple_array")</code>).</p>
<p>The difference is that <code>array</code> type stores their values serialized and <code>simple_array</code> stores their values by using comma separated.</p>
|
c# obtaining property values from object <p>I am trying to use a method to create an object and return that object to main(). Once in main I want to be able to access the properties of that object such as print Holly.age. VS does not recognize the object Holly in main() to have any properties. Is anyone able to tell what I am doing wrong or let me know if it's not something possible in c#.</p>
<p>Thanks in advance to anyone who gives there time to help.</p>
<pre><code>class program
{
static void Main(string[] args)
{
object Holly = createobject(Holly, 21);
int hollyage = Holly.age; // This Line is the problem Holly.age is not recognized
// as anything
}
public static object createobject(string name, int i)
{
Cat Holly = new Cat(name, i);
return Holly;
}
public class Cat
{
public string name;
public int age;
public string Name
{
get { return this.name; }
set { this.name = value; }
}
public int Age
{
get { return this.age; }
set { this.age = value; }
}
public Cat(string name, int age)
{
this.name = name;
this.age = age;
}
}
</code></pre>
| <blockquote>
<p>VS does not recognize the object Holly in main() to have any properties</p>
</blockquote>
<p>This is because you have declared <code>Holly</code> to be <code>object</code> rather than <code>Cat</code>, and similarly your create routine returns <code>object</code> rather than <code>Cat</code>.</p>
<p>To be able to use any of the properties of <code>Cat</code> you need to cast <code>Holly</code> back to <code>Cat</code> or better still, return <code>Cat</code> from your create routine. Unless you intend to extend your create routine to do more, you don't really need it and can simply do:</p>
<pre><code>Cat Holly = new Cat("Holly", 21);
</code></pre>
<p>You also have both public fields and public properties in your <code>Cat</code> class. The fields should be made private, but that's not the cause of the problem.</p>
|
Clickable legend at Core Plot <p>I use Core Plot files to create my chart.
But CorePlot doesn't contain event "click on legend item".</p>
<p>How can I detect user's click on legend item ?</p>
<pre><code>class ViewController: NSViewController, CPTPlotDataSource, CPTPieChartDataSource {
@IBOutlet weak var graphView: CPTGraphHostingView!
override func viewDidLoad() {
super.viewDidLoad()
let graph = CPTXYGraph(frame: CGRect.zero)
var axes = graph.axisSet as! CPTXYAxisSet
var lineStyle = CPTMutableLineStyle()
lineStyle.lineWidth = 0
axes.xAxis?.axisLineStyle = lineStyle
axes.yAxis?.axisLineStyle = lineStyle
var pie = CPTPieChart()
pie.pieRadius = 100
pie.dataSource = self
pie.centerAnchor = CGPoint(x: 0.18, y: 0.75)
graph.add(pie)
var theLegend=CPTLegend(graph: graph)
var legendFill=CPTFill(color: CPTColor.gray())
theLegend.fill = legendFill
var legendLineStyle = CPTMutableLineStyle()
legendLineStyle.lineColor = CPTColor.white()
theLegend.borderLineStyle = legendLineStyle
theLegend.cornerRadius = 2.0
theLegend.frame = CGRect(x: 0, y: 0, width: 0.1, height: 50)
theLegend.numberOfColumns = 1
graph.legend = theLegend
graph.legendDisplacement = CGPoint(x: 0.5, y: 300)
self.graphView.hostedGraph = graph
}
</code></pre>
| <p>Core Plot legends can have a delegate that is called on mouse down, mouse up, and/or selected (mouse down followed by mouse up on the same item) events. See the <a href="http://core-plot.github.io/MacOS/protocol_c_p_t_legend_delegate-p.html" rel="nofollow">CPTLegendDelegate protocol</a> for details on the available methods. Unless you need some specific behavior not covered by the delegate, you don't need worry about the responder chain.</p>
|
Ajax.BeginForm JavaScript callback with parameter causes $(this) to refer to window instead of form <p>I am using the following code to create a form with JS callbacks:</p>
<pre><code>@using (Ajax.BeginForm("Example", "Example", null, new AjaxOptions
{
HttpMethod = "POST",
OnBegin = "ajaxFormBegin",
OnSuccess = "ajaxFormSuccess(data, status, xhr, 'exampleValue')"
}
</code></pre>
<p>I have found that if I don't pass a parameter to the callback, as is the case with the OnBegin callback, then the JQuery $(this) variable refers to the calling form.</p>
<p>If I do pass a parameter, as is the case with the OnSuccess callback, $(this) refers to the window. I want it to refer to the form as in the first scenario.</p>
<pre><code>function ajaxFormBegin() {
$form = $(this); // Refers to calling form
}
function ajaxFormSuccess(data, status, xhr, callback_) {
$form = $(this); // Refers to window
}
</code></pre>
<p>Is this expected behavior or is my implementation wrong?</p>
| <p>Your assignment to <code>OnSuccess</code> is a function <strong>call</strong> in global context.</p>
<pre><code>@using (Ajax.BeginForm("Example", "Example", null, new AjaxOptions
{
HttpMethod = "POST",
OnBegin = "ajaxFormBegin",
OnSuccess = "ajaxFormSuccessWrapper"
}
<script>
function ajaxFormSuccessWrapper(data, status, xhr) {
var form = this;
ajaxFormSuccess(data, status, xhr, 'exampleValue');
}
</script>
</code></pre>
|
Jarsigner (MIME Content-Type is not application/timestamp-reply) <p>Some time ago I wrote a program to sign jars in our build process. Which worked for a couple of months without any problems.</p>
<p>Now the jarsigner outputs (without changing anything!):</p>
<pre><code>jarsigner: unable to sign jar:
java.io.IOException: MIME Content-Type is not application/timestamp-reply
</code></pre>
<p>and the jars are not signed anymore.</p>
<p>What is the problem and what do I need to do to get the jarsigner working again?</p>
<p>I'm using this timestamp server:<br>
<strong><a href="http://timestamp.comodoca.com" rel="nofollow">http://timestamp.comodoca.com</a> <br></strong></p>
<p>and this Java version:<br>
<strong>Java HotSpot(TM) 64-Bit Server VM "1.8.0_101" on Linux</strong></p>
<p>This is my exact command line (which worked for the last months!):<br>
<code>jarsigner -storetype pkcs12 -keystore certificate_file.p12 -storepass mypassword -tsa http://timestamp.comodoca.com myjarfile.jar myalias</code></p>
| <p>I am experiencing the same problem. I think something change in Comodo's timestamp service today. The response status for <a href="http://timestamp.comodoca.com" rel="nofollow">http://timestamp.comodoca.com</a> is currently
HTTP/1.1 302 Moved Temporarily
Content-Type: text/html</p>
<p>This causes a problem for jarsigner as it is expecting content-type to be application/timestamp-reply</p>
<p>You should contact Comodo support at <a href="https://support.comodo.com/index.php?/Knowledgebase/Article/View/68/0/time-stamping-server" rel="nofollow">https://support.comodo.com/index.php?/Knowledgebase/Article/View/68/0/time-stamping-server</a></p>
|
XDebug with PhpStorm: Debugging a CLI script, connection over reverse SSH tunnel <p>I've got the PhpStorm 10.0.3 and trying to debug a CLI script that runs on a remote server.</p>
<p>I've got reverse SSH tunnel set up from my local machine to the remote server.</p>
<p>Remote server xDebug is configured with the following:</p>
<pre><code># /etc/php5/apache2/conf.d/20-xdebug.ini
# /etc/php5/cli/conf.d/20-xdebug.ini
zend_extension=xdebug.so
xdebug.remote_enable=true
xdebug.idekey=PHPSTORM
xdebug.remote_host=127.0.0.1
xdebug.remote_port=9000
</code></pre>
<p>I try to start a script like this:</p>
<pre><code> php -dxdebug.remote_autostart=On /var/www/index.php
</code></pre>
<p>The PhpStorm debug tabs get's opened (sometimes it's gray), but it does not prompt me to fix file mappings, it does not open the debugged file and does not point to the breakpoint line. The remote server script execution gets blocked until I manually kill the debugging session. <a href="https://i.stack.imgur.com/1gU2A.png" rel="nofollow"><img src="https://i.stack.imgur.com/1gU2A.png" alt="enter image description here"></a></p>
<p>When I debug over Apache2 using GET parameter:</p>
<pre><code> ?XDEBUG_SESSION_START=1
</code></pre>
<p>The debugging works fine and I get prompted to fix the file mappings.</p>
<p>Any idea why is that?</p>
<p>I was studying below, but it does not solve my problem:
<a href="https://confluence.jetbrains.com/display/PhpStorm/Debugging+PHP+CLI+scripts+with+PhpStorm" rel="nofollow">https://confluence.jetbrains.com/display/PhpStorm/Debugging+PHP+CLI+scripts+with+PhpStorm</a>
(Question: How my script should now that debugging should start without remote_autostart setting set? In green hint they say it is optional.)</p>
<p>and
<a href="http://stackoverflow.com/questions/16518262/xdebug-how-to-debug-remote-console-application">XDebug: how to debug remote console application?</a>
(Re: Setting the remote_host in the XDEBUG_CONFIG variable to my local computer external IP [check the copied bash snippet] does not seem to be working. My local computer is not accessible via external IP, it's only accessible via reverse SSH tunnel)</p>
<pre><code> export XDEBUG_CONFIG="remote_host=$(echo $SSH_CLIENT | awk '{print $1}') idekey=PHPSTORM"
</code></pre>
| <p>There were actually 2 problems here.
As in the @LazyOne comment, there was a port collision with the PHP5-FPM service. In my case I've turned it off, as the client's server configuration does not use FPM anyway.</p>
<p>I also had to export PHP_IDE_CONFIG variable on the remote host:</p>
<pre><code> export PHP_IDE_CONFIG="serverName=serverNameInPHPStorm"
</code></pre>
<p>That host is a configured on the PHPStorm side (Settings / Preferences | Languages & Frameworks | PHP | Servers). I've also had to map the root project folder on the remote server path location, as they are different between my local/dev machine and the remote.</p>
|
Vertical Bootstrap nav (rotated -90°) <p>How to create a <a href="https://v4-alpha.getbootstrap.com/components/navs/" rel="nofollow">Bootstrap Nav</a> with vertically aligned items like so:</p>
<p><a href="https://i.stack.imgur.com/xCQ9c.png" rel="nofollow"><img src="https://i.stack.imgur.com/xCQ9c.png" alt="enter image description here"></a></p>
<p>I'm <strong>not</strong> trying to design a stacked layout with horizontally aligned items one below each other.</p>
<p>I tried to add <code>transform:rotate(-90deg);</code> to <code>.list-group-item</code>, however, it looks like rotational transformation is applied after elements are aligned on the page, and therefore I would have to position each element manually using JavaScript. I'm looking for a clean CSS-only solution, possibly without any "hackarounds".</p>
| <p>(edit) My 1st answer using <strong><code>writing-mode: vertical-lr</code></strong> and then <strong><code>transform: rotate(180deg);</code></strong> plus some CSS to make it work or as a starter (no, flex isn't needed here but I use it so much for navbars...)</p>
<p><strong><a href="http://codepen.io/PhilippeVay/pen/VKxyvg" rel="nofollow">Codepen</a></strong>: clearer than snippet below because I could use Autoprefixer (and also Normalize and LESS which is used by Bootstrap 3 but you can use Sass here - if you already use Bootstrap 4 alpha - syntax is identical for both here)</p>
<p>If you don't use Autoprefixer, then result is:</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>.nav-tabs {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-ms-flex-flow: column nowrap;
flex-flow: column nowrap;
-webkit-box-align: start;
-ms-flex-align: start;
align-items: flex-start;
}
.nav-tabs > li {
-webkit-writing-mode: vertical-lr;
-ms-writing-mode: tb-lr;
writing-mode: vertical-lr;
-webkit-transform: rotate(180deg);
transform: rotate(180deg);
-webkit-transform-origin: center center;
transform-origin: center center;
list-style-type: none;
}
.nav-tabs > li > a {
display: block;
padding: 0.6rem 1rem;
background-color: beige;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="nav nav-tabs">
<li role="presentation" class="active"><a href="#">Home</a></li>
<li role="presentation"><a href="#">Profile</a></li>
<li role="presentation"><a href="#">Messages</a></li>
</ul></code></pre>
</div>
</div>
</p>
<p>I didn't include existing CSS from Bootstrap for this component so you'll have to override a bunch of declarations but I at least used the same selectors like <code>*** > li > a</code> and copy-pasted HTML from documentation.</p>
<p>My reasoning is that rotating by +/- 90ddeg is never <em>safe</em>. Width becomes height, height becomes width and it's messy because content is so fluid. So I wrote text vertically with <a href="https://developer.mozilla.org/fr/docs/Web/CSS/writing-mode" rel="nofollow">writing-mode</a> and then had to rotate by half a turn text to mimick your design. Doing so doesn't change dimensions of each element so no bad surprise ;)</p>
|
Vim regex matching multiple results on the same line <p>I'm working on a project where I'm converting an implementation of a binary tree to an AVL tree, so I have a few files that contain lines like:</p>
<pre><code>Tree<int>* p = new Tree<int>(*t);
</code></pre>
<p>all over the place. The goal I have in mind is to use a vim regex to turn all instances of the string <code>Tree</code> into the string <code>AVLTree</code>, so the line above would become:</p>
<pre><code>AVLTree<int>* p = new AVLTree<int>(*t);
</code></pre>
<p>the regex I tried was <code>:%s/Tree/AVLTree/g</code>, but the result was:</p>
<pre><code>AVLTree<int>* p = new Tree<int>(*t);
</code></pre>
<p>I looks to me like when vim finds something to replace on a line it jumps to the next one, so is there a way to match multiple strings on the same line? I realize that this can be accomplished with multiple regex's, so my question is mostly academic.</p>
| <p>Credit on this one goes to Marth for pointing this out. My issue was with vim's <code>gdefault</code>. By default it's set to 'off', which means you need the /g tag to make your search global, which is what I wanted. I think mine was set to 'on', which means without the tag the search is global, but with the tag the search is not. I found this chart from <code>:help 'gdefault'</code> helpful:</p>
<pre><code> command 'gdefault' on 'gdefault' off
:s/// subst. all subst. one
:s///g subst. one subst. all
:s///gg subst. all subst. one
</code></pre>
|
fgets / fgetc not working <p>Okay, I've read a lot of posts about <code>fgetc</code> not working properly but the errors are involved in a bit more complex tasks than mine.
I'll write only the pertinent block of code. The next code prints EOF when I'm really sure that it shouldn't.</p>
<pre><code>FILE *fp= fopen("data/myfile.txt", "r"); //No errors opening the file
char c;
c= fgetc(fp);
printf("%c", c);
while ((c= fgetc(fp)) != EOF && c!= '\n'){ //
printf("%c", c);
}
</code></pre>
<p>It doesn't even starts the loop due to the premature EOF.</p>
<p>Nonetheless doing the same thing with fgets returns NULL.
EDIT: Added the code to show the behaviour with fgets:</p>
<pre><code>FILE *fp= fopen("data/myfile.txt", "r"); //No errors opening the file
char c[128];
fgets(c, 128 ,fp);
printf("c is null %s", (c == nulls)?"yes":"no");
</code></pre>
<p>Flushing the stdin doesn't change the results (I know that it has nothing to do with file pointers but just in case).</p>
<p>What could be the problem here? I'm a bit confused here.</p>
| <p>Use <code>int c</code> instead of <code>char c;</code>.<code>fgetc</code> returns integer. </p>
|
Cannot find function getMonth in object 33463 <p>I have created a script to send emails to a specific people with Birthday Reminder. This use to work till day before yesterday. I don't know why am I getting this error that Cannot find function getMonth, Can anyone tell where is the mistake</p>
<pre><code>function emailAlert() {
// Short circuit if email notice is set to "No". This causes an error and the script stops.
if (turnOnEmailNotice.toLowerCase() == "no")
{
Logger.log("The Email Notification is NOT turned ON. System will Exit.");
exit
}
//Get the total number of filled row in the sheet.
var currentRowAT = 2;
var currentCellValueAT = "start";
while (currentCellValueAT != ""){
if (currentCellValueAT = birthdaysSheet.getRange("G" + currentRowAT).getValue() != ""){
currentRowAT = currentRowAT +1;
}
}
var birthdaysSheetLastRow = currentRowAT - 1;
// Get today's Date (with Month, Date and Year)
var today = new Date();
var todayMth = today.getMonth()+1;
var todayDate = today.getDate();
var todayYear = today.getFullYear();
// Check sheet cell for match to alertDate, k is the current row number being checked. Starting at 2 as the row #1 is for the headers
for (k=2; k < birthdaysSheetLastRow + 1; k++)
{
var targetBday = new Date();
targetBday = birthdaysSheet.getRange("P" + k).getValue();
// If Birthday is not speicified, continue with the next row
if (targetBday == ""){continue};
var unadjTargetBday = new Date();
var unadjTargetBdayMth = targetBday.getMonth()+1;
var unadjTargetBdayDate = targetBday.getDate();
var unadjTargetBdayYear = targetBday.getFullYear();
var unadjTargetBday = targetBday;
targetBday.setDate(targetBday.getDate()-daysInAdvance); // Calculating how many days in advance you want to trigger the notification. This is set in Settings Tab.
var targetBdayMth = targetBday.getMonth()+1;
var targetBdayDate = targetBday.getDate();
if (targetBdayMth + " " + targetBdayDate == todayMth + " " + todayDate)
{
var targetBirthDateYearsOld = (today.getYear() - unadjTargetBday.getYear())-1900;
prepareAndSendEmail(k, targetBirthDateYearsOld);
}
}
}
</code></pre>
| <h1>Short answer</h1>
<p>Check that the cell value is a valid date for Google Sheet.</p>
<h1>Explanation</h1>
<p>From <a href="https://developers.google.com/apps-script/reference/spreadsheet/range#getvalue" rel="nofollow">https://developers.google.com/apps-script/reference/spreadsheet/range#getvalue</a> (emphasis mine)</p>
<blockquote>
<h3>getValue()</h3>
<p>Returns the value of the top-left cell in the range. The value may be
of type <code>Number</code>, <code>Boolean</code>, <code>Date</code>, or <code>String</code> <strong>depending on the value of the
cell</strong>. Empty cells will return an empty string.</p>
</blockquote>
<p>To avoid this kind of problems, you may include some sort of data validation. You could use build-in features like conditional formatting, data validation, or something like a on edit script together with try / catch or a redundant validation in your emailAlert script.</p>
|
Long Term Support Branches in git? <p>I'm working for an enterprise company, developing software for macOS.</p>
<p>I'm not sure how to solve my problem by supporting multiple versions of a software, in one single git-repo.</p>
<p>The product is an Xcode project for macOS, code is managed by git. </p>
<p>At current there is one release out there:
version 1.0</p>
<p>Every version is valid until next major version will be released. So v1.0 is valid and maintained until v2.0. But v1.0 should now be a "long term supported branch" - means if v2.0 is out there, v1.0 is still maintained. </p>
<p>How can I solve my problem maintaining v1.0 and v2.0 and maybe v3.0 in future?
How can I fix a bug in v1.0 and in the same time in v2.0? </p>
<p>Any ideas? </p>
| <p>You can use <a href="https://git-scm.com/book/en/v1/Git-Branching" rel="nofollow">branches</a> with <a href="https://git-scm.com/book/en/v1/Git-Basics-Tagging" rel="nofollow">tags</a> to handle multiple "trees" in a single repo. Take a look at <a href="https://github.com/rails/rails" rel="nofollow">Ruby on Rails repository</a> as the example. They have <code>x-y-stable</code> branches for different versions.</p>
<p>To port commits from one branch to another, you can use <a href="https://git-scm.com/docs/git-cherry-pick" rel="nofollow">cherry pick feature</a>.</p>
|
JBoss Deployment Error - Failed Services <p>Trying to debug my application in Wildfly 8.x server, I confront that error: </p>
<pre><code>16:03:18,740 INFO [org.jboss.modules] (main) JBoss Modules version 1.3.3.Final
16:03:19,098 INFO [org.jboss.msc] (main) JBoss MSC version 1.2.2.Final
16:03:19,170 INFO [org.jboss.as] (MSC service thread 1-7) JBAS015899: WildFly 8.2.1.Final "Tweek" starting
16:03:20,560 INFO [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) JBAS015014: Re-attempting failed deployment paco.war
16:03:20,633 INFO [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) JBAS015003: Found paco.war in deployment directory. To trigger deployment create a file called paco.war.dodeploy
16:03:20,651 INFO [org.jboss.as.server] (Controller Boot Thread) JBAS015888: Creating http management service using socket-binding (management-http)
16:03:20,671 INFO [org.xnio] (MSC service thread 1-3) XNIO version 3.3.0.Final
16:03:20,680 INFO [org.xnio.nio] (MSC service thread 1-3) XNIO NIO Implementation Version 3.3.0.Final
16:03:20,730 INFO [org.wildfly.extension.io] (ServerService Thread Pool -- 31) WFLYIO001: Worker 'default' has auto-configured to 8 core threads with 64 task threads based on your 4 available processors
16:03:20,738 INFO [org.jboss.as.clustering.infinispan] (ServerService Thread Pool -- 32) JBAS010280: Activating Infinispan subsystem.
16:03:20,746 INFO [org.jboss.as.security] (ServerService Thread Pool -- 45) JBAS013171: Activating Security Subsystem
16:03:20,748 INFO [org.jboss.as.naming] (ServerService Thread Pool -- 40) JBAS011800: Activating Naming Subsystem
16:03:20,762 INFO [org.jboss.as.webservices] (ServerService Thread Pool -- 48) JBAS015537: Activating WebServices Extension
16:03:20,779 INFO [org.jboss.as.connector.logging] (MSC service thread 1-5) JBAS010408: Starting JCA Subsystem (IronJacamar 1.1.9.Final)
16:03:20,788 INFO [org.jboss.as.security] (MSC service thread 1-5) JBAS013170: Current PicketBox version=4.0.21.Final
16:03:20,802 INFO [org.jboss.as.connector.subsystems.datasources] (ServerService Thread Pool -- 27) JBAS010403: Deploying JDBC-compliant driver class org.h2.Driver (version 1.3)
16:03:20,809 INFO [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-6) JBAS010417: Started Driver service with driver-name = h2
16:03:20,812 INFO [org.wildfly.extension.undertow] (MSC service thread 1-2) JBAS017502: Undertow 1.1.8.Final starting
16:03:20,817 INFO [org.wildfly.extension.undertow] (ServerService Thread Pool -- 47) JBAS017502: Undertow 1.1.8.Final starting
16:03:20,827 INFO [org.jboss.as.naming] (MSC service thread 1-6) JBAS011802: Starting Naming Service
16:03:20,831 INFO [org.jboss.as.mail.extension] (MSC service thread 1-2) JBAS015400: Bound mail session [java:jboss/mail/Default]
16:03:20,868 WARN [org.jboss.as.txn] (ServerService Thread Pool -- 46) JBAS010153: Node identifier property is set to the default value. Please make sure it is unique.
16:03:20,874 INFO [org.jboss.as.jsf] (ServerService Thread Pool -- 38) JBAS012615: Activated the following JSF Implementations: [main]
16:03:20,876 INFO [org.jboss.remoting] (MSC service thread 1-3) JBoss Remoting version 4.0.7.Final
16:03:20,991 INFO [org.wildfly.extension.undertow] (ServerService Thread Pool -- 47) JBAS017527: Creating file handler for path C:\Wild\wildfly-8.2.1.Final/welcome-content
16:03:21,088 INFO [org.wildfly.extension.undertow] (MSC service thread 1-4) JBAS017525: Started server default-server.
16:03:21,095 INFO [org.wildfly.extension.undertow] (MSC service thread 1-4) JBAS017531: Host default-host starting
16:03:21,361 INFO [org.jboss.as.server.deployment.scanner] (MSC service thread 1-7) JBAS015012: Started FileSystemDeploymentService for directory C:\Wild\wildfly-8.2.1.Final\standalone\deployments
16:03:21,366 INFO [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015876: Starting deployment of "paco.war" (runtime-name: "paco.war")
16:03:21,504 INFO [org.wildfly.extension.undertow] (MSC service thread 1-1) JBAS017519: Undertow HTTP listener default listening on localhost/127.0.0.1:8080
16:03:21,698 INFO [org.jboss.as.connector.subsystems.datasources] (MSC service thread 1-3) JBAS010400: Bound data source [java:jboss/datasources/ExampleDS]
16:03:22,038 INFO [org.jboss.ws.common.management] (MSC service thread 1-1) JBWS022052: Starting JBoss Web Services - Stack CXF Server 4.3.2.Final
16:03:23,905 WARN [org.jboss.as.server.deployment] (MSC service thread 1-2) JBAS015960: Class Path entry vaadin-server-7.3.5.jar in /C:/Wild/wildfly-8.2.1.Final/standalone/deployments/paco.war/WEB-INF/lib/confirmdialog-2.1.2.jar does not point to a valid jar for a Class-Path reference.
16:03:23,905 WARN [org.jboss.as.server.deployment] (MSC service thread 1-2) JBAS015960: Class Path entry vaadin-sass-compiler-0.9.10.jar in /C:/Wild/wildfly-8.2.1.Final/standalone/deployments/paco.war/WEB-INF/lib/confirmdialog-2.1.2.jar does not point to a valid jar for a Class-Path reference.
16:03:23,906 WARN [org.jboss.as.server.deployment] (MSC service thread 1-2) JBAS015960: Class Path entry vaadin-shared-7.3.5.jar in /C:/Wild/wildfly-8.2.1.Final/standalone/deployments/paco.war/WEB-INF/lib/confirmdialog-2.1.2.jar does not point to a valid jar for a Class-Path reference.
16:03:23,906 WARN [org.jboss.as.server.deployment] (MSC service thread 1-2) JBAS015960: Class Path entry json-0.0.20080701.jar in /C:/Wild/wildfly-8.2.1.Final/standalone/deployments/paco.war/WEB-INF/lib/confirmdialog-2.1.2.jar does not point to a valid jar for a Class-Path reference.
16:03:23,907 WARN [org.jboss.as.server.deployment] (MSC service thread 1-2) JBAS015960: Class Path entry jsoup-1.6.3.jar in /C:/Wild/wildfly-8.2.1.Final/standalone/deployments/paco.war/WEB-INF/lib/confirmdialog-2.1.2.jar does not point to a valid jar for a Class-Path reference.
16:03:23,908 WARN [org.jboss.as.server.deployment] (MSC service thread 1-2) JBAS015960: Class Path entry vaadin-server-7.5.0.jar in /C:/Wild/wildfly-8.2.1.Final/standalone/deployments/paco.war/WEB-INF/lib/confirmdialog-2.1.3.jar does not point to a valid jar for a Class-Path reference.
16:03:23,908 WARN [org.jboss.as.server.deployment] (MSC service thread 1-2) JBAS015960: Class Path entry vaadin-shared-7.5.0.jar in /C:/Wild/wildfly-8.2.1.Final/standalone/deployments/paco.war/WEB-INF/lib/confirmdialog-2.1.3.jar does not point to a valid jar for a Class-Path reference.
16:03:24,645 INFO [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-1) JBAS010403: Deploying JDBC-compliant driver class oracle.jdbc.OracleDriver (version 12.1)
16:03:24,674 INFO [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-7) JBAS010417: Started Driver service with driver-name = paco.war_oracle.jdbc.OracleDriver_12_1
16:03:24,800 INFO [io.undertow.servlet] (MSC service thread 1-4) Initializing AtmosphereFramework
16:03:24,808 INFO [io.undertow.servlet] (MSC service thread 1-4) Initializing AtmosphereFramework
16:03:24,825 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-4) MSC000001: Failed to start service jboss.undertow.deployment.default-server.default-host./paco: org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./paco: Failed to start service
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1904) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [rt.jar:1.7.0_79]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [rt.jar:1.7.0_79]
at java.lang.Thread.run(Unknown Source) [rt.jar:1.7.0_79]
Caused by: java.lang.NoSuchMethodError: com.vaadin.server.communication.PushRequestHandler.initAtmosphere(Ljavax/servlet/ServletConfig;)Lorg/atmosphere/cpr/AtmosphereFramework;
at com.vaadin.server.communication.JSR356WebsocketInitializer.initAtmosphereForVaadinServlet(JSR356WebsocketInitializer.java:152)
at com.vaadin.server.communication.JSR356WebsocketInitializer.contextInitialized(JSR356WebsocketInitializer.java:118)
at io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:173)
at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:194)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:87)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.start(UndertowDeploymentService.java:72)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
... 3 more
16:03:24,831 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) JBAS014613: Operation ("deploy") failed - address: ([("deployment" => "paco.war")]) - failure description: {
"JBAS014671: Failed services" => {"jboss.undertow.deployment.default-server.default-host./paco" => "org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./paco: Failed to start service
Caused by: java.lang.NoSuchMethodError: com.vaadin.server.communication.PushRequestHandler.initAtmosphere(Ljavax/servlet/ServletConfig;)Lorg/atmosphere/cpr/AtmosphereFramework;"},
"JBAS014879: One or more services were unable to start due to one or more indirect dependencies not being available." => {
"Services that were unable to start:" => ["jboss.deployment.unit.\"paco.war\".deploymentCompleteService"],
"Services that may be the cause:" => ["jboss.jdbc-driver.hsqldb_jar"]
}
}
16:03:24,833 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) JBAS014613: Operation ("add") failed - address: ([
("subsystem" => "datasources"),
("data-source" => "DefaultDS")
]) - failure description: {"JBAS014771: Services with missing/unavailable dependencies" => [
"jboss.data-source.java:/DefaultDS is missing [jboss.jdbc-driver.hsqldb_jar]",
"jboss.driver-demander.java:/DefaultDS is missing [jboss.jdbc-driver.hsqldb_jar]"
]}
16:03:24,835 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) JBAS014613: Operation ("add") failed - address: ([
("subsystem" => "datasources"),
("data-source" => "DefaultDS")
]) - failure description: {
"JBAS014771: Services with missing/unavailable dependencies" => [
"jboss.data-source.java:/DefaultDS is missing [jboss.jdbc-driver.hsqldb_jar]",
"jboss.driver-demander.java:/DefaultDS is missing [jboss.jdbc-driver.hsqldb_jar]"
],
"JBAS014879: One or more services were unable to start due to one or more indirect dependencies not being available." => {
"Services that were unable to start:" => [
"jboss.data-source.reference-factory.DefaultDS",
"jboss.naming.context.java.DefaultDS"
],
"Services that may be the cause:" => ["jboss.jdbc-driver.hsqldb_jar"]
}
}
16:03:24,914 INFO [org.jboss.as.server] (ServerService Thread Pool -- 28) JBAS018559: Deployed "paco.war" (runtime-name : "paco.war")
16:03:24,918 INFO [org.jboss.as.controller] (Controller Boot Thread) JBAS014774: Service status report
JBAS014775: New missing/unsatisfied dependencies:
service jboss.jdbc-driver.hsqldb_jar (missing) dependents: [service jboss.driver-demander.java:/DefaultDS, service jboss.data-source.java:/DefaultDS]
JBAS014777: Services which failed to start: service jboss.undertow.deployment.default-server.default-host./paco: org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./paco: Failed to start service
16:03:25,061 INFO [org.jboss.as] (Controller Boot Thread) JBAS015961: Http management interface listening on http://127.0.0.1:9990/management
16:03:25,061 INFO [org.jboss.as] (Controller Boot Thread) JBAS015951: Admin console listening on http://127.0.0.1:9990
16:03:25,062 ERROR [org.jboss.as] (Controller Boot Thread) JBAS015875: WildFly 8.2.1.Final "Tweek" started (with errors) in 6644ms - Started 264 of 326 services (6 services failed or missing dependencies, 92 services are lazy, passive or on-demand)
16:03:25,175 INFO [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-7) JBAS010418: Stopped Driver service with driver-name = paco.war_oracle.jdbc.OracleDriver_12_1
16:03:25,211 INFO [org.hibernate.validator.internal.util.Version] (MSC service thread 1-6) HV000001: Hibernate Validator 5.1.3.Final
16:03:25,665 INFO [org.jboss.as.server.deployment] (MSC service thread 1-6) JBAS015877: Stopped deployment paco.war (runtime-name: paco.war) in 498ms
16:03:25,859 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS018558: Undeployed "paco.war" (runtime-name: "paco.war")
16:03:25,861 INFO [org.jboss.as.controller] (DeploymentScanner-threads - 2) JBAS014774: Service status report
JBAS014775: New missing/unsatisfied dependencies:
service jboss.deployment.unit."paco.war".component."com.patientconsent.PatientconsentUI$Servlet".START (missing) dependents: [service jboss.deployment.unit."paco.war".deploymentCompleteService]
service jboss.deployment.unit."paco.war".component."com.patientconsent.views.TableCheckBoxUI$Servlet".START (missing) dependents: [service jboss.deployment.unit."paco.war".deploymentCompleteService]
service jboss.deployment.unit."paco.war".component."com.sun.faces.config.ConfigureListener".START (missing) dependents: [service jboss.deployment.unit."paco.war".deploymentCompleteService]
service jboss.deployment.unit."paco.war".component."com.vaadin.server.communication.JSR356WebsocketInitializer".START (missing) dependents: [service jboss.deployment.unit."paco.war".deploymentCompleteService]
service jboss.deployment.unit."paco.war".component."javax.faces.webapp.FacetTag".START (missing) dependents: [service jboss.deployment.unit."paco.war".deploymentCompleteService]
service jboss.deployment.unit."paco.war".component."javax.servlet.jsp.jstl.tlv.PermittedTaglibsTLV".START (missing) dependents: [service jboss.deployment.unit."paco.war".deploymentCompleteService]
service jboss.deployment.unit."paco.war".component."javax.servlet.jsp.jstl.tlv.ScriptFreeTLV".START (missing) dependents: [service jboss.deployment.unit."paco.war".deploymentCompleteService]
service jboss.deployment.unit."paco.war".component."org.atmosphere.container.Servlet30CometSupport$CometListener".START (missing) dependents: [service jboss.deployment.unit."paco.war".deploymentCompleteService]
service jboss.undertow.deployment.default-server.default-host./paco (missing) dependents: [service jboss.deployment.unit."paco.war".deploymentCompleteService]
JBAS014777: Services which failed to start: service jboss.undertow.deployment.default-server.default-host./paco
16:03:29,961 INFO [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 2) JBAS015003: Found paco.war in deployment directory. To trigger deployment create a file called paco.war.dodeploy
</code></pre>
<p>Environment:</p>
<ul>
<li>Java 1.7</li>
<li>Eclipse Luna</li>
<li>Wildfly 8.x</li>
</ul>
<p>I have already searched each one of the errors and nothing really helped me. Can you please give me your lights about what could possibly be the fault? Please inform me if you want another information about my app's enviroment </p>
| <p>It seems like database connection issue. Please check </p>
<ol>
<li>If database is up for accepting connections.</li>
<li>Any firewall, stopping opening of ports etc.</li>
<li>Do check jta="true" or false is allowed and code written.</li>
<li>Check if you have packaged associated jdbc driver jar file with application.</li>
</ol>
<p>But yes, answer to your query is; this error is related to database configuration. Please check appropriate documentation. </p>
|
Design pattern to rewrite a Java class from an API <p>I have to use the EWS Java API to call Exchange Server.
In this API, there is Task class which have more than 20-30 getters of different properties.
In our company, we will use only 4-5 properties; idem for Contacts and Appointment.</p>
<p>In my opinion, I consider it may be more practical to write a mini-API so the developers can be found easier the 4-5 properties they have to use for the three Items (Appointments, Task, Contact).</p>
<p>The ExtendedTask I've just created must be extended the Task class from the original API ? If yes, do i have to create the 4-5 attributes in the ExtendedTask because it is rendundant with the parent class ?!</p>
<p>What would you do if you were me ? Use the original class ? Create a subclass ? Create another class which don't extend the Task class ?</p>
<p>Thanks for you help</p>
| <p>Use Facade pattern. Create a class that encapsulates all the logic that your users would be needing in order to use your 3 Task-related actions (Appointments, Task, Contact).</p>
<p>Using this "Facade" class would hide the actual implementation logic (original API) from the end users, since majority of the API is not used.</p>
<pre><code>//pseudo code
class MyAPIFacade {
@Inject
OriginalAPI api;
public Task getTask() {
return api.getTask();
}
public Appointments getAppointments() {
return api.getAppointments();
}
public Contact getContact() {
return api.getContact();
}
</code></pre>
<p>}</p>
|
Cannot get vue-router to work with webpack <p>I'm trying to get vue-router to work without success and it got me quite angry after a while since i don't see any issue.</p>
<p>I'm using webpack via Elixir in Laravel, which has gulpfile like this:</p>
<pre><code>const elixir = require('laravel-elixir');
require('laravel-elixir-vue');
elixir(mix => {
mix.sass('app.scss')
.webpack('app.js');
});
</code></pre>
<p>Into my app.js file I'm "compiling" following code</p>
<pre><code>window.Vue = require('vue');
var VueResource = require('vue-resource');
var VueRouter = require('vue-router');
Vue.use(VueResource);
Vue.use(VueRouter);
</code></pre>
<p>And when I call in browser console</p>
<pre><code>new VueRouter({})
</code></pre>
<p>I got an error saying VueRouter is undefined. Why? The vue-resource is even in the app.js.</p>
<p>My package.json looks like this:</p>
<pre><code>{
"private": true,
"scripts": {
"prod": "gulp --production",
"dev": "gulp watch"
},
"devDependencies": {
"bootstrap-sass": "^3.3.7",
"foundation-sites": "^6.2.3",
"gulp": "^3.9.1",
"jquery": "^2.2.4",
"laravel-elixir": "^6.0.0-9",
"laravel-elixir-vue": "^0.1.4",
"laravel-elixir-webpack-official": "^1.0.2",
"lodash": "^4.14.0",
"script-loader": "^0.7.0",
"vue": "^2.0.1",
"vue-resource": "^0.9.3",
"vue-router": "^2.0.0"
}
}
</code></pre>
<p>Can anyone help?</p>
| <p>thats okay cause you didnt bind VueRouter to the <code>window</code> object as you did with <code>window.Vue = require('vue');</code></p>
<p>But usually you dont need the Router in the <code>window</code>
Do it in your app.js:</p>
<pre><code>window.Vue = require('vue');
var VueRouter = require('vue-router');
window.Vue.use(VueRouter);
var router = new VueRouter({
routes: {
{path: '', component: require('./components/MyComponent.vue')},
{path: '/dash', component: require('./components/Dash.vue')},
}
});
var AppComponent = require('./components/App.vue');
/* eslint-disable no-new */
var app = new Vue({
el: '#app',
router,
render: h => h(AppComponent),
});
</code></pre>
|
How do I combine a Controlled Lifetime relationship type (i.e. Owned<T>) with a delegate factory? <p>In my application, I have a service that requires a constructor parameter not resolved by Autofac, that I instantiate using a delegate factory:</p>
<pre class="lang-cs prettyprint-override"><code>public class Service
{
public Service(string parameter /*, ... other dependencies */)
{
}
public delegate Service Factory(string parameter);
}
</code></pre>
<p>This works great! I really love this feature.</p>
<p>I also like the Controlled Lifetime relationship, so I can let my component depend on a <code>Func<Owned<ISomething>></code> like this:</p>
<pre class="lang-cs prettyprint-override"><code>public class Component
{
private Func<Owned<ISomething>> _somethingFactory;
/* constructor omitted for brevity */
public void DoSomethingUseful()
{
using (var ownedSomething = _somethingFactory())
{
/* Lots of useful code here */
}
}
}
</code></pre>
<p>My problem is that now I want to combine the two. I can't have an instance of <code>Func<Owned<Service>></code> injected, because it needs that parameter, so my current solution is to abstract the factory away into another service, say <code>IServiceFactory</code>:</p>
<pre class="lang-cs prettyprint-override"><code>public interface IServiceFactory
{
Service Create(string parameter);
}
</code></pre>
<p>...implemented as such:</p>
<pre class="lang-cs prettyprint-override"><code>public class ServiceFactory : IServiceFactory
{
private Service.Factory _internalFactory;
public ServiceFactory(Service.Factory internalFactory)
{
_internalFactory = internalFactory;
}
public Service Create(string parameter)
{
return _internalFactory(parameter);
}
}
</code></pre>
<p>My component then becomes this:</p>
<pre class="lang-cs prettyprint-override"><code>public class Component
{
Func<Owned<IServiceFactory>> _serviceFactoryFactory;
/* ... */
}
</code></pre>
<p>The need for such a field name leaves a bad taste in my mouth to the point that I suspect there must be a cleaner way to handle this case.</p>
<p>Is there another way?</p>
| <p>You could change your injected factory to include the string parameter:</p>
<pre><code>private Func<string, Owned<ISomething>> _somethingFactory;
</code></pre>
<p>Then you can pass the <code>string</code> to the factory when you want to create a new instance:</p>
<pre><code>public void DoSomethingUseful()
{
using (var ownedSomething = _somethingFactory("my parameter"))
{
/* Lots of useful code here */
}
}
</code></pre>
<p>I've created a <a href="https://dotnetfiddle.net/6fo4NP" rel="nofollow">.NET Fiddle</a> with a small working sample.</p>
|
Javascript HighCharts Changing Data onChange instead of adding new one <p>I am using HighCharts and I am currently using addSeries which just adds new data but instead I need to replace the existing data and add new data when changing the select box.</p>
<p>Here is the code: </p>
<p><strong>JS:</strong></p>
<p>var chart;</p>
<pre><code>$(function () {
dat1 = [
{
"chall": [
{
"id": "8062",
"name": "name 1",
"desc": "desc 1",
"vfield": 250,
"cfield": 100
},
{
"id": "8061",
"name": "name 2",
"desc": "desc 2",
"vfield": 120,
"cfield": 110
},
{
"id": "8060",
"name": "name 3",
"desc": "desc 3",
"vfield": 76,
"cfield": 90
}
]
}
];
dat2 = [
{
"chall": [
{
"id": "8062",
"name": "name 4",
"desc": "desc 4",
"vfield": 250,
"cfield": 100
},
{
"id": "8061",
"name": "name 5",
"desc": "desc 5",
"vfield": 120,
"cfield": 110
},
{
"id": "8060",
"name": "name 6",
"desc": "desc 6",
"vfield": 76,
"cfield": 90
}
]
}
];
var mainData = dat1;
var cList=[];
var vList=[];
var comList=[];
for (var i = 0; i < mainData[0].chall.length; i++) {
var obj = mainData[0].chall[i];
var chlst = obj.name + " [" + obj.id + "]";
var vl = obj.vfield;
var cl = obj.cfield;
cList.push(chlst);
vList.push(vl);
comList.push(cl);
}
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Title Here'
},
xAxis: {
categories: cList
},
yAxis: {
allowDecimals: false,
min: 0,
title: {
text: 'Left Title'
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
},
},
tooltip: {
formatter: function () {
return '<b>' + this.x + '</b><br/>' +
this.series.name + ': ' + this.y + '<br/>' +
'Total: ' + this.point.stackTotal;
}
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function () {
alert('');
},
},
},
},
column: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
style: {
textShadow: '0 0 3px black'
}
}
}
},
series: [{
name: 'V List',
data: vList
}, {
name: 'C List',
data: comList
}]
});
$('#myselectoptions').change(function() {
var chart = $('#container').highcharts();
chart.addSeries({
data: dat2
});
});
});
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><div class="form-group">
<br><label for="sel">Select:</label>
<select class="form-control" id="myselectoptions">
<option value="1">Dat1</option>
<option value="2">Dat2</option>
</select>
</div>
<div id="container" style="height: 400px"></div>
</code></pre>
<p>How can I switch from one data to the other when changing the select?</p>
| <pre><code>chart.series[0].setData(dat2);
</code></pre>
<p><a href="http://api.highcharts.com/highcharts/Series.setData" rel="nofollow">http://api.highcharts.com/highcharts/Series.setData</a></p>
|
Is it possible to conditionally show an XML include based on a classes method response? <p>I'm wondering if it's possible to use DataBinding to do conditionally show a layout based on a methods boolean response. Here's what I'm trying to do</p>
<p>XML Layout:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="View"
type="android.view.View"/>
<variable
name="App"
type="com.app.JTApp"/>
</data>
<include layout="@layout/view_checkout_total_cardview"
android:visibility="@{App.isLandscape() ? View.GONE : View.VISIBLE}" />
</layout>
</code></pre>
<p>JTApp class:</p>
<pre class="lang-java prettyprint-override"><code>public class JTApp {
public boolean isLandscape() {
Timber.d("putty-- isLandscape: --------------------------");
return getResources().getBoolean(R.bool.is_landscape);
}
â¦
}
</code></pre>
<p>Currently this doesn't work. Am I missing something or is this not possible? I'm coming from the web where this is possible with frameworks like Angular.</p>
| <p>Yes, using a conditional statement within XML is possible. I am not too familiar with data binding library, but a similar functionality is used in the <a href="https://developer.android.com/topic/libraries/data-binding/index.html#layout_details" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>Zero or more import elements may be used inside the data element.
These allow easy reference to classes inside your layout file, just
like in Java.</p>
<pre><code><data>
<import type="android.view.View"/>
</data>
</code></pre>
<p>Now, View may be used within your binding expression:</p>
<pre><code><TextView
android:text="@{user.lastName}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="@{user.isAdult ? View.VISIBLE : View.GONE}"/>
</code></pre>
</blockquote>
<p>I believe the only issue with your code is that you are using the <code>View</code> as a <code>variable</code> instead of as an <code>import</code> in your <code><data></code> element.</p>
|
Apply style to control in custom renderer <p>I want to apply a style to a control. This is the style</p>
<pre class="lang-xml prettyprint-override"><code><Application.Resources>
<ResourceDictionary>
<SolidColorBrush x:Key="BackgroundColor" Color="Yellow" />
<Style TargetType="Button" x:Name="myNewButtonStyle">
<Setter Property="Background" Value="{StaticResource BackgroundColor}" />
</Style>
</ResourceDictionary>
</Application.Resources>
</code></pre>
<p>, which can be found in <em>App.xaml</em> (UWP project). And here is the custom renderer:</p>
<pre class="lang-cs prettyprint-override"><code>protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if (this.Element != null)
{
var style = Windows.UI.Xaml.Application.Current.Resources["myNewButtonStyle"] as Windows.UI.Xaml.Style;
this.Control.Style = style;
}
}
</code></pre>
<p>The idea is based on <a href="http://stackoverflow.com/a/38117908/426227">this answer</a>. But the style isn't applied. Setting the background color in code does work:</p>
<pre class="lang-cs prettyprint-override"><code>this.Control.BackgroundColor = new SolidColorBrush(Windows.UI.Colors.Yellow);
</code></pre>
<p>How can I apply a style to a control in a custom renderer?</p>
| <p>Now I created a separate test project with the code above. Now I tried with different Xamarin.Form versions and this is the result:</p>
<p><strong>XF 2.2.0.45</strong>: style is applied<br>
<strong>XF 2.3.0.107</strong>: style isn't applied<br>
<strong>XF 2.3.1.114</strong>: style isn't applied<br>
<strong>XF 2.3.2.127</strong>: style isn't applied </p>
<p>I'll fill a bug report.</p>
|
Parse String to double[] <p>As can add all the values ââof a string array being these positive or negative and then pass them to a double array.</p>
<p>Example:
SUM VALUES
String sa_notas[] = {1, 5, -2}
RESULT (1+5-2) = 4</p>
<p>ERROR MENSSAGE:
at org.apache.harmony.luni.util.FloatingPointParser.initialParse(FloatingPointParser.java:149)
at org.apache.harmony.luni.util.FloatingPointParser.parseDouble(FloatingPointParser.java:281)
at java.lang.Double.parseDouble(Double.java:318)
at es.amedidaapp.gado.D_Anadir_Registro$3.afterTextChanged(D_Anadir_Registro.java:176)</p>
<p>Thanks for the help</p>
<p>code:</p>
<pre><code>if (s.length() > 0) {
s_contains_notas = et_notas.getText().toString();
if (b_calculadora) {
if (s_contains_notas.length() <= 0 || !s_contains_notas.matches("[^0-9]+")) {
s_contains_notas = s_contains_notas.replace("+", " ");//separate positives numbers
s_contains_notas = s_contains_notas.replaceAll("[^0-9, -]", ""); //delete letters
s_contains_notas = s_contains_notas.replace(",", "."); //change format numbers
s_contains_notas = s_contains_notas.replace("-", " -"); //separate negatives numbers
String sa_notas[] = s_contains_notas.split(" "); //{1, 5, -2}
double[] d_notas = new double[sa_notas.length];
for (int i = 0; i < d_notas.length; i++) {
d_notas[i] = Double.parseDouble(sa_notas[i]); //ERROR to write negative numbers
}
double d_sum_notas = 0;
for (Double d : d_notas) {
d_sum_notas += d;
}
s_euros = String.valueOf(d_sum_notas);
et_euros.setText(nf_locale.format(d_sum_notas));
}
}
}
}
</code></pre>
| <p>How about a little different approach?</p>
<pre><code>import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegEx {
// Example input:
final static private String NUMBERS = "Data: 0,5⬠-0.1$ 9 -3 #3";
// Regular expression to match floating point numbers:
final static private Pattern PATTERN = Pattern.compile("[-]?[0-9]+(?:[,.][0-9]+)?");
public static void main(String[] args) {
final Matcher m = PATTERN.matcher(NUMBERS);
while ( m.find() ) {
System.out.println(m.group());
}
}
}
</code></pre>
<p>Output:</p>
<pre><code>0,5
-0.1
9
-3
3
</code></pre>
|
The jQuery UI sortable serialization <p>I know this question has been asked numerous times but I think I'm missing a point or something.
I'm trying to leverage the serialization of jQuery sortable, but it looks like it's not working. </p>
<p>Here is my base list:</p>
<pre><code> <ol class='simple_with_no_drop vertical'>
<li id='script_1' class='highlight'>Hello ES</li>
<li id='script_2' class='highlight'>Login ES</li>
<li id='script_3' class='highlight'>Test ES</li>
<li id='script_4' class='highlight'>Another ES</li>
</ol>
</div>
<div class='span4'>
<h3>Scenario scripts</h3>
<ol class='simple_with_drop vertical'>
<li id='script_1'>Hello ES</li>
<li id='script_2'>Login ES</li>
</ol>
</div><button>Save Scenario</button>
<pre id='serialize_output'> </pre>
</code></pre>
<p>Here is the js:</p>
<pre><code>var group = $("ol.simple_with_drop").sortable({
group: 'simple_with_drop',
onDragStart: function ($item, container, _super) {
if(!container.options.drop){
$item.clone().insertAfter($item);
}
_super($item, container);
},
onDrop: function ($item, container, _super) {
var data = group.sortable('serialize').get();
var jsonString = JSON.stringify(data);
$('#serialize_output').text(jsonString);
_super($item, container);
}, });
$("ol.simple_with_no_drop").sortable({
group: 'simple_with_drop',
drop: false
});
</code></pre>
<p>And the serialization result :</p>
<pre><code>[[{},{},{}]]
</code></pre>
<p>The idea was to leverage the auto serialization with item_id form, but it looks lite it's not recognized.
If I try, as in many ressources, without the .get(), I have a "Uncaught TypeError: Converting circular structure to JSON" error when dropping.</p>
<p>I tried to use the serialization with $(this) but got this result instead :</p>
<pre><code> [{"containerPath":"","containerSelector":"ol, ul","distance":0,"delay":0,"handle":"","itemPath":"","itemSelector":"li","bodyClass":"dragging","draggedClass":"dragged","placeholderClass":"placeholder","placeholder":"<li class=\"placeholder\"></li>","pullPlaceholder":true,"tolerance":0,"drag":true,"drop":true,"exclude":"","nested":true,"vertical":true,"group":"simple_with_drop"}]
</code></pre>
<p>Any input would be appreciated! thanks!</p>
| <p>Your JS Code is fine. In your html code just add data-id attribute with each of the li, and it will work!</p>
<pre><code><ol class='simple_with_no_drop vertical'>
<li id='script_1' data-id='script_1' class='highlight'>Hello ES</li>
<li id='script_2' data-id='script_2' class='highlight'>Login ES</li>
<li id='script_3' data-id='script_3' class='highlight'>Test ES</li>
<li id='script_4' data-id='script_4' class='highlight'>Another ES</li>
</ol>
</div>
<div class='span4'>
<h3>Scenario scripts</h3>
<ol class='simple_with_drop vertical'>
<li id='script_1' data-id='script_1'>Hello ES</li>
<li id='script_2' data-id='script_2'>Login ES</li>
</ol>
</div><button>Save Scenario</button>
<pre id='serialize_output'> </pre>
</code></pre>
|
Android objectanimator not animating <p>I have designed today two drawable's of the classic <code>arrow</code> and <code>hamburger</code> icon to recreate and understand <code>objectAnimator</code> in android. The problem occurs when no animation is played but the drawable is changed.</p>
<p>I have created <code>ic_backarrow.xml</code>:</p>
<pre><code><vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="48dp"
android:width="48dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path android:strokeColor="@color/blue_ripple"
android:fillColor="@color/blue_ripple"
android:pathData="@string/arrow" />
</vector>
</code></pre>
<p>Followed by <code>ic_menu.xml</code>:</p>
<pre><code><vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="48dp"
android:width="48dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path android:fillColor="@color/blue_ripple"
android:pathData="@string/menu" />
</vector>
</code></pre>
<p>In <code>strings.xml</code> I have defined my path's to be more easy to follow:</p>
<pre><code><string name="arrow">M4,11 H20 V13 H4 V11 M4,11 L12,4 L13.5,5.5 L5.5,12.5 L4,11 M4,13 L12,20 L13.5,18.5 L7.2,13 L4,13</string>
<string name="menu">M3,6 H21 V8 H3 V6 M3,11 L21,11 L21,13 L3,13 L3,11 M3,16 L21,16 L21,18 L3,18 L3,16</string>
</code></pre>
<p>I also modified the paths to be able to animate the drawable's: arrow to menu and menu to arrow.</p>
<p>After I have created the <code>arrow_to_menu.xml</code> where I define the <code>objectAnimator</code>:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<objectAnimator
xmlns:android="http://schemas.android.com/apk/res/android"
android:propertyName="pathData"
android:valueFrom="@string/arrow"
android:valueTo="@string/menu"
android:duration="@integer/duration"
android:interpolator="@android:interpolator/fast_out_slow_in"
android:valueType="pathType" />
</code></pre>
<p>and the <code>menu_to_arrow.xml</code>:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<objectAnimator
xmlns:android="http://schemas.android.com/apk/res/android"
android:propertyName="pathData"
android:valueFrom="@string/menu"
android:valueTo="@string/arrow"
android:duration="@integer/duration"
android:interpolator="@android:interpolator/fast_out_slow_in"
android:valueType="pathType" />
</code></pre>
<p>In drawable's I also defined the <code>animated-vector</code> with the initial <code>drawable</code> and the target <code>objectAnimator</code>:</p>
<p>File: <code>avd_arrow_to_menu.xml</code>:</p>
<pre><code><animated-vector
xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/ic_backarrow">
<target
android:name="@string/tick"
android:animation="@animator/arrow_to_menu" />
</animated-vector>
</code></pre>
<p>And also <code>avd_menu_to_arrow.xml</code>:</p>
<pre><code><animated-vector
xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/ic_menu">
<target
android:name="@string/cross"
android:animation="@animator/menu_to_arrow" />
</animated-vector>
</code></pre>
<p>In the project <code>layout</code> I have created an <code>ImageView</code>:</p>
<pre><code><ImageView
android:id="@+id/tick_cross"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/ic_menu"
android:layout_margin="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />
</code></pre>
<p>In the <code>class</code> file I look-up for the <code>ImageView</code> and import the <code>AnimatedVectorDrawable's</code> </p>
<pre><code>arrowMenu = (ImageView) findViewById(R.id.tick_cross);
menuToArrow = (AnimatedVectorDrawable) getDrawable(R.drawable.avd_menu_to_arrow);
arrowToMenu = (AnimatedVectorDrawable) getDrawable(R.drawable.avd_arrow_to_menu);
arrowMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
animate(arrowMenu);
}
});
</code></pre>
<p>And when the <code>ImageView</code> is clicked, it should animate between <code>hamburger</code> icon and <code>arrow</code> icon:</p>
<pre><code>public void animate(View view) {
AnimatedVectorDrawable drawable = menu ? menuToArrow : arrowToMenu;
arrowMenu.setImageDrawable(drawable);
drawable.start();
menu = !menu;
}
</code></pre>
<p>As I said before, there is no animation between arrow and hamburger icon. I tried to change <code>android:duration</code> to something bigger like 1000 or something small like 400 but I have the same result. </p>
<p>Sorry for the long post, I really needed to explain every step I done.</p>
| <p>You need to give names to the <code>paths</code> in your <code>VectorDrawables</code>.
If we look at your first <code>AnimatedVectorDrawable</code>:</p>
<pre><code><animated-vector
xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/ic_backarrow">
<target
android:name="@string/tick"
android:animation="@animator/arrow_to_menu" />
</animated-vector>
</code></pre>
<p>The line <code>android:name="@string/tick"</code> specifies what part of the <code>VectorDrawable</code> you are trying to animate, but if we look at the <code>VectorDrawable</code>, no part of it has been given a name to match that.</p>
<p>To fix that, take the <code>ic_backarrow.xml</code> and add the appropriate name tag:</p>
<pre><code><vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="48dp"
android:width="48dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:name="@string/tick"
android:strokeColor="@color/blue_ripple"
android:fillColor="@color/blue_ripple"
android:pathData="@string/arrow" />
</vector>
</code></pre>
<p>Then add the appropriate <code>@string/cross</code> name to the path in your other <code>VectorDrawable</code>.</p>
|
HTML / CSS Div trouble - sitting next to but below each other <p>I'm real sorry if this has been answered multiple times before, I did try to search, but I couldn't quite find what I'm looking for.</p>
<p>I'm messing around toying with different generic portfolio pages just for practice / learning (I'm pretty new). What I'm trying to do atm is have a wall of images laid out that scroll with a nav area stays fixed.</p>
<p>I've been trying for ages to fix this, but for some reason my columns of images sit to the side of each other (as desired) but also below each other, like a stair case. I'll post the HMTL / CSS below, I'd really appreciate some help!</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>/*NAVIGATION*/
#navi {
position: fixed;
float: left;
}
#navi a {
text-decoration: none;
color: #969696;
}
#navi ul {
list-style-type: none;
margin-left: -40px;
margin-top: 10px;
}
#navi h1 {
color: #4A968F;
}
/*IMAGE WALL*/
img {
max-width: 250px;
margin-bottom: 10px;
}
#one {
margin-left: 250px;
}
#two {
margin-left: 510px;
}
#three {
margin-left: 770px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="main">
<!-- NAVIGATION -->
<div class="container">
<div class="row">
<div class="col-md-3" id="navi">
<h1>SR|BEST</h1>
<ul>
<li><a href="#">HOME</a>
</li>
<li><a href="#">PROJECTS</a>
</li>
<li><a href="#">TEXTS</a>
</li>
<li><a href="#">CONACT / ABOUT</a>
</li>
</ul>
</div>
<!-- IMAGE WALL -->
<div class="rowone">
<div class="col-md-3" id="one">
<img src="https://srbest.files.wordpress.com/2013/08/2012-09-09-07-07-49.jpg" />
<img src="https://srbest.files.wordpress.com/2013/05/fi010513.jpg" />
<img src="https://srbest.files.wordpress.com/2013/04/sd.jpg" />
<img src="https://srbest.files.wordpress.com/2011/07/in.jpg" />
<img src="https://srbest.files.wordpress.com/2012/06/7.jpg" />
</div>
</div>
<div class="rowtwo">
<div class="col-md-3" id="two">
<img src="https://srbest.files.wordpress.com/2013/04/17.jpg" />
<img src="https://srbest.files.wordpress.com/2013/04/1.jpg" />
<img src="https://srbest.files.wordpress.com/2013/08/2012-09-09-07-04-31.jpg" />
<img src="https://srbest.files.wordpress.com/2011/06/1.jpg" />
<img src="https://srbest.files.wordpress.com/2011/06/ramsgate-sf2.jpg" />
</div>
</div>
<div class="rowthree">
<div class="col-md-3" id="three">
<img src="https://srbest.files.wordpress.com/2013/08/2012-09-09-07-01-12.jpg" />
<img src="https://srbest.files.wordpress.com/2013/08/2012-09-04-08-03-57.jpg" />
<img src="https://srbest.files.wordpress.com/2012/10/pr17.jpg" />
<img src="https://srbest.files.wordpress.com/2011/10/briavels.jpg" />
<img src="https://srbest.files.wordpress.com/2012/12/n-24.jpg" />
</div>
</div>
</div>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| <p>Something like this would be a good start. Bootstrap can take care of the columns for you so you don't need to set any margins for those. The sticky navigation isn't really ideally done here but should work.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="main">
<!-- NAVIGATION -->
<div class="container">
<div class="row">
<div class="col-md-3" id="navi">
<h1>SR|BEST</h1>
<ul>
<li><a href="#">HOME</a>
</li>
<li><a href="#">PROJECTS</a>
</li>
<li><a href="#">TEXTS</a>
</li>
<li><a href="#">CONACT / ABOUT</a>
</li>
</ul>
</div>
<!-- IMAGE WALL -->
<div class="col-md-9" id="wall">
<div class="col-md-4">
<img src="https://srbest.files.wordpress.com/2013/08/2012-09-09-07-07-49.jpg" />
<img src="https://srbest.files.wordpress.com/2013/05/fi010513.jpg" />
<img src="https://srbest.files.wordpress.com/2013/04/sd.jpg" />
<img src="https://srbest.files.wordpress.com/2011/07/in.jpg" />
<img src="https://srbest.files.wordpress.com/2012/06/7.jpg" />
</div>
<div class="col-md-4">
<img src="https://srbest.files.wordpress.com/2013/04/17.jpg" />
<img src="https://srbest.files.wordpress.com/2013/04/1.jpg" />
<img src="https://srbest.files.wordpress.com/2013/08/2012-09-09-07-04-31.jpg" />
<img src="https://srbest.files.wordpress.com/2011/06/1.jpg" />
<img src="https://srbest.files.wordpress.com/2011/06/ramsgate-sf2.jpg" />
</div>
<div class="col-md-4">
<img src="https://srbest.files.wordpress.com/2013/08/2012-09-09-07-01-12.jpg" />
<img src="https://srbest.files.wordpress.com/2013/08/2012-09-04-08-03-57.jpg" />
<img src="https://srbest.files.wordpress.com/2012/10/pr17.jpg" />
<img src="https://srbest.files.wordpress.com/2011/10/briavels.jpg" />
<img src="https://srbest.files.wordpress.com/2012/12/n-24.jpg" />
</div>
</div>
</div>
</div>
</div>
</body>
</html>
</code></pre>
<p>And the CSS:</p>
<pre><code>/*NAVIGATION*/
#navi {
position: fixed;
top: 0;
left: 20px;
}
#navi a {
text-decoration: none;
color: #969696;
}
#navi ul {
list-style-type: none;
margin: 0;
padding: 0;
}
#navi h1 {
color: #4A968F;
}
/*IMAGE WALL*/
#wall {
margin: 20px 0 0 250px;
}
img {
max-width: 100%;
margin-bottom: 20px;
}
</code></pre>
|
How to debug production java using a dump recorded when app throws an exception? <h3>How can we debug what happened when an exception was thrown at a later time?</h3>
<p>We've got a production app written in Java that randomly throws an exception, which we can catch and log on the server. We'd like to debug this to see what's happening, as the logs aren't revealing much information.</p>
<p>And by debug I mean step into a debugger like Eclipse or IntelliJ's debugger and walk through the code for what happened when the exception was thrown, complete with data being passed to methods and local variables, etc.</p>
<p>So I'd like to have a dump of some sort saved whenever this happens, and then be able to load that dump in some tool to debug it after the fact.</p>
<h3>So I'd prefer solutions that:</h3>
<ul>
<li>Can create a dump file from code <em>without</em> adversely affecting our production app</li>
<li>Can be analyzed using a GUI tool like Eclipse's debugger, for example.</li>
</ul>
| <p>I recommend having a look into Oracle's JVM Flight Recorder, which is not free, but exactly for this scenario.</p>
<p><a href="http://www.oracle.com/technetwork/java/javaseproducts/mission-control/java-mission-control-1998576.html" rel="nofollow">http://www.oracle.com/technetwork/java/javaseproducts/mission-control/java-mission-control-1998576.html</a></p>
|
Jenkins build job cannot locate item in a keychain <p>I've got a jenkins job that will execute a gradle script that retrieves android store and key passwords from the keychain. The script works fine running on my local machine, however I'm trying to add it to the jenkins job and it's failing to locate the item in the keychain:</p>
<p><code>security: SecKeychainSearchCopyNext: The specified item could not be found in the keychain.</code></p>
<p>The command it's trying to run is: <code>security -q find-generic-password -a jenkins -gl storePassword</code></p>
<p>Running this command from terminal retrieves the password as expected.</p>
<p>I think the problem is to do with the fact that jenkins job is running under jenkins user. I've tried su to jenkins user and I think it only has system keychain - if I do <code>security list-keychains</code> it comes up with <code>System.keychain</code>. My store and key passwords are inside login keychain which I don't think jenkins user has access to? Any suggestions how to rectify this? I've tried creating the keychain through security but that didn't really work.</p>
| <p>Just in case this is useful for someone:</p>
<p>1) Create a new keychain using keychain-access. Let's call it 'jenkins', for example.<br>
2) Copy the keychain to the <code>jenkins</code> library directory (<code>$HOME/Library/Keychains/jenkins.keychain</code>)<br>
3) run <code>chown jenkins:jenkins</code> on the <code>jenkins.keychain</code><br>
4) run <code>sudo su jenkins</code> to switch to jenkins user.<br>
5) add the jenkins.keychain to the keychain list <code>security list-keychains -s ~/Library/Keychains/jenkins.keychain</code><br>
6) add a bash script call to the jenkins build process to unlock the keychain. ideally, the call should use the password stored in the jenkins build via the mask password plugin. Something like <code>security unlock-keychain -p "${jenkins_keychain_password}" "$HOME/Library/Keychains/jenkins.keychain"</code></p>
<p>This is a good guide for more details: <a href="http://www.egeek.me/2015/04/12/jenkins-setting-up-ios-code-signing/" rel="nofollow">http://www.egeek.me/2015/04/12/jenkins-setting-up-ios-code-signing/</a></p>
|
Finding characters with spaces <p>I was trying last week to find parts of a text containing specific words delimited by punctuation characters. That works well.</p>
<pre><code>[^.?!:]*\b(why|how)\b[^.?!]*[.?!]
</code></pre>
<p>On the following sentence <code>"How did you do it? bla bla bla! why did you do it?"</code>, it's giving me the following output : </p>
<pre><code>"How did you do it?"
"why did you do it?"
</code></pre>
<p>Now I am trying to add the hyphen character : I want to detect if there is an hyphen with spaces around (a new sentence delimiter):</p>
<pre><code>"The man went walking upstairs - why was he there?
</code></pre>
<p>That would return me : <code>"why was he there?"</code></p>
<p>It would follow the following rules:</p>
<pre><code>hello - bye -> this would be the only one to be matched
hello-bye -> not matched
hello -bye -> not matched
hello- bye -> not matched
</code></pre>
<p>Using the negation, I tried to add that part : </p>
<pre><code>[^.?!:\\s\\-\\s] => ignore everything that ends with a "." or a "?" or a "!" or a ":" or a " - "
</code></pre>
<p>I doesn't work, but as I am pretty bad using regex, I am probably missing something obvious.</p>
<pre><code>var regex = /[^.?!:\\s\\-\\s]*\b(why|how)\b[^.?!]*[.?!]/igm
var text = "Here I am - why did you want to see me?"
var match;
while ((match = regex.exec(text)) != null) {
console.log(match);
}
</code></pre>
<p>Output : </p>
<pre><code>Here I am - why did you want to see me?
</code></pre>
<p>Expected output : </p>
<pre><code>why did you want to see me?
</code></pre>
| <p><code>[ ]</code> is always a character class, which means that at one position, you can match <em>one</em> character. The "negation" in your example is in fact probably not even doing what you thing it does. </p>
<p>What you probably want to match is <em>either the beginning of a string, the end of a sentence, or a dash with two spaces around</em>, so just replace it with <code>(^|[.?!]| - )\b((why|how)...etc)</code>. You will need some post processing of the result, as JavaScript does not support look-behind assertions as far as I know.</p>
|
Sqlite database gives me warnings <p>I have a sqlite database and I use System.Data.SQLite in my C# project.</p>
<p>My request is :</p>
<pre><code>SELECT d1.* FROM DYN_table as d1 INNER JOIN ( SELECT id_bill, ordre_phase, type, MAX(valeur) maximum FROM DYN_table WHERE id_customer=347 AND type IN (1,5,2) GROUP BY id_bill, ordre_phase, type) as d2 ON d1.type = d2.type AND d1.valeur = d2.maximum AND d1.ordre_phase=d2.ordre_phase AND d1.id_bill=d2.id_bill WHERE d1.id_customer=347 AND d1.type IN (1,5,2)
</code></pre>
<p>The request is working but I have the following Warning :</p>
<pre><code>SQLite warning (284): automatic index on sqlite_sq_1E5A8EC0(id_bill)
</code></pre>
<p>When I try my request using "EXPLAIN QUERY PLAN" I see the last step is :</p>
<pre><code>SEARCH SUBQUERY 1 AS d2 USING AUTOMATIC COVERING INDEX (id_bill=? AND ordre_phase=? AND type=?)
</code></pre>
<p>But there is an index for id_bill in this table, all the indexes I have :
-Primary Key : id_player, id_bill, ordre_phase, type
-type
-id_player
-ordre_phase
-id_competition</p>
<p>I've tried to create an index with id_bill, ordre_phase and type but still the same "USING Automatic covering index" in the analyze.</p>
<p>Am I missing something ? </p>
| <p>The database creates a temporary index on the column <code>id_bill</code> of the subquery <code>d2</code>.</p>
<p>It is not possible to create this index explicitly, unless you explicitly create a (temporary) table for this subquery.</p>
<p>Ignore the warning.
If you need to optimize this query, consider rewriting it so that it is not necessary to do a join with such a complex subquery, i.e., so that <a href="http://www.sqlite.org/optoverview.html#flattening" rel="nofollow">subquery flattening</a> is possible.</p>
|
Swift adding multiple images to a single UIButton <p><a href="https://i.stack.imgur.com/r6Hvw.png" rel="nofollow"><img src="https://i.stack.imgur.com/r6Hvw.png" alt="enter image description here"></a>In my app, I would like to add multiple images on a single <code>UIButton</code>.</p>
<p>This is what I have now:</p>
<pre><code> NextButton = UIButton(frame: CGRect(x: width*0, y: height*0.55, width: width*0.95, height: height*0.05))
NextButton.addTarget(self, action: #selector(OnNextPressed), for: .touchUpInside)
NextButton.isExclusiveTouch = true
NextButton.setTitle("ButtonText", for: UIControlState())
NextButton.setTitleColor(UIColor(red:0, green:0, blue:0, alpha:1.0), for: UIControlState())
NextButton.setBackgroundImage(UIImage(named: "ButtonOutline"), for: .normal)
view.addSubview(NextButton)
</code></pre>
<p>I would like a 2nd image as an arrow pointing to the next page.
thanks in advance :)</p>
<p>the rest of the button works but I don't know how to make the arrow appear</p>
| <p>I fixed the problem here is the new code:</p>
<pre><code> let screenSize: CGRect = UIScreen.main.bounds
let width = screenSize.width
let height = screenSize.height
NextButton = UIButton(frame: CGRect(x: width*0, y: height*0.55, width: width*0.95, height: height*0.05))
NextButton.addTarget(self, action: #selector(OnNextPressed), for: .touchUpInside)
NextButton.isExclusiveTouch = true
NextButton.setTitle("ButtonText", for: UIControlState())
NextButton.setTitleColor(UIColor(red:0, green:0, blue:0, alpha:1.0), for: UIControlState())
NextButton.setBackgroundImage(UIImage(named: "ButtonOutline"), for: .normal)
NextButton.setImage(UIImage(named: "arrow_next"), for: UIControlState())
NextButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, width*0.7)
view.addSubview(NextButton)
</code></pre>
<p>by simply adding setImage to the code i could create a second image on top of the BackgroundImage. then by suing imageEdgeInsets i aligned the image on the button.</p>
|
Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force NOT WORKING <p>I'm trying to setup Node.js and Python on my work laptop.</p>
<p>I've installed Node and Python successfully.</p>
<p>When I'm trying to update my npm using this command in Windows PowerShell:</p>
<pre><code>Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
npm install -g npm-windows-upgrade
npm-windows-upgrade
</code></pre>
<p>While setting execution policy to unrestricted it throws the error in the image below and says "Cannot run scripts on this system".</p>
<p><a href="https://i.stack.imgur.com/5xzTv.png" rel="nofollow"><img src="https://i.stack.imgur.com/5xzTv.png" alt="Please check image"></a></p>
<p>I did run <code>Get-ExecutionPolicy -List</code>. It shows a table:</p>
<pre> Scope ExecutionPolicy
----- ---------------
MachinePolicy RemoteSigned
UserPolicy Undefined
Process Undefined
CurrentUser Unrestricted
LocalMachine Unrestricted</pre>
<p>How do I make it run scripts?</p>
<p>My OS: Windows 7 Enterprise 64 bit.</p>
| <p>The error message show the root of error:</p>
<pre><code> Window powershell updated your execution policy suceffully, but the
setting is overridden by a policy defined at a more specific scope.
Due to the override, your shell will retain its current effective
execution policy of remoteassigned.
</code></pre>
<p>So, there is a group policy setting for the current user assigned to remoteassigned and can't be changed by the command.</p>
<p>Modify the setting in the group policy as in the given steps:</p>
<pre><code> run: gpedit.msc
</code></pre>
<p>In the left tree, select:</p>
<p>user configuration -> administrative templates->
windows components -> windows powershell</p>
<p>turn on script execution -> enabled
As in the figure:
<a href="https://i.stack.imgur.com/YVGLB.png" rel="nofollow"><img src="https://i.stack.imgur.com/YVGLB.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/6EUqG.png" rel="nofollow"><img src="https://i.stack.imgur.com/6EUqG.png" alt="enter image description here"></a>
If your machine is a member of domain and you log as a domain user, there may be a restriction for modification. </p>
<p>In that case contact the Domain administrator to modify your group policy.</p>
|
add document to a groups one drive usign microsofts graph api <p>I'm trying to find a way to add documents to a group in Office Online via the Microsoft graph api. I see example in the documentation (<a href="http://graph.microsoft.io/en-us/docs/api-reference/v1.0/resources/drive" rel="nofollow">http://graph.microsoft.io/en-us/docs/api-reference/v1.0/resources/drive</a>) to get items in a groups one drive but no way to post or put documents to a groups one drive.</p>
| <p>Group drive contains <code>root</code> and <code>items</code> navigation properties just like regular drive resource.
Just like you can create new files on the drive, you should be able to use similar <a href="http://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_post_children" rel="nofollow">API</a> on group drive as well. </p>
<p><code>POST /groups/{group-id}/drive/items/{parent-item-id}/children</code>. </p>
<p>Note: By default, all navigation properties are read-only, which means that you can't <code>patch</code> to the resource and update the navigation property. </p>
|
Ng-repeat with ng-hide OR do the job in the controller for improved performance? <p>The question is simple but for sure i believe it provides added value to an application development.</p>
<p>In terms of performance is it better to use:</p>
<pre><code>ng-repeat="r in roads", ng-hide="r.distance > 1000"
</code></pre>
<p>OR is it better to push items in an array in the controller, like this:</p>
<pre><code>for (var i in $scope.roads) {
var road = $scope.roads[i];
if (road.distance <= 1000) $scope.roadsToShow.push(road);
}
</code></pre>
<p>and then use, just the ng-repeat like so?</p>
<pre><code>ng-repeat="r in roadsToShow"
</code></pre>
<p>Which is considered best practice in terms of better performance? Imagine that the objects in the arrays are more than 1000.</p>
| <p>It is better to filter the items of the array in the controller or better on the server instead of hiding them after having rendered them. If you filter the array before displaying it the browser don't need to render the DOM associated to the item and then spending time to hiding it. Keep in mind that using <code>ng-hide</code> applies the CSS class <code>display: none</code> to the element, so the node exists but is not visible.</p>
|
Transforming one column into multiple ones in a Spark Dataframe <p>I have a big dataframe (1.2GB more or less) with this structure:</p>
<pre>
+---------+--------------+------------------------------------------------------------------------------------------------------+
| country | date_data | text |
+---------+--------------+------------------------------------------------------------------------------------------------------+
| "EEUU" | "2016-10-03" | "T_D: QQWE\nT_NAME: name_1\nT_IN: ind_1\nT_C: c1ws12\nT_ADD: Sec_1_P\n ...........\nT_R: 45ee" |
| "EEUU" | "2016-10-03" | "T_D: QQAA\nT_NAME: name_2\nT_IN: ind_2\nT_C: c1ws12\nT_ADD: Sec_1_P\n ...........\nT_R: 46ee" |
| . | . | . |
| . | . | . |
| "EEUU" | "2016-10-03" | "T_D: QQWE\nT_NAME: name_300000\nT_IN: ind_65\nT_C: c1ws12\nT_ADD: Sec_1_P\n ...........\nT_R: 47aa" |
+---------+--------------+------------------------------------------------------------------------------------------------------+
</pre>
<p>The number of rows is 300.000 and "text" field is a string of 5000 characters approximately.</p>
<p>I would like to separate the field âtextâ in this new fields:</p>
<pre>
+---------+------------+------+-------------+--------+--------+---------+--------+------+
| country | date_data | t_d | t_name | t_in | t_c | t_add | ...... | t_r |
+---------+------------+------+-------------+--------+--------+---------+--------+------+
| EEUU | 2016-10-03 | QQWE | name_1 | ind_1 | c1ws12 | Sec_1_P | ...... | 45ee |
| EEUU | 2016-10-03 | QQAA | name_2 | ind_2 | c1ws12 | Sec_1_P | ...... | 45ee |
| . | . | . | . | . | . | . | . | |
| . | . | . | . | . | . | . | . | |
| . | . | . | . | . | . | . | . | |
| EEUU | 2016-10-03 | QQWE | name_300000 | ind_65 | c1ws12 | Sec_1_P | ...... | 47aa |
+---------+------------+------+-------------+--------+--------+---------+--------+------+
</pre>
<p>Currently, I´m using regular expressions to solve this problem. Firstly, I write the regular expresions and create a function to extract individual fields from text (90 regular expressions in total):</p>
<pre><code>val D_text = "((?<=T_D: ).*?(?=\\\\n))".r
val NAME_text = "((?<=nT_NAME: ).*?(?=\\\\n))".r
val IN_text = "((?<=T_IN: ).*?(?=\\\\n))".r
val C_text = "((?<=T_C: ).*?(?=\\\\n))".r
val ADD_text = "((?<=T_ADD: ).*?(?=\\\\n))".r
.
.
.
.
val R_text = "((?<=T_R: ).*?(?=\\\\n))".r
//UDF function:
def getFirst(pattern2: scala.util.matching.Regex) = udf(
(url: String) => pattern2.findFirstIn(url) match {
case Some(texst_new) => texst_new
case None => "NULL"
case null => "NULL"
}
)
</code></pre>
<p>Then, I create a new Dataframe (tbl_separate_fields ) as a result of applying the function with a regular expression to extract every new field from text. </p>
<pre><code>val tbl_separate_fields = hiveDF.select(
hiveDF("country"),
hiveDF("date_data"),
getFirst(D_text)(hiveDF("texst")).alias("t_d"),
getFirst(NAME_text)(hiveDF("texst")).alias("t_name"),
getFirst(IN_text)(hiveDF("texst")).alias("t_in"),
getFirst(C_text)(hiveDF("texst")).alias("t_c"),
getFirst(ADD_text)(hiveDF("texst")).alias("t_add"),
.
.
.
.
getFirst(R_text)(hiveDF("texst")).alias("t_r")
)
</code></pre>
<p>Finally, I insert this dataframe into a Hive table:</p>
<pre><code>tbl_separate_fields.registerTempTable("tbl_separate_fields")
hiveContext.sql("INSERT INTO TABLE TABLE_INSERT PARTITION (date_data) SELECT * FROM tbl_separate_fields")
</code></pre>
<p>This solution lasts for 1 hour for the entire dataframe so I wish to optimize and reduce the execution time. Is there any solution? </p>
<p>We are using <strong>Hadoop 2.7.1</strong> and <strong>Apache-Spark 1.5.1</strong>. The configuration for Spark is:</p>
<pre><code>val conf = new SparkConf().set("spark.storage.memoryFraction", "0.1")
val sc = new SparkContext(conf)
val hiveContext = new org.apache.spark.sql.hive.HiveContext(sc)
</code></pre>
<p>Thanks in advance.</p>
<p><strong>EDIT DATA:</strong></p>
<pre>
+---------+--------------+------------------------------------------------------------------------------------------------------+
| country | date_data | text |
+---------+--------------+------------------------------------------------------------------------------------------------------+
| "EEUU" | "2016-10-03" | "T_D: QQWE\nT_NAME: name_1\nT_IN: ind_1\nT_C: c1ws12\nT_ADD: Sec_1_P\n ...........\nT_R: 45ee" |
| "EEUU" | "2016-10-03" | "T_NAME: name_2\nT_D: QQAA\nT_IN: ind_2\nT_C: c1ws12 ...........\nT_R: 46ee" |
| . | . | . |
| . | . | . |
| "EEUU" | "2016-10-03" | "T_NAME: name_300000\nT_ADD: Sec_1_P\nT_IN: ind_65\nT_C: c1ws12\n ...........\nT_R: 47aa" |
+---------+--------------+------------------------------------------------------------------------------------------------------+
</pre>
| <p>Using regular expressions in this case is slow and also fragile.</p>
<p>If you know that all records have the same structure, i.e. that all "text" values have the same <em>number</em> and <em>order</em> of "parts", the following code would work (for any number of columns), mainly taking advantage of the <code>split</code> function in <code>org.apache.spark.sql.functions</code>:</p>
<pre><code>import org.apache.spark.sql.functions._
// first - split "text" column values into Arrays
val textAsArray: DataFrame = inputDF
.withColumn("as_array", split(col("text"), "\n"))
.drop("text")
.cache()
// get a sample (first row) to get column names, can be skipped if you want to hard-code them:
val sampleText = textAsArray.first().getAs[mutable.WrappedArray[String]]("as_array").toArray
val columnNames: Array[(String, Int)] = sampleText.map(_.split(": ")(0)).zipWithIndex
// add Column per columnName with the right value and drop the no-longer-needed as_array column
val withValueColumns: DataFrame = columnNames.foldLeft(textAsArray) {
case (df, (colName, index)) => df.withColumn(colName, split(col("as_array").getItem(index), ": ").getItem(1))
}.drop("as_array")
withValueColumns.show()
// for the sample data I created,
// with just 4 "parts" in "text" column, this prints:
// +-------+----------+----+------+-----+------+
// |country| date_data| T_D|T_NAME| T_IN| T_C|
// +-------+----------+----+------+-----+------+
// | EEUU|2016-10-03|QQWE|name_1|ind_1|c1ws12|
// | EEUU|2016-10-03|QQAA|name_2|ind_2|c1ws12|
// +-------+----------+----+------+-----+------+
</code></pre>
<p><strong>Alternatively</strong>, if the assumption above is not true, you can use a UDF that converts the text column into a <code>Map</code>, and then perform a similar <code>reduceLeft</code> operation on the hard-coded list of desired columns:</p>
<pre><code>import sqlContext.implicits._
// sample data: not the same order, not all records have all columns:
val inputDF: DataFrame = sc.parallelize(Seq(
("EEUU", "2016-10-03", "T_D: QQWE\nT_NAME: name_1\nT_IN: ind_1\nT_C: c1ws12"),
("EEUU", "2016-10-03", "T_D: QQAA\nT_IN: ind_2\nT_NAME: name_2")
)).toDF("country", "date_data", "text")
// hard-coded list of expected column names:
val columnNames: Seq[String] = Seq("T_D", "T_NAME", "T_IN", "T_C")
// UDF to convert text into key-value map
val asMap = udf[Map[String, String], String] { s =>
s.split("\n").map(_.split(": ")).map { case Array(k, v) => k -> v }.toMap
}
val textAsMap = inputDF.withColumn("textAsMap", asMap(col("text"))).drop("text")
// for each column name - lookup the value in the map
val withValueColumns: DataFrame = columnNames.foldLeft(textAsMap) {
case (df, colName) => df.withColumn(colName, col("textAsMap").getItem(colName))
}.drop("textAsMap")
withValueColumns.show()
// prints:
// +-------+----------+----+------+-----+------+
// |country| date_data| T_D|T_NAME| T_IN| T_C|
// +-------+----------+----+------+-----+------+
// | EEUU|2016-10-03|QQWE|name_1|ind_1|c1ws12|
// | EEUU|2016-10-03|QQAA|name_2|ind_2| null|
// +-------+----------+----+------+-----+------+
</code></pre>
|
Check array so that no duplicates can be added <p>Inside my <code>getNearestMeeting</code> method it seems to allow array with the same <code>key</code> and same <code>value</code>.</p>
<p>I'm wanting to check to see if there is <code>key</code> already and <code>meeting_id</code> value. As you see down below that the result from my code so far returns two keys == <code>6</code> and they have the same <code>meeting_id</code> == <code>1812</code>.</p>
<p>What am I doing wrong?</p>
<pre><code>$pupils = array("parent" => array( array ("pupil_name" => "Daniel", "pupil_id" => "5", "pupil_grade" => "87"),
array ("pupil_name" => "Daniel", "pupil_id" => "5", "pupil_grade" => "86"),
array ("pupil_name" => "Callum", "pupil_id" => "6", "pupil_grade" => "87")
));
$meetings = array( array("slot_id" => "1", "meeting_id" => "1812", "startTime" => "2016-10-07 14:30:00",
"endTime" => "2016-10-07 14:35:00", "grade_id" => "87"),
array("slot_id" => "2", "meeting_id" => "1812", "startTime" => "2016-10-07 14:35:00",
"endTime" => "2016-10-07 14:40:00", "grade_id" => "87"),
array("slot_id" => "3", "meeting_id" => "1812", "startTime" => "2016-10-07 14:40:00",
"endTime" => "2016-10-07 14:45:00", "grade_id" => "87"),
array("slot_id" => "4", "meeting_id" => "1813", "startTime" => "2016-10-07 15:05:00",
"endTime" => "2016-10-07 15:10:00", "grade_id" => "-1"),
array("slot_id" => "6", "meeting_id" => "1813", "startTime" => "2016-10-07 15:10:00",
"endTime" => "2016-10-07 15:15:00", "grade_id" => "-1"),
array("slot_id" => "9", "meeting_id" => "1813", "startTime" => "2016-10-07 15:20:00",
"endTime" => "2016-10-07 15:25:00", "grade_id" => "-1"),
array("slot_id" => "10", "meeting_id" => "1813", "startTime" => "2016-10-07 15:30:00",
"endTime" => "2016-10-07 15:35:00", "grade_id" => "88"),
array("slot_id" => "11", "meeting_id" => "1813", "startTime" => "2016-10-07 15:40:00",
"endTime" => "2016-10-07 15:45:00", "grade_id" => "88"),
array("slot_id" => "17", "meeting_id" => "1813", "startTime" => "2016-10-07 15:50:00",
"endTime" => "2016-10-07 15:50:00", "grade_id" => "88")
);
function in_array_r($array, $key, $val) {
foreach ($array as $item) {
if (key($item) == $key && isset($item[$key]) && $item[$key]["meeting_id"] == $val)
return true;
else
return false;
}
}
function getNearestMeeting($meetings){
global $pupils;
$ignore = array();
$current_pupil_id = "5";
$current_pupil_grade_id = "87";
foreach($meetings as $item){
if($current_pupil_grade_id === $item["grade_id"]){
$earliest = strtotime($item["endTime"]);
$ignore[$current_pupil_id][] = array("meeting_id" => $item["meeting_id"], "endTime" => $item["endTime"]);
break;
}
}
$counter = 0;
foreach($pupils["parent"] as $item){
$counter++;
foreach($meetings as $item2){
$lastArray = end(end($ignore));
$previousTime = strtotime($lastArray["endTime"]);
if(!in_array_r($ignore, $item["pupil_id"], $item2["meeting_id"])) {
if(isset($previousTime) && strtotime($item2["startTime"]) >= $previousTime && strtotime($item2["startTime"]) >= $earliest){
if($item["pupil_grade"] === $item2["grade_id"]){
$ignore[$item["pupil_id"]][] = array("meeting_id" => $item2["meeting_id"], "endTime" => $item2["endTime"]);
}
}
}
}
}
print_r($ignore);
}
getNearestMeeting($meetings);
</code></pre>
<p>result from <code>print_r($ignore);</code>:</p>
<pre><code>Array
(
[0] => Array
(
[5] => Array
(
[meeting_id] => 1812
[endTime] => 2016-10-07 14:35:00
)
)
[1] => Array
(
[6] => Array
(
[meeting_id] => 1812
[endTime] => 2016-10-07 14:40:00
)
)
[2] => Array
(
[6] => Array
(
[meeting_id] => 1812
[endTime] => 2016-10-07 14:45:00
)
)
)
</code></pre>
| <p><a href="http://chat.stackoverflow.com/rooms/11/conversation/bug-fix-discussion-between-sean-and-chris-beckett">After the discussion in the Stack Overflow PHP Chat</a>, the problems identified were the following:</p>
<ol>
<li>The <code>$ignore</code> array was structured strangely, if a pupil had multiple meetings it would create multiple top-level arrays, when it should have just used one which referenced that particular pupil.</li>
<li>The <code>in_array_r</code> function was structured incorrectly.</li>
</ol>
<p>The end fixes resulted in the following changes:</p>
<h3>For #1:</h3>
<p>Additions to the <code>$ignore</code> array were changed to:</p>
<pre><code>$ignore[$item["pupil_id"]][] = array("meeting_id" => $item2["meeting_id"], "endTime" => $item2["endTime"]);
</code></pre>
<p>With an additional check to ensure <code>$ignore[$item["public_id"]]</code> is an array, and if it wasn't then to create it before appending a new item to it.</p>
<h3>For #2:</h3>
<p>The <code>in_array_r</code> function was changed to reflect the new array structure:</p>
<pre><code>function in_array_r($array, $key, $val) {
if(array_key_exists($key, $array)){
foreach ($array[$key] as $item) {
if ($item["meeting_id"] === $val)
return true;
else
return false;
}
}
}
</code></pre>
|
html page failed to show css background-image <p>I`m working on a VS2010 ASP.NET Web Application project, and I`ve added a html page to it. The problem is when starting debug(F5) , this page fail to show some icons which were set in css file , but when opening html page directly, those background-image is showing perfectly.</p>
<p>css codes are:</p>
<pre><code>.leaflet-draw-toolbar a {
background-image: url('images/spritesheet.png');
background-image: linear-gradient(transparent,transparent),url('images/spritesheet.svg');
background-repeat: no-repeat;
background-size: 270px 30px;}
</code></pre>
<p>and related javascripts are:</p>
<pre><code>var drawnItems = L.featureGroup().addTo(map);
map.addControl(new L.Control.Draw({
edit: {
featureGroup: drawnItems,
poly: {
allowIntersection: false
}
},
draw: {
polygon: {
allowIntersection: false,
showArea: true
}
}
}));
</code></pre>
<p><a href="https://i.stack.imgur.com/NpDsf.png" rel="nofollow">debug</a></p>
<p><a href="https://i.stack.imgur.com/Xqx06.png" rel="nofollow">open directly</a></p>
<p>I think maybe there are some web-configs limiting the access to resources.
Dose Anybody know how to deal with it? </p>
<p>Thx!</p>
| <p>I changed css codes and it worked:</p>
<pre><code>.leaflet-draw-toolbar a {
background-image: linear-gradient(transparent, transparent), url('images/spritesheet.svg');
background-image: url('images/spritesheet.png');
background-repeat: no-repeat;
background-size: 270px 30px;}
</code></pre>
<p>As you see , in the former codes background-image use svg over png , now I`ve changed to use png over svg. </p>
<p>So the only different lies between svg and png , and I`m gonna learn details about svg. I still guess it has something to do with the way browser interpret svg which is given in a debug mode website.</p>
|
Can a member variable (attribute) reside in a register in C++? <p>A local variable (say an int) can be stored in a processor register, at least as long as its address is not needed anywhere. Consider a function computing something, say, a complicated hash:</p>
<pre><code>int foo(int const* buffer, int size)
{
int a; // local variable
// perform heavy computations involving frequent reads and writes to a
return a;
}
</code></pre>
<p>Now assume that the buffer does not fit into memory. We write a class for computing the hash from chunks of data, calling <code>foo</code> multiple times:</p>
<pre><code>struct A
{
void foo(int const* buffer, int size)
{
// perform heavy computations involving frequent reads and writes to a
}
int a;
};
A object;
while (...more data...)
{
A.foo(buffer, size);
}
// do something with object.a
</code></pre>
<p>The example may be a bit contrived. The important difference here is that <code>a</code> was a local variable in the free function and now is a member variable of the object, so the state is preserved across multiple calls.</p>
<p>Now the question: would it be legal for the compiler to load <code>a</code> at the beginning of the <code>foo</code> method into a register and store it back at the end? In effect this would mean that a second thread monitoring the object could never observe an intermediate value of <code>a</code> (synchronization and undefined behavior aside). Provided that speed is a major design goal of C++, this seems to be reasonable behavior. Is there anything in the standard that would keep a compiler from doing this? If no, do compilers actually do this? In other words, can we expect a (possibly small) performance penalty for using a member variable, aside from loading and storing it once at the beginning and the end of the function?</p>
<p>As far as I know, the C++ language itself does not even specify what a register is. However, I think that the question is clear anyway. Whereever this matters, I appreciate answers for a standard x86 or x64 architecture.</p>
| <p>The compiler can do that if (and only if) it can prove that nothing else will access <code>a</code> during <code>foo</code>'s execution.<br>
That's a non-trivial problem in general; I don't think any compiler attempts to solve it. </p>
<p>Consider the (even more contrived) example</p>
<pre><code>struct B
{
B (int& y) : x(y) {}
void bar() { x = 23; }
int& x;
};
struct A
{
int a;
void foo(B& b)
{
a = 12;
b.bar();
}
};
</code></pre>
<p>Looks innocent enough, but then we say</p>
<pre><code>A baz;
B b(baz.a);
baz.foo(b);
</code></pre>
<p>"Optimising" this would leave <code>12</code> in <code>baz.a</code>, not <code>23</code>, and that is clearly wrong. </p>
|
Using Multiple Spring Eureka Discovery Services <p>I have a user request to allow a support tool, which uses Spring Cloud Services, to display a set of links to the same support tool that would exist multiple environments (Dev, Test 1, Test 2, Prod). I am currently connecting via Eureka Server and registering in each of these environments. The current change request is to have a drop down of links of the support tool in each of these environments. Now, I know I can hard code the url of each instance of the support tool that exists in each environment but I would rather use the DiscoveryClient instance from Eureka to gather that information but it looks like the DiscoveryClient (that is autowired) can only connect to instance at time. Not even sure if multiple DiscoveryClients can be used to do this or if what I am wanting is even possible. Any suggestions would be greatly appreciated.</p>
<p>Thanks in advance!</p>
| <p>Correct, <code>DiscoveryClient</code> only connects to one eureka server at a time. You would have to create each <code>DiscoveryClient</code> manually. It would probably be easier to use the eureka <a href="https://github.com/Netflix/eureka/wiki/Eureka-REST-operations" rel="nofollow">http api</a>.</p>
|
Do I need to specifically seperate out css and js when using plunker <p>This script renders ok on our local webserver but when added to <code>plunker</code> nothing is being rendered.</p>
<p>Am I allowed to embed javascript in the html file in plunker - or do I need to explicitly move it to .js files?</p>
<p>To reference another file in plunker do I just supply the file name, like so? ...</p>
<pre><code>var pieDataCSV = "pie.csv";
var barDataCSV = "bar.csv";
var lineDataCSV = "line.csv";
</code></pre>
<p>Here is the plunker I am referring to: <a href="https://plnkr.co/edit/QDHVKNxuHAC1TSk1gk4s?p=preview" rel="nofollow">https://plnkr.co/edit/QDHVKNxuHAC1TSk1gk4s?p=preview</a></p>
| <p>In your plnkr, you need to change the javascript reference from</p>
<pre><code><script src="http://d3js.org/d3.v2.js"></script>
</code></pre>
<p>to</p>
<pre><code><script src="https://d3js.org/d3.v2.js"></script>
</code></pre>
<p>to avoid the following error.</p>
<pre><code>Mixed Content: The page at 'https://plnkr.co/edit/QDHVKNxuHAC1TSk1gk4s?p=preview' was loaded over HTTPS, but requested an insecure script 'http://d3js.org/d3.v2.js'. This request has been blocked; the content must be served over HTTPS.
</code></pre>
|
Netbeans 8.1 & Java : Messed up output when error is thrown <p>I noticed that Netbeans messes up the entire output once an error is thrown. It makes the output look like this incomprehensive mess:</p>
<pre><code>Pushing elements onto doubleStack
1.1 2.2 3.3 4.4 5.5 6.6
Exceptions.FullStackException: Stack is full, cannot push 6.6
Popping elements from doubleStack
5.5 4.4 3.3 2.2 1.1
at domein.Stack.push(Stack.java:37)
Pushing elements onto integerStack
at StackApplicatie2.testPush(StackApplicatie2.java:40)
1 2 3 4 5 6 7 8 9 10 11
at StackApplicatie2.testStacks(StackApplicatie2.java:24)
Popping elements from integerStack
at StackApplicatie2.main(StackApplicatie2.java:75)
<etc. â¦>
</code></pre>
<p>instead of what one would expect:</p>
<pre><code>Pushing elements onto doubleStack
1.1 2.2 3.3 4.4 5.5 6.6
Exceptions.FullStackException: Stack is full, cannot push 6.6
at domein.Stack.push(Stack.java:37)
at StackApplicatie2.testPush(StackApplicatie2.java:40)
at StackApplicatie2.testStacks(StackApplicatie2.java:24)
at StackApplicatie2.main(StackApplicatie2.java:75)
Popping elements from doubleStack
5.5 4.4 3.3 2.2 1.1
Pushing elements onto integerStack
1 2 3 4 5 6 7 8 9 10 11
Popping elements from integerStack
<etc. â¦>
</code></pre>
<p>I was just wondering: is this normal for Netbeans 8.1 to give such a weird ouput or not?</p>
| <p>When you use <code>exception.printStackTrace()</code>, then the stack trace is printed to <code>System.err</code>, your own messages are printed to <code>System.out</code> (I guess). Both are buffered streams, and only when those streams are flushed (buffer size reached, newlines, etc), the output appears at the destination.</p>
<p>In a simple terminal applications, both streams are directed at the console, however the buffering of both streams has the effect that flushes can interleave, and therefor the output of both streams can get mixed up.</p>
<p>This, btw, is not specific to Netbeans.</p>
<p>If for some reasons you really want them in order, and don't want to write the exception stacktrace to the error stream, then you could use <code>exception.printStackTrace(System.out)</code>. However be aware that it is unusual to do so; exceptions should be exceptional and should usually not go to the 'standard output'.</p>
|
Check how many users are using application on network? <p>I have a winform application on my network drive that many users are using. Is there a way to track how many users either by count or by their domain username who is using the application? I've look around and can't find any starting point on this subject. Any help is appreicated. Thanks.</p>
<p>EDIT:</p>
<p>So I decided on application load to save a text document with the domain username as filename and when the user exit application to delete the text document. Within the application i have a listbox that gets the text files in the directory and shows who is logged in. Easy and simply. The End.</p>
| <p>Take a look at this documentation, you will be able to see how many users and which users have your winform application open. </p>
<p><a href="https://technet.microsoft.com/en-us/library/cc725689%28v=ws.11%29.aspx?f=255&MSPPError=-2147217396" rel="nofollow">https://technet.microsoft.com/en-us/library/cc725689%28v=ws.11%29.aspx?f=255&MSPPError=-2147217396</a></p>
<p>It's a starting point :)</p>
|
How to avoid ValueWidth with AmCharts? <p>I'm using a 100% Stacked Column Chart in a website for a client.</p>
<p>In the legend, we have the value of the variable we're hovering. It gave : </p>
<p>[Color of the variable] [Name of the variable] [Value of the variable]</p>
<p>However, in some cases, when the value of the variable is too big, it's on the name of this variable.</p>
<p>Does someone know a way to avoid this problem without using <strong>valueWidth</strong> ? Indeed we have multiple legends, and this way of working is not effective when name of variables haven't the same size.</p>
<p>thanks in advance !</p>
<p>Best regards,</p>
| <p>You could try playing around with the equalWidths and horizontalGap properties, like in this demo:
<a href="https://codepen.io/team/amcharts/pen/1acd9511369ff5f6d89e447be0b8f191" rel="nofollow">https://codepen.io/team/amcharts/pen/1acd9511369ff5f6d89e447be0b8f191</a></p>
<pre><code>"legend": {
"position": "bottom",
"equalWidths": false,
"horizontalGap": 50,
...
}
</code></pre>
<p>Not sure of your setup, but there's a list of other legend props and options at <a href="https://docs.amcharts.com/3/javascriptcharts/AmLegend" rel="nofollow">https://docs.amcharts.com/3/javascriptcharts/AmLegend</a>.</p>
|
Avoid a Dictionary<string, T> from being bound to all query string parameters <p>In a C# ASP.NET MVC project, I have an action that receives a <code>Dictionary<string, T></code> (<code>T</code> type is not really important, I think) as a parameter. I also want that parameter to be optional, with a default value of <code>null</code>. </p>
<p>However, if I don't specify that parameter when calling the action, I get it nonetheless, a dictionary filled with all query string key-value pairs. </p>
<p>The way I understand it, the MVC framework tries to bound the parameter to the query string, and because it is a dictionary with string keys the collection of key-value pairs in the query string is suitable data for the databinding mechanism. </p>
<p>But I need to be able to receive a <code>null</code> parameter anyway. And I am not allowed to explictly pass <code>null</code> in the route values either. How could I prevent the query string data binding from happening?</p>
| <p>Instead of defining you model param as Dictionary create a model that would require more explicit binding</p>
<p>Something like</p>
<pre><code> ModelClass {
string SomeName {get;set;}
T Internal {get;set;}
}
public ActionResult YourAction(ModelClass boundInstance){}
</code></pre>
<p>This would certainly not get bound to random query string parameters. Do note however any model objects defined as optional parameters will never be null, they will just have empty data, even in your case if there were no query string parameters you would still end up with a constructed but empty Dic(). The default model binder calls any parameters empty constructor before attempting to bind data so the object is constructed even if no data can be bound to it.</p>
<p>Other option - If your only planning on getting the Dictionary data from a post you can add the attribute [FromBody] to the binding</p>
<pre><code>public ActionResult YourAction([FromBody]Dictionary<string, T> boundInstance){}
</code></pre>
<p>Rant: Avoid using generic collection types as action parameters and you can avoid these issue entirely.</p>
|
Nifi-1.0.0 and Crate.IO <p>Crate database offers a jdbc driver through which I should be able to connect to Crate from Nifi using DBCPConnectionPool controller service. So I did that, I get a connection, the ConvertJSONToSQL processor is able to get the columns from the Crate database but when I get to the PUTSql processor I get the following error:</p>
<pre><code>FlowFileHandlingException: transfer relationship not specified
</code></pre>
<p>The thing is that I have a SUCCESS, FAILURE, RETRY relationship defined. It just throws a ProcessException in the onTrigger() method.</p>
<p>Any ideas how can I make it work ?
As soon as the jdbc driver is compatible it should work, but ... </p>
| <p>I believe this is a bug in PutSQL that is hiding an issue either in the JDBC configuration, SQL statement, or something else. Using the standalone JDBC driver with valid SQL INSERT statements, I was able to PutSQL working with Crate.</p>
<p>Can you double-check your connection information and SQL statement(s)? Also if you can reproduce and want to share the SQL and/or connection info (JDBC URL, e.g.), please feel free, it could help get to the bottom of the PutSQL bug that is hiding another issue.</p>
|
Realm + NSClassFromString <p>Hi everyone and thank you for be reading this. </p>
<p>I am new with Realm and I am stucked with a function that I can't figure out how to build. My intention is to have one function called <code>func delete(className:String, id:Int){</code> that should be able to delete any object of any Realm class by its ID. The inner code of the function is:</p>
<pre><code>func delete(objectNameV:String, id:Int){
let theClass = NSClassFromString(objectNameV)
// Get the default Realm
let realm = try! Realm()
let queryResult = realm.objects(theClass as! Object.Type).filter("id = \(id)")
try! realm.write {
realm.delete(queryResult)
}
}
</code></pre>
<p>But the fact is that <code>let theClass = NSClassFromString(objectNameV)</code> it's allways NIL. </p>
<p>Any help is appreciated, <strong>i just need a function that given a realm classname and the id from an object of that class can delete it</strong>!</p>
<p>Realm version: 2.0.1
Xcode version: 8</p>
| <p><a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/WritingSwiftClassesWithObjective-CBehavior.html" rel="nofollow">According to the Apple developer docs</a>, classes in Swift are namespaced by their module names. So it's not sufficient to simply write the class name; you must also include their module name as well.</p>
<p>The example Apple used on their website is:</p>
<pre><code>let myPersonClass: AnyClass? = NSClassFromString("MyGreatApp.Person")
</code></pre>
|
Replace semicolon between letters in PHP <p>I have the following issue, I need to replace all semicolons inside a string which appear only between letters with a slash. The issues is that I also have html entities with semicolons and str_replace messes them up.</p>
<p>Sample string:</p>
<pre><code>Category A &gt; Subcategory A;Category A &gt; Subcategory B;Category B &gt; Subcategory C
</code></pre>
<p>Desired output:</p>
<pre><code>Category A &gt; Subcategory A/Category A &gt; Subcategory B/Category B &gt; Subcategory C
</code></pre>
| <p>To replace semicolon between letter only, you can use regex lookahead and lookbehind.</p>
<pre><code>$str = "Category A &gt; Subcategory A;Category A &gt; Subcategory B;Category B &gt; Subcategory C";
$str = preg_replace("/(?<!\s);(?!\s)/", "/", $str);
echo $str;
</code></pre>
<p>or if your html entities is only <code>&gt;</code> then you could use code below</p>
<pre><code>$str = "Category A &gt; Subcategory A;Category A &gt; Subcategory B;Category B &gt; Subcategory C";
$str = preg_replace("/(?<!\&gt);/", "/", $str);
echo $str;
</code></pre>
|
what is the use of jQuery.parseXML() <p>I was reading the document <a href="https://api.jquery.com/jQuery.parseXML/" rel="nofollow">https://api.jquery.com/jQuery.parseXML/</a>.
It says <code>Jquery.parseXML(string)</code> Parses a well formed XML string into an XML document.I am just confused what is difference between a well formed xml string and xml document and xml object , I just can't understand what <code>jQuery.parseXML()</code> really does, Can someone explain what this method really does with an example.</p>
| <p>A string is just textual information. You could open in Notepad, display it in your console, send it in an email, etc. It doesn't carry any intrinsic meaning or function.</p>
<p>An XML document is an object which is constructed <em>from</em> a string. It gives you functions just like working with the DOM. You can search for nodes, add nodes, remove nodes, etc.</p>
<p><strong>TL;DR</strong> A string is just text, an XML document is an object.</p>
|
Download from DropBox using DropBox.Api <p>anybody knows how to do this using DropBox.Api package and not DropNet package in C#?</p>
<pre><code>//using DropNet:
client = new DropNetClient("gwsdfs343sdfjtwt8", "6ygdfghdfhd34cf", userToken: "w5dgfdfg343", userSecret: "239dgfsgs34434o");
</code></pre>
<p>I've installed DropBox.Api but can't find any overload that takes these 4 parameters:</p>
<pre><code>//using DropBox.Api
DropboxClient client = new DropboxClient("cU5M-a4ekhkhklhjb5h63563bh356k3kjkbjk356XH");
</code></pre>
<p>Which is the equivalent using DropBox.Api?</p>
| <p>I've just used the <code>generated token</code> from DropBox app, it wasn't possible to do it the other way, it was years ago, now it's easier using just the <code>generated token</code></p>
|
replacing fields from json formating using easier methodology in Qt 5.7 using QVariantMaps <p>I have 3 variantMaps created from JSON and I would like to substitute<br>
for example all 3 things from 3d with 2nd and than second to first to the properties.</p>
<pre><code> QVariantMap wholeMapToChange; //1.
QVariantMap propertiesMapToChange; //2.
QVariantMap cmdMap; //3.
</code></pre>
<p>1st contain this JSON data but in map: </p>
<pre><code>{
properties {
"A": true,
"B": true,
"fieldName": "ewfqfqewf",
"C": false,
"fieldPassword": "451541611",
"isBtnSignOnClicked": true
},
type: "xyz"
}
</code></pre>
<p>2nd contain this JSON data but in map: </p>
<pre><code>{
"A": true,
"B": true,
"fieldName": "ewfqfqewf",
"C": false,
"fieldPassword": "451541611",
"isBtnSignOnClicked": true
}
</code></pre>
<p>3d contain this JSON data but in map: </p>
<pre><code>{
"fieldName": "nick",
"fieldPassword": "0000",
"isBtnSignOnClicked": true
}
</code></pre>
<p>What I see as a possibility for substituing 3 with 2 is to create cycle</p>
<pre><code>for (QVariantMap::const_iterator it = propertiesMapToChange.begin(); it != propertiesMapToChange.end(); ++it){
for (QVariantMap::const_iterator itt = cmdMap.begin(); itt != cmdMap.end(); ++itt){
///here would be the comparig...
}
}
</code></pre>
<p>But I dont think this is good solution... I would like to ask you for advice or opinion, whether its correct, or there exist better way to do that.</p>
<p>Thx</p>
| <p>It is the right solution if the maps aren't too big, since the cost is N*M. But it is a premature pessimization. You should implement the loop to have N+M cost: after all, the maps are sorted, so you only need to iterate each map once.</p>
<p>A complete example:</p>
<pre><code>// https://github.com/KubaO/stackoverflown/tree/master/questions/json-map-iter-39979440
#include <QtCore>
QVariantMap replaceMap(QVariantMap dst, const QVariantMap & src) {
auto dit = dst.begin();
auto sit = src.begin();
while (dit != dst.end() && sit != src.end()) {
if (sit.key() < dit.key()) {
++ sit;
continue;
}
if (dit.key() < sit.key()) {
++ dit;
continue;
}
Q_ASSERT(sit.key() == dit.key());
dit.value() = sit.value();
++ sit;
++ dit;
}
return dst;
}
int main() {
auto json1 = QJsonDocument::fromJson({R"ZZ({
"properties":{
"A":true,
"B":true,
"fieldName":"ewfqfqewf",
"C":false,
"fieldPassword":"451541611",
"isBtnSignOnClicked":true
},
"type":"xyz"
})ZZ"}).toVariant().value<QVariantMap>();
auto json2 = QJsonDocument::fromJson({R"ZZ({
"A":true,
"B":true,
"fieldName":"ewfqfqewf",
"C":false,
"fieldPassword":"451541611",
"isBtnSignOnClicked":true
})ZZ"}).toVariant().value<QVariantMap>();
auto json3 = QJsonDocument::fromJson(
{R"ZZ({
"fieldName":"nick",
"fieldPassword":"0000",
"isBtnSignOnClicked":true
})ZZ"}).toVariant().value<QVariantMap>();
json2 = replaceMap(json2, json3);
auto props = replaceMap(json1["properties"].value<QVariantMap>(), json2);
json1["properties"] = props;
qDebug() << QJsonDocument::fromVariant(json1).toJson().constData();
}
</code></pre>
<p>Output:</p>
<pre><code>{
"properties": {
"A": true,
"B": true,
"C": false,
"fieldName": "nick",
"fieldPassword": "0000",
"isBtnSignOnClicked": true
},
"type": "xyz"
}
</code></pre>
|
Point to Json File you created in Android Studio <p>Practing my JSON to JAVA Object skills, running into an issue, trying to point to the json file i created in android studio, instead of writing out my json data in full. here is my code. Thank you</p>
<p>Trying to turn this:</p>
<pre><code> System.out.println(
gson.fromJson("{\"draw_date\":\"2016-10-07T00:00:00.000\",\"mega_ball\":\"14\",\"multiplier\":\"02\",\"winning_numbers\":\"24 37 42 50 65\"}", MegaPOJO.class));
</code></pre>
<p>Into This:</p>
<pre><code> System.out.println(gson.fromJson(jsonFile, MegaPOJO.class));
</code></pre>
| <p>If you want to do this, place the json file in the raw resources folder.</p>
<p>I created a ResourceManager class to get the content.</p>
<pre><code>public class ResourceManager {
private final Context context;
private final Resources resources;
private static ResourceManager resourceManager;
private ResourceManager(Context context) {
this.context = context;
this.resources = context.getResources();
}
public static ResourceManager getResourceManager(Context context) {
if (resourceManager == null) {
resourceManager = new ResourceManager(context);
}
return resourceManager;
}
public String getJSONFromRawResources(String jsonFilename) {
int resourceID = resources.getIdentifier(jsonFilename, "raw", context.getPackageName());
InputStream inputStream = resources.openRawResource(resourceID);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder jsonStringStringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
jsonStringStringBuilder.append(line);
}
return jsonStringStringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
</code></pre>
<p>You can access this class by:</p>
<pre><code>ResourceManager resourceManager = ResourceManager.getResourceManager(this);
String jsonResult = resourceManager.getJSONFromRawResources("jsonfile");
</code></pre>
<p>And then you can use:</p>
<pre><code> System.out.println(gson.fromJson(jsonResult, MegaPOJO.class));
</code></pre>
|
maven-dependency-plugin analyze - "Skipping project with no build directory" <p>I'm running mvn dependency:analyze-only & im getting the error below. Can someone point me to the correct config for running the maven dependency analyzer?. </p>
<p>FYI, my project build fine with maven, so im not sure what its looking for. I also listed my pom.xml for the plugin.</p>
<p><strong>this is the error im getting</strong></p>
<pre><code>[INFO]
[INFO] --- maven-dependency-plugin:2.10:analyze-only (default-cli) @ MFC ---
[INFO] Skipping project with no build directory
</code></pre>
<p>...
<strong>This is my pom.xml for the dependency plugin</strong>
...</p>
<pre><code><plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.10</version>
<executions>
<execution>
<id>analyze</id>
<goals>
<goal>analyze</goal>
</goals>
<configuration>
<failOnWarning>true</failOnWarning>
<outputDirectory>c:\TEMP\</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</code></pre>
| <blockquote>
<p>Note that the dependency:analyze-only goal is used in preference to dependency:analyze since it doesn't force a further compilation of the project, but uses the compiled classes produced from the earlier test-compile phase in the lifecycle.</p>
<p>The project's dependencies will then be automatically analyzed during the verify lifecycle phase</p>
</blockquote>
<p>If you have not compiled or run your tests before, you will get that message. </p>
<p>Then you must execute as follows</p>
<pre><code> >mvn verify dependency:analyze-only
</code></pre>
<p>or simply </p>
<pre><code> > mvn verify
</code></pre>
<p><strong>UPDATE</strong></p>
<p>Your pluging goal must be <strong><code><goal>analyze-only</goal></code></strong> not <code><goal>analyze</goal></code> plugin then must be</p>
<pre><code><plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.10</version>
<executions>
<execution>
<id>analyze</id>
<goals>
<goal>analyze-only</goal>
</goals>
<configuration>
<failOnWarning>true</failOnWarning>
<outputDirectory>c:\TEMP\</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</code></pre>
<p>do the change and execute mvn verify dependency:analyze-only or verify and it should works.</p>
|
A JSONArray text must start with '[' at 1 [character 2 line 1] <p>I have a JSON file and i am trying to deal with but the following error is appears:</p>
<blockquote>
<p>Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
at org.json.JSONObject.(JSONObject.java:195)
at org.json.JSONObject.(JSONObject.java:319)
at amazondataset.AmazonDataset.main(AmazonDataset.java:11)
Java Result: 1</p>
</blockquote>
<p>This is a sample of the file:</p>
<pre><code>{ "reviewerID": "A2SUAM1J3GNN3B",
"asin": "0000013714",
"reviewerName": "J. McDonald",
"helpful": [2, 3],
"reviewText": "I bought this for my husband who plays the piano. He is having a wonderful time playing these old hymns. The music is at times hard to read because we think the book was published for singing from more than playing from. Great purchase though!",
"overall": 5.0,
"summary": "Heavenly Highway Hymns",
"unixReviewTime": 1252800000,
"reviewTime": "09 13, 2009"
}
</code></pre>
<p>and this is my code, simply: </p>
<pre><code>JSONObject ar = new JSONObject("E:\\amazonDS.json");
for (int i = 0; i < ar.length(); i++) {
System.out.println( "Name: " + ar.getString("reviewerName").toString() );
}
</code></pre>
| <p>You have to read the content of the file first, because the constructor of <a href="https://github.com/stleary/JSON-java/blob/master/JSONArray.java" rel="nofollow">JSONArray</a> needs the file-content and not the file-path.</p>
<pre><code>new JSONObject(new JSONTokener(new FileInputStream(new File("path"), "UTF-8")));
new JSONObject(new JSONTokener(new FileReader("path")));
</code></pre>
<p><em>update</em>
You should use a filereader or specify the charset for the FileInputStream</p>
|
PhantomJS ReferenceError for included function <p>I am trying to render a page of a webapp of mine.</p>
<pre><code><html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="includes.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
load_gantt(some, values);
});
</script>
</head>
<body>
<div class="container"></div>
</body>
</html>
</code></pre>
<p>As you can see I include jQuery and a joined javascript file which includes all my libs and custom scripts. It is joined into a single file to make sure that the depending libs are ready when the custom code kicks in. Might not be pretty or ideal but that is not the problem here.</p>
<p>The problem is the script block where I call load_gantt(). The function is defined at the end of include.js (after all the libs) like this:</p>
<pre><code>load_gantt = function(some, values){ /* CODE HERE */ };
</code></pre>
<p>load_gantt() does the actual rendering to div.container and is pretty important. When I try to render this file with PhantomJS now, I get this error:</p>
<pre><code>ReferenceError: Can't find variable: load_gantt
</code></pre>
<p>I also tried to remove the script-Block and use phantomJS's evaluate-function to run load_gantt() but it results in the same error. It seems that the scope of the acutal HTML page is different from the scope of the included js files. However, the strange thing is, that phantomjs does not complain about the jQuery part of the script block although the jquery lib gets included the same way...</p>
<p>Code is working perfectly in every browser by the way. No problems or errors...</p>
<p>Edit: fixed some minor syntax error</p>
| <p>This is not really an answer but a fix.. I registered the <code>onConsoleMessage</code>, <code>onError</code>, <code>onResourceError</code> and <code>onResourceTimeout</code> events and noticed and error which indicated that the function was not initialized properly.</p>
<p>I used</p>
<pre><code>load_gantt = function(a = 'default_a', b = 'default_b'){ /* ... */};
</code></pre>
<p>but PhantomJS does not get along with this... It has to be without the default values. I don't know why but it works now.</p>
<pre><code>load_gantt = function(a, b){ /* ... */};
</code></pre>
|
Visual Studio Load Testing. Is there a way to specify both how many times a minute you want a test to run and how many minutes? <p>I am attempting to do some loadtesting at work, and they want me to use Visual Studio's load testing. The test asked for is to have 100 logins occur per minute for 30 minutes.</p>
<p>I can see a way to set up a 1 minute duration test where I can have 100 virtual users log in. I can also set up a test for 100 virtual users to log in and have it run 30 times. </p>
<p>So my question is this: Is there a way to meet both of these requirements at one time?</p>
| <p>Before really answering this question you need to ask some other questions, such as:</p>
<ul>
<li>What do the users do after they login?</li>
<li>Can we just do logins and will the system under test (SUT) mind having several hundred (or several thousand) users who have logged in but not logged out?</li>
</ul>
<p>Having created a test script that may include think times, work out how long it takes on average at low loads; let this be T seconds. Work out how many tests one virtual user (VU) can perform in 30 minutes, that is <code>30*60/T</code>.</p>
<p>The test spec is <em>"to have 100 logins occur per minute for 30 minutes"</em>. This means that <code>100*30</code> logins are required in total. We know how many logins one VU can do, so divide the two number to work out how many VUs are needed. The value is <code>(100*30)/(30*60/T)</code>. Rearranging and simplifying gives <code>T*5/3</code>.</p>
<p>Example. Suppose a test takes 45 seconds, so <code>T == 45</code>. Thus we need <code>45*5/3 == 75</code> VUs. If we use a constant load pattern this will give 150 logins in the first minutes but only 75 in the second minute, the third minute will have approximately 150 and the fourth approximately 45, and so on. The total averages to 100 per minute, the normal variations in think times and execution times means the load spreads out over time. It may be better to use a stepped load pattern calculated to give 100 tests starting in the first minute. Given the (assumed) 45 second text execution time, if the 75 VUs are started in 45 seconds then 25 of these VUs will finish their test within the first minute and can start another test, thus giving 75+25 tests that start in the first minute. So 75 VUs in 45 seconds is the same as 25 VUs in 15s is the same as 5 VUs in 3s. Hence we could use a stepped load pattern starting with 5 VUs, increasing by 5 VUs every 3 seconds to a maximum of 75 VUs.</p>
<p>Example. Suppose a test takes 6 seconds, so <code>T == 6</code>. Thus we need <code>6*5/3 == 10</code> VUs. If we use a constant load pattern this will give approximately 100 logins in each minutes but, at least initially, the 10 users will be in phase until the normal variations in think times and execution times means the load spreads out over time. Again it may be better to use a stepped load pattern. The simplest I can see is to starting with 1 VU, increasing by 1 VU every (one) second to a maximum of 10 VUs.</p>
|
python pyquery import not working on Mac OS Sierra <p>I'm trying to import pyquery as I did hundreds on time before, and it's not working. It looks like related to the Mac OS Sierra. (module installed with pip and up-to-date)</p>
<pre><code>from pyquery import PyQuery as pq
</code></pre>
<p>And got an error on the namespacing</p>
<pre><code>ImportError: cannot import name PyQuery
</code></pre>
<p>Any idea ?
Thx !</p>
| <p>Finally found why. My file had the same name as my import...
So the library import was overridden by the name of the .py file. </p>
|
Mongodb won't start - reason: errno:111 Connection refused <p>All of a sudden I can't get mongodb to work.</p>
<p>Usually I will start with </p>
<pre><code>mongo
</code></pre>
<p>however I get this when trying to start.</p>
<pre><code>MongoDB shell version: 3.0.6
connecting to: test
2016-10-11T15:36:56.462+0100 W NETWORK Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused
2016-10-11T15:36:56.464+0100 E QUERY Error: couldn't connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed
at connect (src/mongo/shell/mongo.js:179:14)
at (connect):1:6 at src/mongo/shell/mongo.js:179
exception: connect failed
</code></pre>
<p>I haven't updated anything on the server or even logged into it until the website broke. Any ideas why this is happening? I have tried to comment out the bind_ip but I don't get why it would just stop working and failing to start.</p>
<p>I have also tried</p>
<pre><code>sudo service mongo start
mongod start/running, process 1529
</code></pre>
<p>Then when I tried - </p>
<pre><code>sudo service mongod status
mongod stop/waiting.
</code></pre>
<p>I can't start my nodejs app because it returns</p>
<pre><code> /node_modules/mongoose/node_modules/mongodb/lib/server.js:22ââ8 process.nextTick(function() { throw err; }) ^ Error: connect ECONNREFUSED at exports._errnoException (util.js:746:11) at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1010:19)
</code></pre>
<p>I think that is because mongodb isn't starting correctly but not sure.</p>
<p>The error produces this </p>
<pre><code>2016-10-11T15:40:30.400+0100 E JOURNAL [initandlisten] Insufficient free space for journal files
2016-10-11T15:40:30.400+0100 I JOURNAL [initandlisten] Please make at least 3379MB available in /var/lib/mongodb/journal or use --smallfiles
2016-10-11T15:40:30.400+0100 I JOURNAL [initandlisten]
2016-10-11T15:40:30.402+0100 I STORAGE [initandlisten] exception in initAndListen: 15926 Insufficient free space for journals, terminating
2016-10-11T15:40:30.402+0100 I CONTROL [initandlisten] now exiting
2016-10-11T15:40:30.402+0100 I NETWORK [initandlisten] shutdown: going to close listening sockets...
2016-10-11T15:40:30.402+0100 I NETWORK [initandlisten] removing socket file: /tmp/mongodb-27017.sock
2016-10-11T15:40:30.402+0100 I NETWORK [initandlisten] shutdown: going to flush diaglog...
2016-10-11T15:40:30.402+0100 I NETWORK [initandlisten] shutdown: going to close sockets...
2016-10-11T15:40:30.402+0100 I STORAGE [initandlisten] shutdown: waiting for fs preallocator...
2016-10-11T15:40:30.402+0100 I STORAGE [initandlisten] shutdown: final commit...
2016-10-11T15:40:30.402+0100 I STORAGE [initandlisten] shutdown: closing all files...
2016-10-11T15:40:30.402+0100 I STORAGE [initandlisten] closeAllFiles() finished
2016-10-11T15:40:30.402+0100 I CONTROL [initandlisten] dbexit: rc: 100
2016-10-11T15:45:36.614+0100 I CONTROL ***** SERVER RESTARTED *****
2016-10-11T15:45:36.642+0100 E NETWORK [initandlisten] Failed to unlink socket file /tmp/mongodb-27017.sock errno:1 Operation not permitted
2016-10-11T15:45:36.642+0100 I - [initandlisten] Fatal Assertion 28578
2016-10-11T15:45:36.642+0100 I - [initandlisten]
***aborting after fassert() failure
2016-10-11T15:46:21.636+0100 I CONTROL ***** SERVER RESTARTED *****
2016-10-11T15:46:21.663+0100 E NETWORK [initandlisten] Failed to unlink socket file /tmp/mongodb-27017.sock errno:1 Operation not permitted
2016-10-11T15:46:21.663+0100 I - [initandlisten] Fatal Assertion 28578
2016-10-11T15:46:21.663+0100 I - [initandlisten]
</code></pre>
<p>I broswed to that dir and saw this!!! Why are those files so huge?</p>
<p><a href="https://i.stack.imgur.com/20wBl.png" rel="nofollow"><img src="https://i.stack.imgur.com/20wBl.png" alt="enter image description here"></a></p>
| <p>It seems that your error is similar to <a href="http://stackoverflow.com/questions/29813648/failed-to-unlink-socket-file-error-in-mongodb-3-0">this</a></p>
<p>Removing the <code>/tmp/mongodb-27017.sock</code> file should do the trick.</p>
<p>Also check your disk space, as it seems the process is not starting because you are missing space for the journal files (check @dave-v comment below)</p>
|
Write a Java method changeBlue(weight) <p>Write a method <code>changeBlue(weight)</code>. Do not change any color of the pixels in the first half of the picture. For the second half, change blue value of each pixel by <code>new blue=original blue * weight</code>. </p>
<blockquote>
<p>For example, if a pixel has values (200,100,100) and weight is 0.5,
then the new values will be (200,100,50). If the weight is 1.5, then
the new values will be (200,100,150). </p>
</blockquote>
<p>You can use any image to test this method.</p>
<p>Here's what I have. I think I'm pretty close, but I'm getting some errors. Any advice is appreciated.</p>
<pre><code>public void changeBlue(int weight)
{
Pixel[] pixelArray = this.getPixels();
Pixel pixelObj = null;
int value = 0;
int index = 0;
while (index >= pixelArray.length/2)
{
pixelObj = pixelArray[index];
value = pixelObj.getBlue();
value = (value * weight);
pixelObj.setBlue(value);
index++;
}
}
</code></pre>
| <p>Not the best implementation but try : </p>
<pre><code>public void changeBlue(int weight)
{
Pixel[] pixelArray = this.getPixels();
Pixel pixelObj = null;
int value = 0;
int index = 0;
int halfSize = pixelArray.length/2;
for (index = 0; index <= pixelArray.length; index++) {
if (index <= halfSize){
// FIrts half of the file
}
if (index > halfSize) {
// Seconde part of the file
pixelObj = pixelArray[index];
value = pixelObj.getBlue();
value = (value * weight);
pixelObj.setBlue(value);
}
}
}
</code></pre>
|
kubectl exec into contain of multi container pod <p>I have problem login into one container of a multi-container pod.
I get the container id from the <code>kubectl describe pod <pod-name></code></p>
<pre><code>kubectl describe pod ipengine-net-benchmark-488656591-gjrpc -c <container id>
</code></pre>
<p>When i try: </p>
<pre><code>kubectl exec -ti ipengine-net-benchmark-488656591-gjrpc -c 70761432854f /bin/bash
</code></pre>
<p>It says: Error from server: container 70761432854f is not valid for pod ipengine-net-benchmark-488656591-gjrpc</p>
| <p>ah once more detailed reading the man page of kubectl exec :</p>
<blockquote>
<p>Flags:
-c, --container="": Container name. If omitted, the first container in the pod will be chosen
-p, --pod="": Pod name
-i, --stdin[=false]: Pass stdin to the container
-t, --tty[=false]: Stdin is a TTY</p>
</blockquote>
<p>So i just used the container name from my manifest.yaml and it worked like charm. Hope this helps others ... </p>
<p><code>Name of the container: ipengine-net-benchmark-iperf-server</code></p>
<pre><code>kubectl exec -ti ipengine-net-benchmark-488656591-gjrpc -c ipengine-net-benchmark-iperf-server /bin/bash
</code></pre>
|
WebViewClient not calling shouldOverrideUrlLoading <p>The problem is rather simple.
In the application we want to keep track of the current url being displayed. For that we use <code>shouldOverrideUrlLoading</code> callback from the <code>WebViewClient</code> by saving the url into a class field for every update. Here is the relevant code:</p>
<pre><code> mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
mCurrentUrl = url;
// If we don't return false then any redirect (like redirecting to the mobile
// version of the page) or any link click will open the web browser (like an
// implicit intent).
return false;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
...
}
});
mWebView.loadUrl(mInitialUrl);
</code></pre>
<p>However, there is at least one scenario, where the callback never gets triggered and the mCurrentUrl field doesnt get updated.</p>
<p>The url: <a href="https://m.pandora.net/es-es/products/bracelets/556000">https://m.pandora.net/es-es/products/bracelets/556000</a></p>
<p>Last updated url (shouldOverrideUrlLoading never gets called when clicking the product): <a href="https://m.pandora.net/es-es/products/bracelets">https://m.pandora.net/es-es/products/bracelets</a></p>
<p>I have tried with callbacks like onPageStarted(), but the url also gets filtered and there doesn't seem to be an accessible one upstream since its protected code.</p>
<p>Reading android documentation about WebView I found this:</p>
<p><a href="https://developer.android.com/guide/webapps/migrating.html#URLs">https://developer.android.com/guide/webapps/migrating.html#URLs</a></p>
<p><em>The new WebView applies additional restrictions when requesting resources and resolving links that use a custom URL scheme. For example, if you implement callbacks such as shouldOverrideUrlLoading() or shouldInterceptRequest(), then WebView invokes them only for valid URLs.</em></p>
<p>But still doesnt make sense since the above url is generic and should meet the standard. </p>
<p>Any alternative or solution to this?</p>
| <p>When you click a product on that web page, it loads the new content in with JavaScript and updates the visible URL in the address bar using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries" rel="nofollow">HTML5 History APIs</a>.</p>
<p>From the above MDN article:</p>
<blockquote>
<p>This will cause the URL bar to display <a href="http://mozilla.org/bar.html" rel="nofollow">http://mozilla.org/bar.html</a>, but won't cause the browser to load bar.html or even check that bar.html exists.</p>
</blockquote>
<p>These are sometimes called <a href="https://en.wikipedia.org/wiki/Single-page_application" rel="nofollow">single-page applications</a>. Since the actual loaded page doesnât change, the WebView callback for page loads isnât called.</p>
<p>In case you know precisely what kind of HTTP request you want to intercept, you could use the <code>shouldInterceptRequest</code> callback that gets called for each request. Itâs likely that the web application loads some data from an API, for example when a product is shown, which you could then detect.</p>
<p>If detecting this isnât possible, but youâre in control of the web application, you could use the <a href="https://developer.android.com/guide/webapps/webview.html#BindingJavaScript" rel="nofollow">Android JavaScript interface</a> to invoke methods within the Android application directly from the web page.</p>
<p>If youâre not in control of the loaded page, you could still try to <a href="https://stackoverflow.com/questions/21552912/android-web-view-inject-local-javascript-file-to-remote-webpage">inject a local JavaScript file</a> into the web page and <a href="https://stackoverflow.com/questions/4570093/how-to-get-notified-about-changes-of-the-history-via-history-pushstate">observe when the history APIs are used</a>, then call methods in your Android application over the JS interface. I tried observing these events in Chrome with the method described in the previous link and it seems to work fine.</p>
|
Trivia Game loop and get line issues <p>Ok, so I'm new to this so please bare with me. I'm working on a simple trivia game, and just for testing I created this small bit of code to make sure it was working right.</p>
<pre><code>// Trivia game for one player. Player will choose a category and program
// will ask you questions within set category. Correct answers are
// worth 5 points and incorrect answers are worth only 2.5 points.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
float score = 0;
string name, question, ans1, ans2, ans3, ans4;
char ans, correct;
ifstream history;
history.open("History.txt");
while (!history.eof())
{
getline(history, question);
cout << question << '\n';
getline(history, ans1);
cout << ans1 << '\n';
getline(history, ans2);
cout << ans2 << '\n';
getline(history, ans3);
cout << ans3 << '\n';
getline(history, ans4);
cout << ans4 << '\n';
history >> correct;
cout << "Enter your answer: ";
cin >> ans;
if (ans = correct)
{
cout << "You are correct!\n";
cout << "5 Points awarded...\n";
score = score + 5;
}
else
{
cout << "Wrong!\n";
cout << "2.5 Points awarded...\n";
score = score + 2.5;
}
}
}
</code></pre>
<p>History.txt looks like this....</p>
<pre><code>What was the first Tudor monarch in England?
A. Henry V
B. Edward IV
C. Henry VII
D. Edmund
C
The Kingdom of Joseon was founded in 1392 in what country?
A. England
B. Isreal
C. China
D. Korea
D
The Spanish Civil War began in what year?
A. 1936
B. 1874
C. 1920
D. 1948
A
</code></pre>
<p>So what's happening is it reads and outputs the first question and answers properly, then for the next set it only goes to C. then to B, so on so on. It is also counting every responses from the user as correct. What am I doing wrong?</p>
| <p>It's counting every answer as correct because the condition of your <code>if</code> statement:</p>
<pre><code>if (ans = correct)
</code></pre>
<p>is an assignment, which technically evaluates to <code>true</code> (because it's non-zero).</p>
<p>Change to:</p>
<pre><code>if (ans == correct)
</code></pre>
<p>to evaluate for equality.</p>
|
Why don't objects have hasattr and getattr as attributes? <p>When you need to access an object's attributes dynamically in Python, you can just use the builtin functions <code>hasattr(object, attribute)</code> or <code>getattr(object, attribute)</code>.</p>
<p>However this seems like an odd order for the syntax to take. It's less readable and intuitive as it messes up the regular sentence structure for English.</p>
<blockquote>
<p><code>if hasattr(person, age):</code><br>
if has attribute Person age</p>
</blockquote>
<p>Where having it as a method of the object would be much more readable:</p>
<blockquote>
<p><code>if person.hasattr(age):</code><br>
if Person has attribute age</p>
</blockquote>
<p>Is there a particular reason for not implementing it this way? I could imagine there are cases where you're not sure if the object is even a proper object, rather than just <code>None</code>, but surely in those cases of uncertainty you could just use the builtin function anyway for extra safety.</p>
<p>Is there some other drawback or consideration I'm not thinking of that makes adding these not worth it?</p>
| <p>You'll find quite a few similar examples - like <code>len(obj)</code> instead of <code>obj.length()</code>, <code>hash(obj)</code> instead of <code>obj.hash()</code>, <code>isinstance(obj, cls)</code> instead of <code>obj.isinstance(cls)</code>. You may also have noticed that addition is spelled <code>obj1 + obj2</code> instead of <code>obj1.add(obj2)</code>, substraction spelled <code>obj1 - obj2</code> instead of <code>obj1.sub(obj2)</code> etc... The point is that some builtin "functions" are to be considered as operators rather than really functions, and are supported by "__magic__" methods (<code>__len__</code>, <code>__hash__</code>, <code>__add__</code> etc). </p>
<p>As of the "why", you'd have to ask GvR but historical reasons set asides, it at least avoids a lot of namespace pollution / name clashes. How would you name the length of a "Line" or "Rectangle" class if <code>length</code> was already a "kind of but not explicitely reserved" name ? And how should introspection understand that <code>Rectangle.length()</code> doesn't mean <code>Rectangle</code> is a sizeable sequence-like object ?</p>
<p>Using generic "operator" functions (note that proper operators also exist as functions, cf the <code>operator</code> module) + "__magic__" methods make the intention clear and leaves normal names open for "user space" semantic.</p>
<p>wrt/ the "regular sentence structure for English", I have to say I don</p>
<blockquote>
<p>I could imagine there are cases where you're not sure if the object is
even a proper object, rather than just None</p>
</blockquote>
<p><code>None</code> <em>is</em> a "proper" object. Everything in Python (well, everything you can bind to a name) is a "proper" object. </p>
|
find duplicates in Ruby array of arrays, sum their values, then combine them <p>I have a pipe delimited text file that i am looping through that looks like so:</p>
<pre><code>123|ADAM JOHNSON|AAUA|||||||||||1||||
123||AAUA||||||||8675|90.0|90.0||||||||
444|STEVE SMITH|AAUA|||||||||||1|||||
444||AAUA||||||||2364|50.0|50.0|||||||
444||AAUA||||||||8453|50.0|50.0||||
567|ALLEN JONES|AAUA|||||||||||1||||||
567||AAUA||||||||6578|75.0|75.0||||||
567||AAUA||||||||1234|10.0|10.0||||
567||AAUA||||||||1234|15.0|15.0|||||
</code></pre>
<p>What I start with is grab the first, tenth and eleventh indexes of these rows and put them into an array of arrays like so:</p>
<pre><code>CSV.foreach('data.txt', { :col_sep => '|' }) do |row|
if row[1].nil?
@group_array << [row[0], [row[10], row[11]]]
end
end
</code></pre>
<p>So I get something like:</p>
<pre><code>[["123", ["8675", "90.0"]]
------------------
["444", ["2364", "50.0"]]
["444", ["8453", "50.0"]]
------------------
["567", ["6578", "75.0"]]
["567", ["1234", "10.0"]]
["567", ["1234", "15.0"]]]
</code></pre>
<p>What I am struggling with is looping through the arrays, finding groupings with the same first index (the 3 integer ids), looping through that then finding any duplicates in the second array with the same 4 integer id, then adding the third index floats then spitting out a final array with the duplicates removed and their values summed.</p>
<p>Expected output should look like: </p>
<pre><code>[["0006310001", ["789663473", "90.0"]],
["0006410001", ["297103188", "50.0"]],
["0006410001", ["757854164", "50.0"]],
["0006610001", ["557493572", "75.0"]],
["0006610001", ["981894386", "25.0"]]]
</code></pre>
| <p>I don't think your data item looks like <code>[["123", ["8675", "90.0"]]]</code> based on how it's created... more likely it looks like <code>["123", ["8675", "90.0"]]</code></p>
<p>In which case, this should do what you want...</p>
<pre><code>group_array = @group_array.sort
result = []
save_3 = nil
save_4 = nil
total = 0.0
group_array.each do |group|
if group[0] != save_3 || group[1][0] != save_4
result << [save_3, [save_4, total.to_s]] if save_3
total = 0.0
save_3 = group[0]
save_4 = group[1][0]
end
total += group[1][1].to_f
end
result << [save_3, [save_4, total.to_s]] if save_3
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.