input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Bash scripting - Complex MYSQL statements <p>So I am trying to take this:</p>
<pre><code>SELECT 'cran_juniper' AS `set`, c.*
FROM cran_juniper c
WHERE ROW(c.device_fqdn, c.device_ip, c.interface, c.admin_state, c.link_state, c.description) NOT IN
(
SELECT device_fqdn, device_ip, interface, admin_state, link_state, description
FROM cran_juniper_baseline
)
UNION ALL
SELECT 'cran_juniper_baseline' AS `set`, b.*
FROM cran_juniper_baseline b
WHERE ROW(b.device_fqdn, b.device_ip, b.interface, b.admin_state, b.link_state, b.description) NOT IN
(
SELECT device_fqdn, device_ip, interface, admin_state, link_state, description
FROM cran_juniper
)
into outfile 'today.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
;
</code></pre>
<p>And insert it into a bash script. Considering there's a SLEW of special characters all over this query, I am having a hard time finding a way to go about this. Any assist would be magical.</p>
| <h3>1st solution using <em>here-doc</em> :</h3>
<pre><code>mysql -h 127.0.0.1 <<'EOF'
SELECT 'cran_juniper' AS `set`, c.*
FROM cran_juniper c
...
;
EOF
</code></pre>
<h3>2nd solution using a separate file</h3>
<pre><code>mysql -h 127.0.0.1 < file.sql # you will put all of your query within this file
</code></pre>
<h3>Check</h3>
<pre><code>man bash | less +/here-doc
</code></pre>
|
Swift Console Output to Text Label <p>I am trying to take console output from a json request and post it as a text label for the user. I can't seem to get it to work. Any advice? Thanks! It prints fine in the console, but won't work for the "self.resultLabel.text = json"</p>
<pre><code>do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
print(json)
dispatch_async(dispatch_get_main_queue(),{
self.myActivityIndicator.stopAnimating()
self.myImageView.image = nil;
self.resultLabel.text = json
func loadSites(){
//trying to get the post to show up in the place of the invisible label
}
});
}catch {
print(error)
}
</code></pre>
| <p>I am not sure why exactly you want to show raw json to users in UILabel but you should convert json to a string if you want to assign it to UILabel's <code>text</code> property.</p>
<p>There is a <code>description</code> method, which is always used in Objective-C whenever you print an NSObject subclass via NSLog.
This method is also available in Swift:</p>
<pre><code>self.resultLabel.text = (json as AnyObject).description
</code></pre>
|
How to Filter Data with D3.js? <p>I've been searching all online but I can't really find what I'm looking for. I think maybe I'm not using the right terminology. </p>
<p>I have a simple scatterplot in D3.js. My csv file is like: </p>
<pre><code>Group, X, Y
1, 4.5, 8
1, 9, 12
1, 2, 19
2, 9, 20
3, 2, 1
3, 8, 2
</code></pre>
<p>I want to filter by group. So the graph will display by default only the values of group 1, but you can also select to see values of group 2 or group 3. </p>
<p>Here is some code I have already...
</p>
<pre><code>var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("l2data.csv", function(error, data) {
if (error) throw error;
// Coerce the strings to numbers.
data.forEach(function(d) {
d.x = +d.x;
d.y = +d.y;
});
// Compute the scalesâ domains.
x.domain(d3.extent(data, function(d) { return d.x; })).nice();
y.domain(d3.extent(data, function(d) { return d.y; })).nice();
// Add the x-axis.
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.svg.axis().scale(x).orient("bottom"));
// Add the y-axis.
svg.append("g")
.attr("class", "y axis")
.call(d3.svg.axis().scale(y).orient("left"));
// Add the points!
svg.selectAll(".point")
.data(data)
.enter().append("path")
.attr("class", "point")
.attr("d", d3.svg.symbol().type("triangle-up"))
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
});
</code></pre>
<p></p>
| <p>You have a good start here! To make this even better, you need three things. A UI component for selecting the group, an event listener for detecting a change in this component, and a function for handling the update to the visualization.</p>
<p>In the code I added, I've created three new functions for each part of the d3 lifecycle. Enter handles appending new elements to our graph. Update updates existing values based on a change in the bound data. Exit removes any elements that no longer have data bound to them. Read the classic article <a href="https://bost.ocks.org/mike/join/" rel="nofollow">https://bost.ocks.org/mike/join/</a> by Mike Bostock at that link to get more info. With this, you have the flexibility to add cool transitions to your chart, and can also customize the way data should enter and exit.</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 data = [{ group: 1, x: 5.5, y: 0 }, { group: 1, x: 0, y: 6 }, { group: 1, x: 7.5, y: 8 }, { group: 2, x: 4.5, y: 4 }, { group: 2, x: 4.5, y: 2 }, { group: 3, x: 4, y: 4 }];
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Coerce the strings to numbers.
data.forEach(function(d) {
d.x = +d.x;
d.y = +d.y;
});
// Compute the scalesâ domains.
x.domain(d3.extent(data, function(d) { return d.x; })).nice();
y.domain(d3.extent(data, function(d) { return d.y; })).nice();
// Add the x-axis.
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.svg.axis().scale(x).orient("bottom"));
// Add the y-axis.
svg.append("g")
.attr("class", "y axis")
.call(d3.svg.axis().scale(y).orient("left"));
// Get a subset of the data based on the group
function getFilteredData(data, group) {
return data.filter(function(point) { return point.group === parseInt(group); });
}
// Helper function to add new points to our data
function enterPoints(data) {
// Add the points!
svg.selectAll(".point")
.data(data)
.enter().append("path")
.attr("class", "point")
.attr('fill', 'red')
.attr("d", d3.svg.symbol().type("triangle-up"))
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
}
function exitPoints(data) {
svg.selectAll(".point")
.data(data)
.exit()
.remove();
}
function updatePoints(data) {
svg.selectAll(".point")
.data(data)
.transition()
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
}
// New select element for allowing the user to select a group!
var $groupSelector = document.querySelector('.group-select');
var groupData = getFilteredData(data, $groupSelector.value);
// Enter initial points filtered by default select value set in HTML
enterPoints(groupData);
$groupSelector.onchange = function(e) {
var group = e.target.value;
var groupData = getFilteredData(data, group);
updatePoints(groupData);
enterPoints(groupData);
exitPoints(groupData);
};</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>
<label>
Group
<select class="group-select">
<option value=1 selected>1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
</label></code></pre>
</div>
</div>
</p>
|
Jquery displays link text instead of image <p>for my wordpress site I have replaced the bottom paging-navigation with a load more function.</p>
<p>This used to say the text "load more" but I have replaced it with an image, or at least that is the plan.</p>
<p>The jquery is just showing the link to the file, instead of actually showing it.
I just can't figure it out, anybody out there who can lend me a hand ?
The piece in the index.php that is what I'm trying to fix:</p>
<pre><code>'plus' => esc_js( plugins_url( '/images/plus.png', __FILE__ ) ),
</code></pre>
<p>located in this bit:</p>
<pre><code> $max = $wp_query->max_num_pages;
$paged = ( get_query_var('paged') > 1 ) ? get_query_var('paged') : 1;
wp_enqueue_script( '-load-more', plugins_url( '/js/loadmore.js', __FILE__ ), array( 'jquery' ), '20131010', true );
wp_localize_script( '-load-more', '_load_more', array(
'current_page' => esc_js( $paged ),
'max_pages' => esc_js( $max ),
'ajaxurl' => esc_js( admin_url( 'admin-ajax.php' ) ),
'plus' => esc_js( plugins_url( '/images/plus.png', __FILE__ ) ),
'loading_img' => esc_js( plugins_url( '/images/ajax-loader.gif', __FILE__ ) )
) );
}
</code></pre>
<p>Used in the javascript here :</p>
<pre><code>if ( next_page <= max_pages ) {
$( '.paging-navigation' ).html( '<div class="nav-links"><a class="load_more" href="#">' + _load_more.plus + '</a><img class="load_more_img" style="display: none;" src="' + _load_more.loading_img + '" alt="Loading..." /></div>' );
}
</code></pre>
<p>The website is located here: <a href="http://www.hellodolly.be/" rel="nofollow">www.hellodolly.be</a></p>
<p>So the goal is to get the link to the image, which is correct, to actually display as the image.</p>
| <p>You have <code>display: none;</code> style for img with class <code>load_more_img</code>. That's why loading image isn't showed (As I understand you want to show it after click "show more"). Also you render <code>_load_more.plus</code> value which is path of the image to the content of <code><a></a></code> tag (don't know why you need this, but it's strange).</p>
<p>After all I think you want to make <code><a></a></code> element with image in backround from <code>_load_more.plus</code> path and with <code>href</code> with path to open more items. And when items are still loading you want to show <code>load_more_img</code>. In this case you should make some refactoring of your code.</p>
<p><strong>EDITED</strong>:</p>
<p>Some changes for this piece of code. You need to add click handler for <code>load_more</code> link for dynamic async loading of new items. May be smth like this:</p>
<pre><code> $('.load_more').click(function() {
$.get('<url_to_get_more_items>').done(function(data) {
var html = compileTemplate(data); // use Handlebars or Mustache as templates engine, or just make response from server as ready for use html
$('<items_container>).append(html);
});
});
</code></pre>
<p>Also you need to add <code>img</code> tag with all data inside of <code><a></a></code> tag to show <code>show_more</code> image. Result:</p>
<pre><code>if ( next_page <= max_pages ) {
$( '.paging-navigation' ).html( '<div class="nav-links"><a class="load_more" href="#"><img class="some-awesome-class-name" src="' + _load_more.plus + '" alt="Show more"></a><img class="load_more_img" style="display: none;" src="' + _load_more.loading_img + '" alt="Loading..." /></div>' );
}
</code></pre>
|
Google Analytics Destination Goal not Being Tracked <p>I'm trying to set up a Google Analytics Goal using the following settings(this is a simplified version of what's being used):</p>
<p>Goal setup: custom,
Goal type: destination,
Destination: "Equals to" /en-us/industries/chemical-petrochemical ,
Value=Off,
Funnel=Off</p>
<p>Here's the Google Tag Manager Javascript I use on the page:</p>
<pre><code><script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-TSLS6W');</script>
</code></pre>
<p>When I hit the /en-us/industries/chemical-petrochemical page on the site, I see the page being hit under Content in the Real-time reporting section of Google Analytics, so I know it is seeing the page. However, I never see anything registered in the Conversions section of the Real-time reporting.</p>
<p>Does anyone have any ideas on what the problem could be?</p>
| <p>It turns out a filter was preventing the goal from being reached. The filter was pre-appending the hostname of the URL.</p>
|
How to extend Spree::Adjustable::Adjuster? <p>Iâm trying to extend Spree::Adjustable::Adjuster as documented in the guide (<a href="http://guides.spreecommerce.org/developer/adjustments.html" rel="nofollow">http://guides.spreecommerce.org/developer/adjustments.html</a>). The directions aren't to hard to follow and I followed them to a T but I'm getting the following error:</p>
<pre><code>`<module:Adjuster>': uninitialized constant Spree::Adjustable::Adjuster::Base (NameError)
</code></pre>
| <p>What version of Spree are you using?</p>
<p>This feature was added in 3.1.</p>
<p><a href="https://github.com/spree/spree/blame/3-1-stable/core/app/models/spree/adjustable/adjuster/base.rb" rel="nofollow">https://github.com/spree/spree/blame/3-1-stable/core/app/models/spree/adjustable/adjuster/base.rb</a></p>
<p><a href="https://github.com/spree/spree/blame/master/guides/content/developer/core/adjustments.md#L99-L146" rel="nofollow">https://github.com/spree/spree/blame/master/guides/content/developer/core/adjustments.md#L99-L146</a></p>
|
ABI Split failed in NativeScript 2.3.0 <p>Iâve asked for help in the general group but most people didnt get it work as well.
Im having a huge problem ridiculous apk size of my simple app. I used @markosko nativescript filter to reduce the app to 14MB from 17.2MB, even <code>nativescript-snapshot</code> couldn't help still 17MB for release version. </p>
<p>I tried using the ABI split sample in the nativescipt documentation but what I noticed is that itâs trying to split but the glade is using same name for all the apks so I came up with this in my app.glade</p>
<pre class="lang-glade prettyprint-override"><code>def tnsBuildMultipleApks=true;
android {
defaultConfig {
generatedDensities = []
applicationId = "com.maliyo.oneclick"
versionCode Integer.parseInt("" + "1" + "0")
}
aaptOptions {
additionalParameters "--no-version-vectors"
}
if (Boolean.valueOf(tnsBuildMultipleApks)) {
splits {
abi {
enable true
reset()
include 'armeabi', 'armeabi-v7a', 'x86', 'mips'
universalApk true
}
}
}
}
def getDate() {
def date = new Date()
def formattedDate = date.format('yyyyMMdd')
return formattedDate
}
// map for the version code that gives each ABI a value
ext.versionCodes = [
'F0F1F2X86Debug':1, 'F0F1F2ArmeabiDebug':2, 'F0F1F2Armeabi-v7aDebug':3, 'F0F1F2MipsDebug':4,
'F0F1F2X86Release':1, 'F0F1F2ArmeabiRelease':2, 'F0F1F2Armeabi-v7aRelease':3, 'F0F1F2MipsRelease':4
]
// For each APK output variant, override versionCode with a combination of
// ABI APK value * 100 + defaultConfig.versionCode
android.applicationVariants.all { variant ->
// assign different version code for each output
variant.outputs.each { output ->
if (output.outputFile != null && output.outputFile.name.endsWith('.apk')) {
println("******************************************************")
println(output);
println(output.getVariantOutputData().getFullName())
if (Boolean.valueOf(tnsBuildMultipleApks)) {
def file = output.outputFile
// version at the end of each built apk
//output.outputFile = new File(file.parent, file.name.replace(".apk", "-" + android.defaultConfig.versionName + "-" + getDate() + ".apk"))
output.outputFile = new File(file.parent, file.name.replace(".apk", "-" + output.getVariantOutputData().getFullName() + "-" + getDate() + ".apk"))
output.versionCodeOverride =
//(assd++) * 100
project.ext.versionCodes.get(output.getVariantOutputData().getFullName(), 0) * 100
+ android.defaultConfig.versionCode
}
}
}
}
/**/
</code></pre>
<p>Fine, it splits but I think because I hacked the filename at output the adb couldn't find one to push the apk to the device or emulator due to the naming pattern, maybe, just saying <code>apk not found</code>.</p>
<p>I tried to manually send the appropriate apk to the device via USB, it app installed successfully but it crashes after splashscreen saying <code>metadata/treeNodeStream.dat could not be loaded</code></p>
<h1>UPDATE</h1>
<p>@plamen-petkov thanks so much for your contribution, I agree with you that it work fine, when you build one after another changing the abi filter. But with this in my app.gradle, I managed to build multiple apks successfully and tested and OK.</p>
<p>but is like the the tns is only pushing <code>appname-debug.apk</code> or <code>appname-release.apk</code> to the adb. I can toggle this splitting off with <code>tnsBuildMultipleApks</code> and maybe when Im still testing I can turn it off and use <code>tns run android</code> and when I want to make final build and it turn it one again as it works fine with <code>tns build android --release ....</code></p>
<pre><code>// Add your native dependencies here:
// Uncomment to add recyclerview-v7 dependency
//dependencies {
// compile 'com.android.support:recyclerview-v7:+'
//}
import groovy.json.JsonSlurper //used to parse package.json
def tnsBuildMultipleApks=true;
String content = new File("$projectDir/../../app/package.json").getText("UTF-8")
def jsonSlurper = new JsonSlurper()
def appPackageJson = jsonSlurper.parseText(content)
android {
defaultConfig {
generatedDensities = []
applicationId = appPackageJson.nativescript.id
versionCode = appPackageJson.version_code ?: 1
}
aaptOptions {
additionalParameters "--no-version-vectors"
}
if (Boolean.valueOf(tnsBuildMultipleApks)) {
splits {
abi {
enable true
reset()
include 'x86', 'armeabi-v7a', 'arm64-v8a'
universalApk true
}
}
}
}
// map for the version code that gives each ABI a value
ext.versionCodes = [
'x86':1, 'armeabi-v7a':2, 'arm64-v8a':3
]
// For each APK output variant, override versionCode with a combination of
// ABI APK value * 100 + android.defaultConfig.versionCode
// getAbiFilter() not working for me so I extracted it from getFullname()
if (Boolean.valueOf(tnsBuildMultipleApks)) {
android.applicationVariants.all { variant ->
println(appPackageJson)
println(android.defaultConfig.versionCode)
println(android.defaultConfig.applicationId)
def name
def flavorNamesConcat = ""
variant.productFlavors.each() { flavor ->
flavorNamesConcat += flavor.name
}
flavorNamesConcat = flavorNamesConcat.toLowerCase()
println(flavorNamesConcat)
variant.outputs.each { output ->
if (output.outputFile != null && output.outputFile.name.endsWith('.apk')) {
//You may look for this path in your console to see what the values are
println("******************************************************")
println(output); println(output.getVariantOutputData().getFullName())
def abiName = output.getVariantOutputData().getFullName().toLowerCase().replace(flavorNamesConcat, "").replace(project.ext.selectedBuildType, "")
println(abiName)
def file = output.outputFile
output.versionCodeOverride =
project.ext.versionCodes.get(abiName, 0) * 100
+ android.defaultConfig.versionCode
def apkDirectory = output.packageApplication.outputFile.parentFile
def apkNamePrefix = output.outputFile.name.replace(".apk", "-" + abiName)
if (output.zipAlign) {
name = apkNamePrefix + ".apk"
output.outputFile = new File(apkDirectory, name);
}
name = apkNamePrefix + "-unaligned.apk"
output.packageApplication.outputFile = new File(apkDirectory, name);
}
}
}
}
</code></pre>
| <p>ABI splits can be useful if you use them one at a time. Here's an example: </p>
<pre><code>android {
...
splits {
abi {
enable true
reset()
include 'armeabi-v7a'
}
}
...
}
</code></pre>
<p>The resulting .apk file will only contain the libraries necessary for armeabi-v7a devices, because it's the only architecture mentioned in the ABI splits configuration above. The ABIs available are 'arm64-v8a', 'armeabi-v7a', 'x86' as pointed out in the <a href="https://docs.nativescript.org/publishing/publishing-android-apps#apks-with-abi-splits" rel="nofollow">documentation</a>, so you can't use 'armeabi' or 'mips' architectures.</p>
<p>Furthermore you don't need this line: 'universalApk true', because what it does is ignoring the splits and making one .apk file containing all the provided architectures and you want the opposite.</p>
<p>You can also follow the progress of <a href="https://github.com/NativeScript/android-runtime/issues/529" rel="nofollow">this</a> issue as it will decrease the .apk size even more.</p>
<p>Hope this helps!</p>
|
jQuery toggle doesn't work in my page <p>I want to toggle a div with jQuery toggle function.</p>
<p>Here is my code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function () {
$("#removeSongButton").click(function () {
$("#radioButton1").toggle();
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<asp:Button runat="server" ID="removeSongButton" Text="remove song" />
</div>
<div id="radioButton1">
<asp:RadioButtonList runat="server" ID="radioButton">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
<asp:ListItem Text="3" Value="3"></asp:ListItem>
</asp:RadioButtonList >
</div></code></pre>
</div>
</div>
</p>
<p>when i click the "removeSongButton" the div tog×¢le up and immediately toggle down. i think maybe the page reload.</p>
| <p>You are right, its the reload.
If the onliest thing you want to do by button-click is to toggle then add an preventDefault like this. Or are there other events you want to trigger by the button-click?</p>
<pre><code>$("#removeSongButton").click(function (e) {
e.preventDefault();
$("#radioButton1").toggle();
});
</code></pre>
|
Itext5 program get troubles with charset when executed on Windows? <p>I'm developing an application which modifies some PDF on java. The application is finished and it work on my computer (using Linux) but now, I'm trying to execute it on a friend's computer (which use Windows) and it does not work properly. It seems to be a problem with char-set because some characters like é á ó ú doesn't appear, but I don't know how to fix it because I can't find if is a windows-configuration problem or it is a problem of my program in java... </p>
<p>My code is something like:</p>
<pre><code> Charset charset = StandardCharsets.UTF_8;
PdfReader reader = new PdfReader("template.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("resultados"+direccionamiento+"result"+paciente+".pdf"));
AcroFields wrt = stamper.getAcroFields();
if(larga == true){
File file2 = new File("informes"+direccionamiento+rs+"-"+value+".txt") ;
if(file2.exists()){
try (FileInputStream fis2 = new FileInputStream(file2)) {
String ll = "" ;
BufferedReader br = new BufferedReader(new InputStreamReader(fis2));
ll = br.readLine() ;
wrt.setField("#KEY_"+keylarga, ll) ;
}
</code></pre>
<p>(is more than this but I think you can sow the itext's parts)</p>
<p>I think maybe it could be the default charset of the windows computer but I've tried to set it as UTF_8 and it seems to be set in this way...</p>
| <p>You have to set the charset in <code>InputStreamReader</code> otherwise it will use a default charset whatever that may be.</p>
|
Switching between docker tags <p>I have an apache,wsgi based python application on ubuntu machine. Application is inside a docker container. Developer fix issue 1, deploy it and gives to tester. Developer fixed issue 2 but can`t deploy since tester is still testing issue 1. Is it possible if developer can create tags in docker image and can switch between them ? He can have 2 different versions of code in two tags or commits, can switch between them whenever he or tester wants. </p>
| <p>Each time you commit a container you will get a different image ID.
Each of this images can be tagged independently.
Example:</p>
<pre><code>docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
python 1.0 e0122ddbfbc5 23 hours ago 100 MB
python latest e0122ddbfbc5 23 hours ago 100 MB
</code></pre>
<p>Change 1:</p>
<pre><code>docker commit python:1.1
docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
python 1.0 e0122ddbfbc5 23 hours ago 100 MB
python latest e0122ddbfbc5 23 hours ago 100 MB
python 1.1 ba130ccb3f66 1 minute ago 101 MB
</code></pre>
<p>Change 2: </p>
<pre><code>docker commit python:1.2
docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
python 1.0 e0122ddbfbc5 23 hours ago 100 MB
python latest e0122ddbfbc5 23 hours ago 100 MB
python 1.1 ba130ccb3f66 10 minute ago 101 MB
python 1.2 946baf236fcc 1 minute ago 101 MB
</code></pre>
<p>Once accepted you can tag the image as latest:</p>
<pre><code>docker tag python:1.1 python:latest
</code></pre>
<p>or</p>
<pre><code> docker tag python:1.2 python:latest
</code></pre>
|
any way to make the map scrollable/moveable = false? <p>I'm looking for a way to set my map scrollable/moveable to false.</p>
<p>I can use</p>
<pre><code>map.setMaxZoomLevel(15);
map.setMinZoomLevel(15);
</code></pre>
<p>to set the zoomlevel to 15. But I found no way to set the map not scrollable/moveable</p>
| <p>One trick is to put a transparent view on top of the map view. Then you can toggle it on and off to pass through touch events or not.</p>
|
define operator[] for assignment and for reading <p>Is it possible to have two definition of <code>operator[]</code> for the following two cases?</p>
<ul>
<li><p><code>My_bit_array[7] = true;</code></p></li>
<li><p><code>bool x = My_bit_array[0];</code></p></li>
</ul>
<p>This is useful because reading a bit and toggling one of the 8 bits of a byte (<code>uint8_t</code>) are different. These two cases would require two different definitions.</p>
| <p>It's quite simple. It should be implemented using proxy object, as it was already mentioned in comments. Something like this, I suppose:</p>
<pre><code>#include <iostream>
#include <cstddef>
using namespace std;
struct proxy_obj;
struct my_bit_array
{
uint8_t bit_array_;
proxy_obj operator[](int n);
};
struct proxy_obj
{
my_bit_array& my_bit_array_;
int n_;
proxy_obj(my_bit_array& bit_array, int n)
: my_bit_array_(bit_array), n_(n) {}
proxy_obj& operator=(bool b)
{
uint8_t set_mask = 0x01 << n_;
if(b) my_bit_array_.bit_array_ |= set_mask;
else my_bit_array_.bit_array_ &= (~set_mask);
return *this;
}
operator bool(){ return my_bit_array_.bit_array_ & (0x01 << n_); }
};
proxy_obj my_bit_array::operator[](int n)
{
return proxy_obj(*this, n);
}
int main() {
my_bit_array bit_set;
bit_set[0] = false;
bool b = bit_set[0];
cout << b << endl;
bit_set[3] = true;
b = bit_set[3];
cout << b << endl;
return 0;
}
</code></pre>
|
Running fifo pipe from single terminal <p>I was wondering if there is anyway to run two programs using named pipe i.e. fifo, by executing only one program. For example, solution mentioned here [Sending strings between two pipes][1] can it be ran using one terminal only? Is there anyway to call writer.c from reader.c and run the whole program just by running reader.c</p>
<p>EDIT: I removed my code because it had a lot of problems. I was using many functions without having any knowledge about them.</p>
<p>CLOSED.</p>
| <p>Use the popen() function to run writer.py from inside your reader program:</p>
<p><a href="https://linux.die.net/man/3/popen" rel="nofollow">https://linux.die.net/man/3/popen</a></p>
<p>The popen function returns a FILE * which you can then use with any C buffered I/O function. Eg:</p>
<pre><code>#include <stdio.h>
#include <errno.h>
int main(int argc, char **argv) {
FILE *fp;
if((fp = popen("/path/to/writer.py", "r")) == NULL) {
// handle error in some way
perror("popen");
exit(1);
}
size_t numbytes;
char buffer[255];
// Here we read the output from the writer.py and rewrite it to
// stdout. The result should look the same as if you ran writer.py
// by itself.. not very useful. But you would replace this with code
// that does something useful with the data from writer.py
while((numbytes = fread(buffer, 1, sizeof(buffer), fp)) > 0) {
fwrite(buffer, 1, numbytes, stdout);
// should check for error here
}
pclose(fp);
exit(0);
}
</code></pre>
<p>PS: I did not compile or run this program, it is just an example to give you the idea... But it should work. Also.. I notice you say writer.c in one place and writer.py in another. It does not matter what language writer is written in. As long as the program pathname you pass to popen() results in output being written to stdout, it will work.</p>
|
How to Find and Fix Memory Leaks in Nested Classes in Java? <p>I'm finding the concept of memory leaks within inner classes fairly difficult to grasp. Most of the answers I find are within the context of java which further confuses a beginner like myself. </p>
<p>Most answers to similar questions here redirected to this: <a href="https://stackoverflow.com/questions/10864853/when-exactly-is-it-leak-safe-to-use-anonymous-inner-classes">When Exactly is it leak safe to use anonymous inner classes?</a> </p>
<p>Again, the answer here was difficult to get across for someone fairly new to OOP. </p>
<p>My question(s):</p>
<ol>
<li><p>Why do memory leaks occur with the inner classes?</p></li>
<li><p>When using inner classes, what are the most common memory leaks that
can occur?</p></li>
<li><p>What are remedies to memory leaks that one can come across
frequently?</p></li>
</ol>
| <blockquote>
<p>Why do memory leaks occur with the inner classes?</p>
</blockquote>
<p>Because the inner class maintains a reference to the outer class.</p>
<p>If the inner class doesn't actually <em>need</em> that reference, which is quiet common for anonymous classes, and the outer class is otherwise unreachable, it is nevertheless not garbage collectable because of that reference.</p>
<p>That is considered a "leak", i.e. memory that should be freed is not being freed, as long as a reference to the inner class is maintained.</p>
<blockquote>
<p>When using inner classes, what are the most common memory leaks that can occur?</p>
</blockquote>
<p>See answer to first question.</p>
<blockquote>
<p>What are remedies to memory leaks that one can come across frequently?</p>
</blockquote>
<p>Use static nested classes instead of anonymous, local, and inner classes. Top-level classes are of course also an option.</p>
<p>This is of course only necessary when the lifetime of the inner class exceeds the lifetime of the outer class.</p>
|
MS Excel VBA - Looping through columns and rows <p>Hello stackoverflow community,</p>
<p>I must confess I primarily code within MS Access and have very limited experience of MS Excel VBA.</p>
<p>My current objective is this, I have an "Expense Report" being sent to me with deductions, this report has many columns with different account names that may be populated or may be null. </p>
<p>My first step will be to start on the first record (Row 14; Column A-K contains personal info regarding the deduction) then skip to the first deduction account (deduction accounts start at column L and span to column DG) checking if each cell is null, if it is then keep moving right,If there is a value present, I need to copy it into an external workbook "Payroll Template" starting at row 2 (Column J for the deduction itself), as well as copy some personal info from the original row in the "Expense Report" related to that deduction (currRow: Column C,E,F from "Expense Report" to "Payroll Template" Columns B,C,D). </p>
<p>Then move to the right until the next cell contains a value, and repeat this process on a new row in the "Payroll Template". Once the last column (DG) has been executed I want to move to the next row (row 15) and start the process again all the way until the "LastRow" in my "Used Range".</p>
<p>I greatly appreciate any feedback, explanations, or links that may point me towards my goal. Thank you in advance for taking the time to read though this!</p>
<p>Current state of code:</p>
<pre><code>`< Sub LoadIntoPayrollTemplate()
Dim rng As Range
Dim currRow As Integer
Dim UsedRng As Range
Dim LastRow As Long
Set UsedRng = ActiveSheet.UsedRange
currRow = 14
Set wb = ActiveWorkbook '"Expense Report"
Set wb2 = MyFilepath '"Payroll Template"
'Copied from another procedure, trying to use as reference
LastRow = rng(rng.Cells.Count).Row
Range("A14").Select
Do Until ActiveCell.Row = LastRow + 1
If (ActiveCell.Value) <> prev Then
currRow = currRow + 1
End If
ActiveCell.Offset(1, 0).Select
Loop
With Worksheets("Collections")
lstRow = .Cells(.Rows.Count, 1).End(xlUp).Row
Set rng = .Range(.Cells(14, 12), Cells(lstRow, 111))
End With
End Sub>`
</code></pre>
| <p>The following code may do what you are after:</p>
<pre><code>Sub LoadIntoPayrollTemplate()
Dim currRowIn As Long
Dim currColIn As Long
Dim currRowOut As Long
Dim wb As Workbook
Dim wb2 As Workbook
Set wb = ActiveWorkbook '"Expense Report"
Set wb2 = Workbooks.Open(Filename:=MyFilepath & "\" & "Payroll Template.xlsx")
'or perhaps
'Set wb2 = Workbooks.Open(Filename:=wb.path & "\" & "Payroll Template.xlsx")
With wb.ActiveSheet
currRowOut = 1
For currRowIn = 14 To .UsedRange.Row + .UsedRange.Rows.Count - 1
For currColIn = 12 To 111
If Not IsEmpty(.Cells(currRowIn, currColIn)) Then
currRowOut = currRowOut + 1
'I'm not sure which worksheet you want to write the output to
'so I have just written it to the first one in Payroll Template
wb2.Worksheets(1).Cells(currRowOut, "J").Value = .Cells(currRowIn, currColIn).Value
wb2.Worksheets(1).Cells(currRowOut, "B").Value = .Cells(currRowIn, "C").Value
wb2.Worksheets(1).Cells(currRowOut, "C").Value = .Cells(currRowIn, "E").Value
wb2.Worksheets(1).Cells(currRowOut, "D").Value = .Cells(currRowIn, "F").Value
End If
Next
Next
End With
'Save updated Payroll Template
wb2.Save
End Sub
</code></pre>
|
AEM CQ5 Query Builder: How to get result by searching for 2 different values in same property? <p>I want to get result matches with all nodes contains property 'abc' value as 'xyz' or 'pqr'.</p>
<p>I am trying in below ways:</p>
<ol>
<li><p><a href="http://localhost:4502/bin/querybuilder.json?path=/content/campaigns/asd&property=abc&property.1_value=/%xyz/%&property.2_value=/%pqr/%property.operation=like&p.limit=-1&orderby:path" rel="nofollow">http://localhost:4502/bin/querybuilder.json?path=/content/campaigns/asd&property=abc&property.1_value=/%xyz/%&property.2_value=/%pqr/%property.operation=like&p.limit=-1&orderby:path</a></p></li>
<li><p><a href="http://localhost:4502/bin/querybuilder.json?path=/content/campaigns/asd&property=abc&property.1_value=/%xyz/%&property.2_value=/%pqr/%&property.1_operation=like&property.2_operation=like&p.limit=-1&orderby:path" rel="nofollow">http://localhost:4502/bin/querybuilder.json?path=/content/campaigns/asd&property=abc&property.1_value=/%xyz/%&property.2_value=/%pqr/%&property.1_operation=like&property.2_operation=like&p.limit=-1&orderby:path</a></p></li>
<li><p><a href="http://localhost:4502/bin/querybuilder.json?path=/content/campaigns/asd&1_property=abc&1_property.1_value=/%xyz/%&1_property.1_operation=like&2_property=abc&1_property.1_value=/%xyz/%&2_property.1_operation=like&p.limit=-1&orderby:path" rel="nofollow">http://localhost:4502/bin/querybuilder.json?path=/content/campaigns/asd&1_property=abc&1_property.1_value=/%xyz/%&1_property.1_operation=like&2_property=abc&1_property.1_value=/%xyz/%&2_property.1_operation=like&p.limit=-1&orderby:path</a></p></li>
</ol>
<p>But none of them served my purpose. Any thing that I am missing in this?</p>
| <p>The query looks right and as such should work. However if it is just <code>xyz</code> or <code>pqr</code> you would like to match in the query, you may not need the <code>/</code> in the values.</p>
<p>For eg.</p>
<pre><code>path=/content/campaigns/asd
path.self=true //In order to include the current path as well for searching
property=abc
property.1_value=%xyz%
property.2_value=%abc%
property.operation=like
p.limit=-1
</code></pre>
<p>Possible things which you can check</p>
<ol>
<li>Check if the path that you are trying to search contains the desired nodes/properties.</li>
<li>Check if the property name that you are using is right.</li>
<li>If you want to match exact values, you can avoid using the like operator and remove the wild cards from the values.</li>
</ol>
|
MySQL select since sum >= 3? <p>Table:</p>
<pre><code>+++++++++++++++++++++++++
+ id | event | group_id +
+ 1 | '+1' | 1 +
+ 2 | 'pt' | 1 +
+ 3 | 'pt' | 1 +
+ 4 | '+1' | 1 +
+ 5 | 'pt' | 1 +
+ 6 | '+1' | 1 +
+ 7 | 'pt' | 1 +
+ 8 | '+1' | 1 +
+++++++++++++++++++++++++
</code></pre>
<p>I need to select <code>SUM(CASE WHEN event = '+1' THEN 1 ELSE 0 END)</code> since <code>SUM(CASE WHEN event = 'pt' THEN 1 ELSE 0 END) = 3</code>.</p>
<p>I tried this:</p>
<pre><code>SELECT group_id, SUM(CASE WHEN event = '+1' THEN 1 ELSE 0 END) AS event_sum
FROM Table
WHERE SUM(CASE WHEN event = 'pt' THEN 1 ELSE 0 END) >= 3
ORDER BY id
GROUP BY group_id
</code></pre>
<p>But this is not the way how group function works, so how could I achieve this output ? Do I need to use user variable to select id when condition <code>SUM(CASE WHEN event = 'pt' THEN 1 ELSE 0 END) = 3</code> is true ? I believe that it is possible to do it without user variable, is it possible ?</p>
<p>Desired output:</p>
<pre><code>++++++++++++++++++++++++
+ group_id | event_sum +
+ 1 | 2 +
++++++++++++++++++++++++
</code></pre>
| <p>You want the number of all +1 events <strong>since</strong> the moment you get at least 3 'pt' events.</p>
<p>For 'since', I guess you want to order the events by ID.</p>
<p>For pt, you need a <em>running total</em>. To achieve this in MySQL there are several answers on Stack Overflow (<a href="http://stackoverflow.com/questions/664700/calculate-a-running-total-in-mysql">this</a> is one).</p>
<pre><code>SET @pts:=0;
SELECT
*,
(@pts := @pts + (CASE WHEN event='pt' THEN 1 ELSE 0)) AS pts
FROM Table
ORDER BY id;
</code></pre>
<p>But you want the count to be reset at every change of groupid, so:</p>
<pre><code>SET @pts:=0,@gid:=-1;
SELECT *,
(@pts := IF (@gid != groupid, 0, @pts + IF(event='pt', 1, 0))) AS pts,
@gid:=groupid
FROM eventi ORDER BY groupid, id;
</code></pre>
<p>So at every loop you save the current groupid value, but before doing so, you check if it's the same. If it is not, then you zero pts count.</p>
<pre><code>+------+-------+---------+------+---------------+
| id | event | groupid | pts | @gid:=groupid |
+------+-------+---------+------+---------------+
| 1 | pt | 1 | 0 | 1 |
| 2 | pt | 1 | 1 | 1 |
| 3 | +1 | 1 | 1 | 1 |
| 4 | pt | 1 | 2 | 1 |
| 5 | +1 | 1 | 2 | 1 |
| 6 | +1 | 1 | 2 | 1 |
| 7 | pt | 2 | 0 | 2 |
| 8 | pt | 2 | 1 | 2 |
| 9 | +1 | 2 | 1 | 2 |
| 10 | pt | 2 | 2 | 2 |
| 11 | +1 | 2 | 2 | 2 |
| 12 | +1 | 2 | 2 | 2 |
+------+-------+---------+------+---------------+
</code></pre>
<p>From here you see that the number of actual pts' is off by one (the check is done in reverse order than the increment).</p>
<p>Now you can do the grouping:</p>
<pre><code>SET @pts:=0,@gid:=-1;
SELECT groupid, SUM(IF(pts >= 3 AND event='+1', 1,0)) AS event_sum FROM (
SELECT *,
(@pts := IF(@gid!=groupid, 0, @pts+IF(event='pt',1,0)))+1 AS pts,
@gid:=groupid
FROM eventi ORDER BY groupid, id
) AS a GROUP BY groupid;
+---------+-----------+
| groupid | event_sum |
+---------+-----------+
| 1 | 2 |
| 2 | 2 |
+---------+-----------+
</code></pre>
<p>You can merge the SET in the same query, too:</p>
<pre><code>SELECT ... AS a, (SELECT @pts:=0,@gid:=-1) AS i GROUP BY groupid;
</code></pre>
<p>This is a <a href="http://sqlfiddle.com/#!9/18624b/4/0" rel="nofollow">test SQLfiddle</a>.</p>
|
load google map with no marker <p>i have a google map that is loaded from web service
if there is no data, i need to clear all markers.
i tried to set an IF on the success()</p>
<pre><code>success: function (data)
{
if (data.d.length > 0)
{
</code></pre>
<p>but it gives me an error, cannot read undefined</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> $(document).ready(function () {
CreateMarker();
$("#CBB_Provincia").change(function () {
// executes when HTML-Documection () {
deleteMarkers();
CreateMarker();
});
$("#CBB_Comune").change(function () {
deleteMarkers();
CreateMarker();
});
});
var map;
var markers = [];
function deleteMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
}
function CreateMarker() {
var params = {
"RcodProvincia": "' + $('#=CBB_Provincia option:selected').val() + '" ,
"RcodCitta": "' + $('#CBB_Comune option:selected').val() + '"
}
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url:"www.medicardonline.com\WebService.asmx/BindMapMarker",
data: JSON.stringify({ Rcodprovincia: $('#CBB_Provincia option:selected').val(),RcodCitta: $('#CBB_Comune option:selected').val() }),//{},//data: JSON.stringify(params),
dataType: "json",
success: function (data)
{
// if (d.length > 0)
//{
var myOptions = {
center: new google.maps.LatLng(data.d[0].Latitudine, data.d[0].Longitudine),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//zoom:14
map = new google.maps.Map(document.getElementById("idgoogleMap"), myOptions);
var ltlng = [];
for (var i = 0; i <= data.d.length-1; i++) {
ltlng.push(new google.maps.LatLng(data.d[i].Latitudine, data.d[i].Longitudine));
marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
icon: data.d[i].Icona,//'3.png',
title: data.d[i].Titolo,
position: ltlng[i]
});
(function (marker, i) {
google.maps.event.addListener(marker, 'click', function () {
infowindow = new google.maps.InfoWindow({ maxWidth: 250 });
infowindow.setContent(data.d[i].Titolo);
infowindow.open(map, marker);
});
})(marker, i);
}
//}
},
error: function (result) {
alert("Error "+result.message);
}
});
};
</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCZjWZloCrmrulw2NocCDcjqCdiU7JjcGY"></script>
<select name="CBB_Provincia" id="CBB_Provincia">
<option selected="selected" value=""></option>
<option value="GR">Grosseto</option>
<option value="IM">Imperia</option>
<option value="IS">Isernia</option>
<option value="SP">La Spezia</option>
<option value="AQ">L&#39;Aquila</option>
<option value="LT">Latina</option>
<div id="UPComuni">
Comune
<select name="CBB_Comune" id="CBB_Comune">
<option value=""></option>
</select>
</div>
<table width="100%">
<tr>
<td>
<div id="idgoogleMap" style="width:100%; height: 400px" />
</td>
</tr>
</table></code></pre>
</div>
</div>
</p>
<p>you can try a simple page here : <a href="http://www.medicardonline.com/prova.aspx" rel="nofollow">http://www.medicardonline.com/prova.aspx</a></p>
| <p>How about:</p>
<pre><code>// if data exists and data.d exists and has a length of > 0
if ((data && data.d && (data.d.length > 0))
</code></pre>
|
PHP bindParam variable error <p>In my web service I have a problem with <code>bindParams</code>. Here is my code:</p>
<pre><code>$stmt = $this->db->prepare("SELECT data FROM sless WHERE ST_CONTAINS(data.area, Point(:query))");
$stmt->bindParam(':query', $queryText, PDO::PARAM_STR);
</code></pre>
<p>but <code>:query</code> variable isnt correctly adapted this code.</p>
<p>When I echo <code>$queryText</code> it gives <code>29.029087,40.990361</code> perfectly. But in the code it's not working. By the way when I write <code>29.029087,40.990361</code> latitude and longitude instead of the variable <code>:query</code> my code working perfectly. Here is the code:</p>
<pre><code>$stmt = $this->db->prepare("SELECT data FROM sless WHERE ST_CONTAINS(data.area, Point(29.029087,40.990361))");
</code></pre>
<p>How can I solve the problem?</p>
| <p>Try both coordinate separately</p>
<pre><code>list($lat, $lng) = split(',', $queryText);
$stmt = $this->db->prepare("SELECT data FROM sless WHERE ST_CONTAINS(data.area, Point(:lat,:lng))");
$stmt->bindParam(':lat', $lat, PDO::PARAM_STR);
$stmt->bindParam(':lng', $lng, PDO::PARAM_STR);
</code></pre>
|
Float value casted to char <p>In the below code,</p>
<pre><code>#include<stdio.h>
int main(){
char array[] = {'1', 2, 5.2};
char* my_pointer = array[2];
printf("%c", *my_pointer);
}
</code></pre>
<p><code>5.2</code> is stored in IEEE 754 representation in memory, <code>char</code> picks 8 bits(first) from this float representation, due to little endian format.</p>
<p>C is a loosely typed language. Am allowed to cast <code>float</code> to <code>char</code>.</p>
<p>Why the program is core dumped? </p>
| <p>In your program change <code>char *my_pointer = array[2];</code> to <code>char *my_pointer = &array[2];</code> as pointer should store the address.</p>
<pre><code>#include<stdio.h>
int main(){
char array[] = {'1', 2, 45.2};
char *my_pointer = &array[2];
printf("%c", *my_pointer);
}
</code></pre>
<p><strong>output:</strong></p>
<pre><code>- //NOTE: asci value of - is 45
</code></pre>
<p>as <a href="http://stackoverflow.com/users/187690/ant"><strong>@AnT</strong></a> has mentioned in comments, when you convert <code>45.2</code> to <code>char</code> type, the compiler will generate code that loads <code>45.2</code>, truncates the value and stores it in your <code>char</code> variable as <code>45</code>, so when you print you get <code>-</code> as output.</p>
|
Combine values in all rows when column header is the same <p>Another tricky problem. I have a cleaned data set with another macro, where I need to loop over the column headers and for each row, combine the values of the columns with the same header name in the first column, separated by <code>;</code></p>
<p>Sample data:</p>
<pre><code>Test Country Test Country
123 456 789 012
abc def ghi jkl
mno pqr stu vwx
</code></pre>
<p>Desired output:</p>
<pre><code>Test Country
123;789 456;012
abc;ghi def;jkl
</code></pre>
<p>I have tried something like this which definitely didn't work:</p>
<pre><code> Dim i As Long
i = 1
j = 1
Do Until Len(Cells(i, j).Value) = 0
If Cells(i, j).Value = Cells(i, j + 1).Value Then
Cells(i, j).Value = Cells(i, j).Value & ";" & Cells(i, j + 1).Value
Rows(j + 1).Delete
Else
i = i + 1
j = j + 1
End If
Loop
</code></pre>
| <p>After a nice chat as agreed ... </p>
<pre><code>Sub ForLoopPair()
Dim lastRow As Integer: lastRow = Cells(xlCellTypeLastCell).Row ' or w/e you had
Dim lastCol As Integer: lastCol = Cells(xlCellTypeLastCell).Column ' or w/e you had
For DestCol = 1 To lastCol
For ReadCol = DestCol + 1 To lastCol
If Cells(1, DestCol) = Cells(1, ReadCol) Then
For i = 2 To lastRow
If Cells(i, ReadCol) <> "" Then
Cells(i, DestCol) = Cells(i, DestCol) & ";" & Cells(i, ReadCol)
End If
Next i
End If
Next ReadCol
Next DestCol
For DestCol = 1 To lastCol
If Cells(1, DestCol) = "" Then Exit For
For ReadCol = lastCol To (DestCol + 1) Step -1
If Cells(1, DestCol) = Cells(1, ReadCol) Then
Columns(ReadCol).Delete
End If
Next
Next
End Sub
</code></pre>
|
Getting Microsoft Graph Drive items by path using the .NET SDK <p>As it is <a href="https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_list_children" rel="nofollow">documented</a>, using the Microsoft Graph REST API you can (among other options) get an item by Id or Path. This works fine, as expected:</p>
<pre><code>GET /me/drive/items/{item-id}/children
GET /me/drive/root:/{item-path}:/children
</code></pre>
<p>Using the .NET SDK, I can get a folder by Id (i.e. the first case):</p>
<pre><code>var items = await graphClient.Me.Drive.Items[myFolderId].Children.Request().GetAsync();
</code></pre>
<p>However, I couldn't find how (using the .NET SDK) to do the same, but specifying a path instead of an Id (i.e. the second case).</p>
<p>I don't want to find an Id of a path I already know, to create the request for it. Right?</p>
<p>I'm afraid is not possible to do this using the current SDK (Microsoft Graph Client Library 1.1.1)?</p>
| <p>This is how:</p>
<pre><code>var items = await graphClient.Me.Drive.Root
.ItemWithPath("/this/is/the/path").Children.Request().GetAsync();
</code></pre>
<p>Use just the plain path. Don't include the ":", and don't include the "/drive/root:/".</p>
<p>it was obvious, now that I see it...</p>
|
php pdo prepares query but does not execute it <p>I'm really new to php and pdos. A friend of mine basically created a pdo class and a couple of examples of how to use it and that's been working great for me. But now I want to do a query that uses the <code>BETWEEN</code> mysql keyword and returns anything that matches the criteria but it just comes up blank. I have created <code>mysql_query.log</code> file and from what I can gather from it the query gets prepared but not executed. I'll show you my findings from the log in a second, let me quickly just show you my code:</p>
<pre><code>$newSlot = array(
"fromDate" => $db->mysql_escape_mimic($startDate->format('Y-m-d H:i:s')),
"untilDate" => $db->mysql_escape_mimic($endDate->format('Y-m-d H:i:s'))
);
$query = "SELECT * FROM schedule_slot WHERE (startDate BETWEEN :fromDate AND :untilDate) OR (endDate BETWEEN :fromDate AND :untilDate);";
$result = $db->prepare($query);
$slot = null;
if($result == 1) {
$result = $db->execute($newSlot);
if($result == 1) {
$slot = $db->fetch();
}
}
print "slot: " . $slot["startDate"];
</code></pre>
<p>Here's the applicable part of the log (which I tidied up a bit):</p>
<pre><code>161010 20:59:31
2 Connect root@localhost as anonymous on test
2 Prepare SELECT * FROM schedule_slot WHERE (startDate BETWEEN ? AND ?) OR (endDate BETWEEN ? AND ?)
2 Close stmt
2 Quit
</code></pre>
<p>And here's an example from the log of a query that actually worked out fine for me:</p>
<pre><code>161010 21:01:07
3 Connect root@localhost as anonymous on test
3 Prepare INSERT INTO schedule_slot(startDate, endDate) VALUES(?,?)
161010 21:01:08
3 Execute INSERT INTO schedule_slot(startDate, endDate) VALUES('2016-10-11 13:35:00','2016-10-11 14:35:00')
3 Close stmt
3 Quit
</code></pre>
<p>Let me know if you want me to edit the pdo code or anything else in but as far as I can tell it's a standard pdo class. Please let me know why my query isn't returning anything</p>
<p><strong>Edit</strong>: Here's the pdo class, filename <code>dbpdo.php</code>:</p>
<pre><code><?php
class dbpdo {
private $_connection;
private $_statement;
public function __construct( ) {}
public function connect( $host, $username, $password, $database ) {
$connect = 'mysql:host='.$host.';dbname='.$database.';charset=utf8mb4';
$this->_connection = new PDO($connect, $username, $password);
$this->_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->_connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
public function __destruct() {
if ($this->_connection)
$this->_connection = null;
}
public function query($query){
try {
return $this->_connection->query($query);
} catch(PDOException $e) {
return "Error: " . $e->getMessage();
}
}
public function fetch(){
try {
return $this->_statement->fetch();
} catch(PDOException $e) {
return "Error: " . $e->getMessage();
}
}
public function prepare($query) {
try {
$this->_statement = $this->_connection->prepare($query);
return 1;
} catch(PDOException $e) {
return "Error: " . $e->getMessage();
}
}
public function execute($array) {
try {
$this->_statement->execute($array);
return 1;
} catch(PDOException $e) {
return "Error: " . $e->getMessage();
}
}
public function mysql_escape_mimic($inp) {
if(is_array($inp))
return array_map(__METHOD__, $inp);
if(!empty($inp) && is_string($inp)) {
return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $inp);
}
return $inp;
}
}
</code></pre>
| <p>First when things are going wrong add these 2 lines after your <code><?php</code> tag as far to many people develop on LIVE servers where error reporting will of course be turned off, and assume there is nothing wrong with their code when in reality it is generating lots of errors.</p>
<pre><code><?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
</code></pre>
<p>Then set PDO to throw exceptions</p>
<pre><code>$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$newSlot = array(
":f1" => $startDate->format('Y-m-d H:i:s')),
":u1" => $endDate->format('Y-m-d H:i:s')),
":f2" => $startDate->format('Y-m-d H:i:s')),
":u2" => $endDate->format('Y-m-d H:i:s'))
);
$query = "SELECT * FROM schedule_slot
WHERE (startDate BETWEEN :f1 AND :u1)
OR (endDate BETWEEN :f2 AND :u2)";
$result = $db->prepare($query);
// now execute the prepared query on $result not $db
$result = $result->execute($newSlot);
$row = $result->fetch_object();
print "slot: " . $row->startDate;
</code></pre>
<p>Now if any errors occur you will see them on the page, or you will see an exception throw, but not caught, so that will also show on the web page</p>
|
A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column 'Id' in TPT inheritance <p>I'm using EF code first, I have following entities:</p>
<p><a href="http://i.stack.imgur.com/nZL4C.png" rel="nofollow"><img src="http://i.stack.imgur.com/nZL4C.png" alt="enter image description here"></a></p>
<p>I'm using <code>TPT</code> method for inheritance, to create one-to-one or zero relation, wrote following code:</p>
<pre><code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>()
.HasOptional(x => x.ProductionInstruction)
.WithRequired(x => x.Order);
}
</code></pre>
<p>I write following code to save a <code>ProductionInstruction</code>:</p>
<pre><code>var pi = new ProductionInstruction();
/* set pi properties */
ctx.ProductionInstructions.Add(pi);
ctx.SaveChanges();
</code></pre>
<p>I get following error when <code>ctx.SaveChanges()</code> run:</p>
<blockquote>
<p>A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'Id'.</p>
</blockquote>
<p>Is there any way to implement 1..0-1 between my two entities, without above error?</p>
| <p>In Entity Framework, a one-to-one mapping with a required principal is implemented by giving the dependent a primary key that's also a foreign key to the principal. The dependent copies its primary key from the principal.</p>
<p>In your case, EF wants <code>ProductionInstruction.Id</code> to be a foreign key to <code>Order.Id</code>, and its value should be copied from the <code>Order</code> it belongs to. However, because of the inheritance, <code>ProductionInstruction.Id</code> is an identity column (<em>store-generated</em>), so it can't be set in code.</p>
<p>You either have to remove the inheritance, so <code>ProductionInstruction.Id</code> can be mapped as not store-generated, or change the mapping to optional on both sides. The latter will give <code>ProductionInstruction</code> a separate foreign key to <code>Order</code>.</p>
|
Bootstrap centering menu element <p>I have troubles centering the logo and menu in the md and sm view.</p>
<p>I want to animate margin of brandlogo and li in menu so margin auto and position absolute is nogo</p>
<p>TransformX and col-offset is kinda centering but not pixel perfect and when animatin margin the logo and menu do not stay centered.</p>
<pre><code><nav class="navbar navbar-default navbar-fixed-top container menufix">
<div class="row row-eq-height" id="rowmenu">
<div class="row row-eq-height-resp">
<!-- Brand Logo -->
<div class="col-xs-10 col-sm-12 col-md-12 col-lg-12">
<a class="navbar-brand" id="brand-logo" href="#">
<img alt="BrandLogo" class="brandlogo" src="/wp-content/themes/kdproduction/logo.png">
</a>
</div>
<!-- Brand and toggle - mobile display -->
<div class="col-xs-2 hidden-lg hidden-md hidden-sm">
<button type="button" class="btn-resp-style" data-toggle="collapse" data-target=".navbar-collapse">SVG</button>
</div>
</div>
<!-- Main Top nav -->
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-8" >
<div class="navbar-collapse collapse">
<?php wp_nav_menu( array(
'theme_location' => 'primary',
'container' => false,
'menu_id' => 'kdnavmenulista',
'menu_class' => 'nav navbar-nav navbar-header kdnavmenulista'
));
?>
</div><!-- /.navbar-collapse -->
</div>
</div>
</nav><!-- /.container -->
</code></pre>
| <p>Instead of this:</p>
<pre><code><a class="navbar-brand" id="brand-logo" href="#">
<img alt="BrandLogo" class="brandlogo" src="/wp-content/themes/kdproduction/logo.png">
</a>
</code></pre>
<p>try and put this:</p>
<pre><code><div style="width:100%; display:flex; justify-content:center; align-items:center;">
<a class="navbar-brand" id="brand-logo" href="#">
<img alt="BrandLogo" class="brandlogo" src="/wp-content/themes/kdproduction/logo.png">
</a>
</div>
</code></pre>
<p>Let me know if it worked.</p>
|
How do I build a matrix using two vectors? <p>So I need to build a matrix of <code>x</code> and <code>y</code> coordinates. I have the <code>x</code> stored in one matrix called <code>vx=0:6000;</code> and <code>y</code> stored in <code>Vy=repmat(300,1,6000);</code>.</p>
<p>Values in <code>x</code> are <code>0,1,2,...,5999,6000</code>.
Values in <code>y</code> are <code>300,300,...,300,300</code>.</p>
<p>How do I build a "vector" with the <code>x,y</code> coordinates above? </p>
<p>It would look like this <code>[(0,300);(1,300);...;(5999,300);(6000,300)]</code>.</p>
<p>After I finish doing this, I am going to want to find the distance between another fixed point <code>x,y</code> (that I will replicate <code>6000</code> times) and the vector above, in order to make a distance graph over time. </p>
<p>Thank you so much!</p>
| <p>You can just use horizontal concatenation with <code>[]</code></p>
<pre><code>X = [Vx(:), Vy(:)];
</code></pre>
<p>If you want to compute the distance between another point and every point in this 2D array, you could do the following:</p>
<pre><code>point = [10, 100];
distances = sqrt(sum(bsxfun(@minus, X, point).^2, 2));
</code></pre>
<p>If you have R2016b or newer you can simply do</p>
<pre><code>distances = sqrt(sum((X - point).^2, 2));
</code></pre>
|
Horizontal Bar Chart on Pandas Data Frame with Dynamic Column Names <p>I have the following source data (which comes from a csv file):</p>
<pre><code>ABC,2016-6-9 0:00,95,"{'//Purple': [115L], '//Yellow': [403L], '//Blue': [16L], '//White-XYZ': [0L]}"
ABC,2016-6-10 0:00,0,"{'//Purple': [219L], '//Yellow': [381L], '//Blue': [90L], '//White-XYZ': [0L]}"
ABC,2016-6-11 0:00,0,"{'//Purple': [817L], '//Yellow': [21L], '//Blue': [31L], '//White-XYZ': [0L]}"
ABC,2016-6-12 0:00,0,"{'//Purple': [80L], '//Yellow': [2011L], '//Blue': [8888L], '//White-XYZ': [0L]}"
ABC,2016-6-13 0:00,0,"{'//Purple': [32L], '//Yellow': [15L], '//Blue': [4L], '//White-XYZ': [0L]}"
DEF,2016-6-16 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [3L]}"
DEF,2016-6-17 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [0L]}"
DEF,2016-6-18 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [7L]}"
DEF,2016-6-19 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [14L]}"
DEF,2016-6-20 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [21L]}"
</code></pre>
<p>I use <a href="http://stackoverflow.com/questions/39928273/how-to-remove-curly-braces-apostrophes-and-square-brackets-from-dictionaries-in">How to remove curly braces, apostrophes and square brackets from dictionaries in a Pandas dataframe (Python)</a> to transform that data into a Data Frame that I can use to plot certain variables. The Data Frame looks as follows (note: not the same data as what's in the source csv file, but the structure is the same):</p>
<pre><code> Company Date Code Yellow Blue White Black
0 ABC 2016-6-9 115 403 16 19 472
1 ABC 2016-6-10 219 381 90 20 2474
2 ABC 2016-6-11 817 21 31 88 54
3 ABC 2016-6-12 80 2011 8888 0 21
4 ABC 2016-6-13 21 15 46 20 56
5 DEF 2016-6-16 64 42 76 4 41
6 DEF 2016-6-17 694 13 84 50 986
7 DEF 2016-6-18 325 485 38 60 174
8 DEF 2016-6-19 418 35 174 251 11
9 DEF 2016-6-20 50 56 59 19 03
</code></pre>
<p>I need to create several time series plots of the colors (which I can do very easily, given the way that the data frame is constructed). </p>
<p>But, I also want to be able to make a horizontal bar plot <strong>as of a specific date</strong> (see <a href="https://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_barplot.html" rel="nofollow">https://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_barplot.html</a> for an example).</p>
<p>For instance, using my data, as of June 9, 2016, the bar plot would look as follows (not to scale):</p>
<pre><code>Black: ********************************
Yellow: **************************
White: ***
Blue: **
</code></pre>
<p>The problem I'm having is that the column names (e.g. 'yellow', 'blue', 'white' and 'black') can change, as can the number of columns.</p>
<p>Does anyone know if it is possible to loop through a certain number of columns <strong>to the right</strong> of the 'Code' column and then use those to create a horizontal bar chart similar to what's above? Or, perhaps take a slice of the data to the right of the 'Code' column? </p>
<p>Or, does the Data Frame itself need to be structured differently such that it can be used to make both a time series plot and a horizontal bar chart?</p>
<p>Thanks!</p>
| <p>in order to loop through a certain number of columns to the right of the 'code' column I would do something of the form</p>
<pre><code>for col in df.columns[3:]:
plot(col)
</code></pre>
<p>However this only works if you can guarantee that your columns will always be in the same order. Alternatively you could make sure that the columns of interest for that particular chart are named in a systematic way.</p>
<p>Hope this helps!</p>
|
Getting verify error when working with asm java <p>So basicly Im trying to add a simple <code>System.out.println("hey");</code>
at the end of a method. I used the tree API. I do however keep getting this error:</p>
<blockquote>
<p>java.lang.VerifyError: Expecting a stackmap frame at branch target 38</p>
</blockquote>
<p>This is my code:</p>
<pre><code>public class MethodNodeCustom extends MethodNode {
public MethodNodeCustom(int paramInt, String paramString1, String paramString2, String paramString3, String[] paramArrayOfString) {
this(327680, paramInt, paramString1, paramString2, paramString3, paramArrayOfString);
return;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public MethodNodeCustom(int paramInt1, int paramInt2, String paramString1, String paramString2, String paramString3,
String[] paramArrayOfString) {
super(paramInt1);
this.access = paramInt2;
this.name = paramString1;
this.desc = paramString2;
this.signature = paramString3;
this.exceptions = new ArrayList((paramArrayOfString == null) ? 0 : paramArrayOfString.length);
int i = ((paramInt2 & 0x400) != 0) ? 1 : 0;
if (i == 0)
this.localVariables = new ArrayList(5);
this.tryCatchBlocks = new ArrayList();
if (paramArrayOfString != null)
this.exceptions.addAll(Arrays.asList(paramArrayOfString));
this.instructions = new InsnList();
}
@Override
public void visitEnd() {
AbstractInsnNode label = instructions.getLast();
instructions.remove(instructions.getLast());
instructions.remove(instructions.getLast());
visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", Type.getDescriptor(PrintStream.class));
visitLdcInsn("Cracked by damm ass pro skills");
visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
visitInsn(Opcodes.RETURN);
instructions.add(label);
super.visitEnd();
}
}
</code></pre>
<p>And this is my class node:</p>
<pre><code>public class ClassNodeCustom extends ClassNode {
public ClassNodeCustom() {
super(ASMContentHandler.ASM4);
}
@SuppressWarnings("unchecked")
@Override
public MethodVisitor visitMethod(int paramInt, String paramString1, String paramString2, String paramString3, String[] paramArrayOfString) {
MethodNode localMethodNode = new MethodNodeCustom(paramInt, paramString1, paramString2, paramString3, paramArrayOfString);
this.methods.add(localMethodNode);
return localMethodNode;
}
}
</code></pre>
<p>And this is how I "inject" the code (I load it directly from the jar thats why it is using a zipFile)</p>
<pre><code>InputStream in = zipFile.getInputStream(entry);
ClassReader cr = new ClassReader(in);
ClassNodeCustom node = new ClassNodeCustom();
cr.accept(node, 0);
ClassWriter cw = new ClassWriter(0);
node.accept(cw);
</code></pre>
<p>And like I said when ever I run it I get the verify error is there any way for me to solve it or any smarter way for me to "inject" that code ?</p>
| <p>If you are adding code at the end of a method, you are adding it after its last instruction which is always a goto, switch, throw or return statement when compiling Java code. Even when compiling a method without an explicit return statement like</p>
<pre><code>void foo() { }
</code></pre>
<p>you are actully compiling </p>
<pre><code>void foo() { return; }
</code></pre>
<p>where the final return is implicit. With your additions, you change the method to</p>
<pre><code>void foo() {
return;
System.out.println("hey");
}
</code></pre>
<p>Such unreachable code is forbidden by <em>javac</em> but perfectly legal in byte code. For unreachable code, it is however required that you are prepending it with a <a href="http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.4" rel="nofollow">stack map frame</a> that describes the state of the stack and the local variable array at that point. It would be easy enough to add a description of an empty frame at this point but I assume that you want to add the code before the return statement. </p>
<p>To implement this, <a href="http://asm.ow2.org/asm50/javadoc/user/org/objectweb/asm/commons/AdviceAdapter.html" rel="nofollow">ASM offers an <code>AdviceAdapter</code></a> that allows you to add code before return statements. As far as I know, there is nothing similar for the tree API but you can simply look for a return node within any method's instruction list and add the code prior to it.</p>
|
converting string to data in swift 3.0 <p>I'm trying to convert a string to a data type. I thought this was all I needed but if I try to print it it just prints "12 bytes"</p>
<pre><code>let tString = "Hello World!"
if let newData = tString.data(using: String.Encoding.utf8){
print(newData)
self.peripheral?.writeValue(newData, for: positionCharacteristic, type: CBCharacteristicWriteType.withResponse)
}
</code></pre>
<p>What am I doing wrong?</p>
| <p>You are not doing anything wrong. That's just how Data currently does its debug printout. It has changed over time. It has at times printed more like NSData. Depending on the debug print format is pretty fragile, I think it's better to just own it more directly. I have found the following pretty useful:</p>
<pre><code>extension Data {
func hex(separator:String = "") -> String {
return (self.map { String(format: "%02X", $0) }).joined(separator: separator)
}
}
</code></pre>
<p>This allows me to replace your simple <code>print(newData)</code> with something like</p>
<pre><code>print(newData.hex())
</code></pre>
<p>or </p>
<pre><code>print(newData.hex(separator:"."))
</code></pre>
<p>if my eyes need help parsing the bytes</p>
<p><em>aside, I do quite a bit of BLE stuff myself, and have worked up a number of other useful Data extensions for BLE stuff</em></p>
|
Laravel 5.3 Error : Creating default object from empty value <p>The code below has an error. I am using Laravel 5.3 and php 7.0.</p>
<p>I google it but still not clear, any help would be greatly appreciated. </p>
<p><strong>ActivationService.php</strong></p>
<pre><code><?php
namespace App;
use Illuminate\Mail\Mailer;
use Illuminate\Mail\Message;
class ActivationService
{
protected $mailer;
protected $activationRepo;
protected $resendAfter = 24;
public function __construct(Mailer $mailer, ActivationRepository $activationRepo)
{
$this->mailer = $mailer;
$this->activationRepo = $activationRepo;
}
public function sendActivationMail($user)
{
if ($user->activated || !$this->shouldSend($user)) {
return;
}
$token = $this->activationRepo->createActivation($user);
$link = route('user.activate', $token);
$message = sprintf('Activate account <a href="%s">%s</a>', $link, $link);
$this->mailer->raw($message, function (Message $m) use ($user) {
$m->to($user->email)->subject('Activation mail');
});
}
public function activateUser($token)
{
$activation = $this->activationRepo->getActivationByToken($token);
if ($activation === null) {
return null;
}
$user = User::find($activation->user_id);
//Below is line 53.
$user->activated = true;
$user->save();
$this->activationRepo->deleteActivation($token);
return $user;
}
private function shouldSend($user)
{
$activation = $this->activationRepo->getActivation($user);
return $activation === null || strtotime($activation->created_at) + 60 * 60 * $this->resendAfter < time();
}
}
</code></pre>
<p><strong>Error message</strong></p>
<blockquote>
<p>ErrorException in ActivationService.php line 53: Creating default object from empty value</p>
</blockquote>
<p>Line 53 of the code above is like this:</p>
<pre><code>$user->activated = true;
</code></pre>
<p>How could I settle the issue? </p>
| <p>The problem is most likely because <code>$user = User::find($activation->user_id);</code> returns <strong>null</strong> or <strong>false</strong>.</p>
<p>When you end up in these kinds of situations always try dumping the variable where the problem is occurring, in this case <code>dd($activation->user_id)</code></p>
<p>I would suggest using <code>Auth::user()->id</code> instead.</p>
|
Knockout Mutliple Dropdowns that adds new items <p>Is it possible for me to have multiple dropdown menus (not a specific amount) that has Items and a New Item option that adds a new Item to the dropdown list.</p>
<p>For example there would be ~5 dropdowns and the user selects the Item number. When they select New Item it adds an Item to the list</p>
<p>This is as far as i get with it, not sure how i can handle this problem with knockout. Is it actually possible?</p>
<pre><code><select data-bind="options: items, optionsText: 'name', optionsValue: 'id', value: selectedChoice"></select>
<br/>
<select data-bind="options: items, optionsText: 'name', optionsValue: 'id', value: selectedChoice"></select>
<br/>
<select data-bind="options: items, optionsText: 'name', optionsValue: 'id', value: selectedChoice"></select>
<br/>
var Item = function(data){
var self = this;
self.id = ko.observable(data.id);
self.name = ko.observable(data.name);
};
var viewModel = function(data) {
var self = this;
self.selectedChoice = ko.observable();
self.items = ko.observableArray([
new Item({id: "1", name: "Item 1"}),
new Item({id: "2", name: "Item 2"}),
new Item({id: "3", name: "New Item"})]);
self.sendMe = function(){
alert(ko.toJSON({ selectedItemId: this.selectedChoice()}));
};
};
ko.applyBindings(new viewModel());
</code></pre>
<p><a href="https://jsfiddle.net/dqUAz/1470/" rel="nofollow">https://jsfiddle.net/dqUAz/1470/</a></p>
| <p>One way of accomplishing this would be to subscribe to the <b>selectedChoice</b> observable and update the array anytime 'New Item' is selected:</p>
<pre><code>self.selectedChoice.subscribe(function(newValue) {
var lastItem = self.items()[self.items().length - 1];
if (newValue === lastItem.id()) {
// Add the new item
var id = self.items().length + 1;
var name = 'Item ' + self.items().length;
var item = new Item({id: id, name: name});
self.items.push(item);
// Drop and re-add the 'New Item' item so that it remains at the bottom
self.items.remove(lastItem);
self.items.push(lastItem);
// Select the newly added item
self.selectedChoice(id);
}
});
</code></pre>
<p><b>Fiddle:</b> <a href="https://jsfiddle.net/dw1284/60n7078s/2/" rel="nofollow">https://jsfiddle.net/dw1284/60n7078s/2/</a></p>
|
Using $ notation in middle of C-Shell statement <p>I have a bunch of directories to process, so I start a for loop like this:</p>
<pre><code>foreach n (1 2 3 4 5 6 7 8)
</code></pre>
<p>Then I have a bunch of commands where I am copying over a few files from different places </p>
<pre><code>cp file1 dir$n
cp file2 dir$n
</code></pre>
<p>but I have a couple commands where the $n is in the middle of the command like this:</p>
<pre><code>cp -r dir$nstep1 dir$n
</code></pre>
<p>When I run this command, the shell complains that it cannot find the variable $nstep1. What i want to do is evaluate the $n first and then concatenate the text around it. I tried using `` and (), but neither of those work. How to do this in csh?</p>
| <p>In this respect behavior is similar to POSIX shells:</p>
<pre><code>cp -r "dir${n}step1" "dir${n}"
</code></pre>
<hr>
<p>The quotes prevent string-splitting and glob expansion. To observe what this means, compare the following:</p>
<pre><code># prints "hello * cruel * world" on one line
set n=" * cruel * "
printf '%s\n' "hello${n}world"
</code></pre>
<p>...to this:</p>
<pre><code># prints "hello" on one line
# ...then a list of files in the current directory each on their own lines
# ...then "cruel" on another line
# ...then a list of files again
# ... and then "world"
set n=" * cruel * "
printf '%s\n' hello${n}world
</code></pre>
<p>In real-world cases, correct quoting can thus be the difference between deleting the oddly-named file you're trying to operate on, and deleting everything else in the directory as well.</p>
|
How to convert array to UnsafeMutablePointer<UnsafeRawPointer?> Swift 3.0? <p>Here was my workable code in the previous version of Swift:</p>
<pre><code> let imageOptionsDictKeys = [ kCVPixelBufferPixelFormatTypeKey, kCVPixelBufferWidthKey, kCVPixelBufferHeightKey, kCVPixelBufferOpenGLESCompatibilityKey, kCVPixelBufferIOSurfacePropertiesKey]
let imageOptionsDictValues = [ cvPixelFormatType, frameW, frameH, boolYES]
var keyCallbacks = kCFTypeDictionaryKeyCallBacks
var valueCallbacks = kCFTypeDictionaryValueCallBacks
let imageOptions = CFDictionaryCreate(kCFAllocatorDefault, UnsafeMutablePointer(imageOptionsDictKeys), UnsafeMutablePointer(imageOptionsDictValues), 4, &keyCallbacks, &valueCallbacks)
</code></pre>
<p>After changes in the Swift 3.0 I have to convert my keys and values arrays into <code>UnsafeMutablePointer<UnsafeRawPointer?></code> for creating CFDictionary.</p>
<p>This way:</p>
<pre><code> let imageOptionsDictKeysPointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 1)
imageOptionsDictKeysPointer.initialize(to: imageOptionsDictKeys)
</code></pre>
<p>gives an Bad Access error.</p>
<p>And after reading documentation I am trying to compile this code:</p>
<pre><code> let imageOptionsDictKeys = [kCVPixelBufferPixelFormatTypeKey, kCVPixelBufferWidthKey, kCVPixelBufferHeightKey, kCVPixelBufferOpenGLESCompatibilityKey]
let imageOptionsDictKeysRawPointer = Unmanaged.passUnretained(imageOptionsDictKeys).toOpaque()
let imageOptionsDictKeysPointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 1)
imageOptionsDictKeysPointer.initialize(to: imageOptionsDictKeysRawPointer)
let imageOptionsDictValues = [ cvPixelFormatType, frameW, frameH, boolYES]
let imageOptionsDictValuesRawPointer = Unmanaged.passUnretained(imageOptionsDictValues).toOpaque()
let imageOptionsDictValuesPointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 1)
imageOptionsDictValuesPointer.initialize(to: imageOptionsDictValuesRawPointer)
let imageOptions = CFDictionaryCreate(kCFAllocatorDefault, imageOptionsDictKeysPointer, imageOptionsDictValuesPointer, 4, &keyCallbacks, &valueCallbacks)
</code></pre>
<p>but error <strong>Generic parameter 'Instance' could not be inferred</strong> appears in the lines <strong>Unmanaged.passUnretained(<em>array</em>).toOpaque()</strong></p>
<p>I have no idea how to create CFDictionary programmatically now.</p>
| <p>I just solved a similar issue converting arrays to <code>UnsafeMutablePointer< UnsafeMutablePointer<T>></code> which you can find here:
<a href="http://stackoverflow.com/questions/40128275/swift-3-unsafemutablepointer-initialization-for-c-type-float/40135482#40135482">Swift 3 UnsafeMutablePointer initialization for C type float**</a></p>
<p>To convert swift arrays using the same scheme, use <code>UnsafeMuTablePointer</code> as suggested here: <a href="http://technology.meronapps.com/2016/09/27/swift-3-0-unsafe-world-2/" rel="nofollow">http://technology.meronapps.com/2016/09/27/swift-3-0-unsafe-world-2/</a></p>
|
Java - how can I get the text from TextField <p>I'm a bloody beginner. I wanna make a login-screen but I encounter a compiler error:</p>
<pre><code>package passwordmanager;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
@SuppressWarnings("serial")
public class Frame extends JFrame
{
JLabel username;
JLabel password;
JTextField user;
JPasswordField pass;
JButton login;
public Frame()
{
//Frame
setLayout(null);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(425, 300);
setVisible(true);
setTitle("Password-Login");
//Label 1
username = new JLabel("Benutzernahme:");
username.setBounds(16, 50, 500, 15);
//Font
Font font1 = new Font("", Font.BOLD, 13);
username.setFont(font1);
add(username);
//Label2
password = new JLabel("Passwort:");
password.setBounds(16, 134, 200, 20);
password.setFont(font1);
add(password);
//TextField
user = new JTextField();
user.setBounds(16, 76, 350, 30);
user.setVisible(true);
add(user);
//PasswordField
pass = new JPasswordField();
pass.setBounds(16, 160, 350, 30);
pass.setVisible(true);
add(pass);
//Button
login = new JButton();
login.setBounds(0, 0, 5, 5);
add(login);
}
String myusername = user.getText();
String mypassword = new String(pass.getPassword());
public class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(myusername.equalsIgnoreCase("whatever") && mypassword.equalsIgnoreCase("whatever"))
{
System.out.println("NICE");
}
}
}
}
</code></pre>
<p>Eclipse says that this string</p>
<pre><code> String myusername = user.getText();
</code></pre>
<p>is wrong. Do you know how I can fix this?</p>
<p>Thank you in advance!:)</p>
| <p>This:</p>
<pre><code>String myusername = user.getText();
String mypassword = new String(pass.getPassword());
</code></pre>
<p>Has to be in a method or constructor...You can't place that code there. You can declare variables there but can't perform operations.</p>
<p>This part:</p>
<pre><code>myusername = user.getText();
mypassword = new String(pass.getPassword());
</code></pre>
<p>Should be in your constructor...or some other method.
You probably want it here:</p>
<pre><code>public void actionPerformed(ActionEvent e)
{
myusername = user.getText();
mypassword = new String(pass.getPassword());
if(myusername.equalsIgnoreCase("whatever") && mypassword.equalsIgnoreCase("whatever"))
{
System.out.println("NICE");
}
}
</code></pre>
|
Xcode 8 - Memory debugger doesn't work <p>I'm using Xcode 8 with Swift 3 to develop my app, but I noticed the Memory Debugger isn't working for some reason. Here the screenshot : <a href="http://i.stack.imgur.com/d5fPd.png" rel="nofollow"><img src="http://i.stack.imgur.com/d5fPd.png" alt="xcode 8 memory debugger"></a>
Do you know why? Is there something new I missed?</p>
| <p>I had the idea to check if NSZombie was enabled and yes, it was. Disable it make everything works. </p>
|
Creating a while loop to run a select statement against a list of DBs within the same server <p>We have servers with 100 DBs each. I want to run a select statement on approximately 50-75 of the databases on each server.</p>
<p>I can write a select statement to put the necessary DBs into a temp table.</p>
<p>From there I want to run a while loop that loops through each DB and runs the select statement, so that I can figure out which DBs have this active account. It needs to be run regularly which is why I am not just doing it manually.</p>
<p>Here is what I have. It gives me an error on my 'USE' command, saying incorrect syntax near @hospuse</p>
<pre><code>DECLARE @hospcounter INT;
DECLARE @hospuse varchar(100);
DECLARE @userlogin varchar(50);
SET @hospcounter = 0;
SET @hospuse = (select name from #tempdbnames where hospnumber = '1')
SET @userlogin = 'dmarch'
SELECT IDENTITY(int, 1,1) AS hospnumber, name into #tempdbnames
FROM master.dbo.sysdatabases
where name NOT LIKE ('%storage_0%')
AND NAME NOT LIKE ('%WSR%')
AND name NOT LIKE ('Z%')
AND name NOT LIKE ('master')
AND name NOT LIKE ('model')
AND name NOT LIKE ('msdb')
AND name NOT LIKE ('tempdb')
AND name NOT LIKE ('_Placeholder')
WHILE @hospcounter <= (select MAX(hospnumber) from #tempdbnames)
BEGIN
USE @hospuse
SELECT ro.user_login, ro.activated from rev_operator ro where ro.user_login = @userlogin and ro.activated != '0'
SET @hospcounter = @hospcounter + 1;
SET @hospuse = (select name from #tempdbnames where hospnumber = @hospcounter);
END;
PRINT 'Done';
GO
</code></pre>
<p>drop table #tempdbnames</p>
<p>I also tried this with sp_msforeachdb but couldn't figure out how to get the syntax right for filtering the DBs I wanted to use without literally saying NOT IN and listing every DB I didn't want. Which doesn't work because DBs get added regularly.</p>
| <p>When trying to run the same query across multiple databases, cursors actually will be a good option. </p>
<pre><code>DECLARE @Databases Table (DBName varchar(256))
DECLARE @Name varchar(256)
DECLARE @SQL Nvarchar(max)
DECLARE @userlogin varchar(50)
SET @userlogin = 'dmarch'
INSERT @Databases
select name from sys.databases where name NOT LIKE ('%storage_0%')
AND NAME NOT LIKE ('%WSR%')
AND name NOT LIKE ('Z%')
AND name NOT LIKE ('master')
AND name NOT LIKE ('model')
AND name NOT LIKE ('msdb')
AND name NOT LIKE ('tempdb')
AND name NOT LIKE ('_Placeholder')
DECLARE DBCursor Cursor For
Select DBName
from @Databases
OPEN DBCursor
FETCH NEXT
FROM DBCursor
INTO @Name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = N'USE ['+@Name+']
select ''['+@Name+']'', ro.user_login, ro.activated from rev_operator ro where ro.user_login = @userlogin and ro.activated != ''0'''
EXEC sp_executesql @SQL
FETCH NEXT
FROM DBCursor
INTO @Name
END
CLOSE DBCursor
DEALLOCATE DBCursor
</code></pre>
|
Pig Join by using OR conditional operator throws error <pre><code>child = load 'file_name' using PigStorage('\t') as (child_code : chararray, child_id : int, child_precode_id : int);
parents = load 'file_name' using PigStorage('\t') as (child_id : int, child_internal_id : chararray, mother_id : int, father_id : int);
joined = JOIN child by child_id, parents by child_id;
mainparent = FOREACH joined GENERATE child_id as child_id_source, child_precode_id, child_code;
store parent into '(location of file)' using PigStorage('\t');
childfirst = JOIN mainparent by (child_id_source), parents by (mother_id OR father_id);
firstgen = FOREACH childfirst GENERATE child_id, child_precode_id, child_code;
store firstgen into 'file_location' using PigStorage('\t');
</code></pre>
<p>Getting the following error when I use the OR condition:</p>
<blockquote>
<p>ERROR org.apache.pig.PigServer - exception during parsing: Error
during parsing. Pig script failed to parse:
NoViableAltException(91@[]) Failed to parse: Pig script failed to
parse: NoViableAltException(91@[])</p>
</blockquote>
| <p>The below syntax is incorrect,there is no conditional join in Pig</p>
<pre><code>childfirst = JOIN mainparent by (child_id_source), parents by (mother_id OR father_id);
</code></pre>
<p>If you would like to join a relation with one key with another relation on 2 keys then create two joins and union the dataset.Note that you might have to distinct the resulting relation.</p>
<pre><code>childfirst = JOIN mainparent by (child_id_source), parents by (mother_id);
childfirst1 = JOIN mainparent by (child_id_source), parents by (father_id);
childfirst2 = UNION childfirst,childfirst1;
childfirst3 = DISTINCT childfirst2;
firstgen = FOREACH childfirst3 GENERATE child_id, child_precode_id, child_code;
store firstgen into 'file_location' using PigStorage('\t');
</code></pre>
|
combobox dependent on another combobox - JavaFX <p>I have three combo box: Country, state and city</p>
<p>How can I become a dependent on another? For example, if I select Brazil appears their states and later the cities of selected state. But if I select United States in the country will show their states</p>
<p>I am using MySQL as the database, if you need some configuration in the database also tell me ... It's the first time you work with it, thank you very much.</p>
| <p>Register a listener with the country combo box and update the state combo box when the selected item changes:</p>
<pre><code>cbxCountry.valueProperty().addListener((obs, oldValue, newValue) -> {
if (newValue == null) {
cbxState.getItems().clear();
cbxState.setDisable(true);
} else {
// sample code, adapt as needed:
List<State> states = stateDAO.getStatesForCountry(newValue);
cbxState.getItems().setAll(states);
cbxState.setDisable(false);
}
});
</code></pre>
<p>You could also do this with bindings if you prefer:</p>
<pre><code>cbxState.itemsProperty().bind(Bindings.createObjectBinding(() -> {
Country country = cbxCountry.getValue();
if (country == null) {
return FXCollections.observableArrayList();
} else {
List<State> states = stateDAO.getStatesForCountry(country);
return FXCollections.observableArrayList(states);
}
},
cbxCountry.valueProperty());
</code></pre>
<p>(and if you want the disable functionality from the solution above also do <code>cbxState.disableProperty().bind(cbxCountry.valueProperty().isNull());</code>).</p>
|
Flask blueprint cannot read sqlite3 DATABASES from config file <p>I would like Python Flask to read from configuration file the location of the sqlite3 database name <strong>without explicitly writing database name</strong>. Templates used are: <a href="http://flask.pocoo.org/docs/0.11/patterns/sqlite3/" rel="nofollow">http://flask.pocoo.org/docs/0.11/patterns/sqlite3/</a> and <a href="http://flask.pocoo.org/docs/0.11/tutorial/dbcon/" rel="nofollow">http://flask.pocoo.org/docs/0.11/tutorial/dbcon/</a>.</p>
<p>When I try to read 'DATABASE' from my config file I get the following error message:</p>
<p>File "/app/my_cool_app/app/<strong>init</strong>.py", line 42, in before_request
g.db = connect_db()</p>
<p>File "/app/my_cool_app/app/<strong>init</strong>.py", line 36, in connect_db
return sqlite3.connect(my_cool_app.config['DATABASE'])</p>
<p>AttributeError: 'Blueprint' object has no attribute 'config'</p>
<p>Here is my <strong>init</strong>.py code when I try to read from the configuration file and get the above error:</p>
<pre><code>import sqlite3
from flask import Flask, g
from .views import my_cool_app
# create application
def create_app(debug=True):
app = Flask(__name__, instance_relative_config=True)
app.debug = debug
app.config.from_object('config')
app.config.from_pyfile('config.py')
app.register_blueprint(my_cool_app)
return app
def connect_db():
return sqlite3.connect(my_cool_app.config['DATABASE']) <= LINE 36
@my_cool_app.before_request
def before_request():
g.db = connect_db()
@my_cool_app.teardown_request
def teardown_request(exception):
db = getattr(g, 'db', None)
if db is not None:
db.close()
</code></pre>
<p>Here is my run.py (I don't change it):</p>
<pre><code>from app import create_app
app = create_app()
</code></pre>
<p>Here is my <strong>init</strong>.py code that works when I explicitly write DB name (not what I want):</p>
<pre><code>import sqlite3
from flask import Flask, g
from .views import my_cool_app
DATABASE='/app/myappname/my_sqlite3_database_name.db'
# create application
def create_app(debug=True):
app = Flask(__name__, instance_relative_config=True)
app.debug = debug
app.config.from_object('config')
app.config.from_pyfile('config.py')
app.register_blueprint(my_cool_app)
return app
def connect_db():
return sqlite3.connect(DATABASE)
</code></pre>
| <p>Your <code>my_cool_app</code> is an instance of <code>Blueprint</code> which doesn't have a <code>config</code> attribute. You need to use <code>current_app</code>:</p>
<pre><code>import sqlite3
from flask import Flask, g, current_app
from .views import my_cool_app
# create application
def create_app(debug=True):
app = Flask(__name__, instance_relative_config=True)
app.debug = debug
app.config.from_object('config')
app.config.from_pyfile('config.py')
app.register_blueprint(my_cool_app)
return app
def connect_db():
return sqlite3.connect(current_app.config['DATABASE'])
@my_cool_app.before_request
def before_request():
g.db = connect_db()
@my_cool_app.teardown_request
def teardown_request(exception):
db = getattr(g, 'db', None)
if db is not None:
db.close()
</code></pre>
|
Node JS multiple http request missing response <p>Hello I am working on node js http request with a loop and its size is 1728 and its response is missing like it stuck at 1727 kindly help me I am trying to fix this problem for three days.</p>
<pre><code>for ( let i = 0 ; i < playerLength ; i++ ) {
for ( let j = startYear ; j < currentYear ; j++ ) {
var playerSeasonData = {};
playerSeasonData.url = me.config.sport.url + league + '/v2/JSON/PlayerSeasonStatsByPlayer/'+ j +'/' + playerData[i].playerID;
playerSeasonData.method = 'GET';
playerSeasonData.headers = {};
playerSeasonData.headers = {'Ocp-Apim-Subscription-Key':'**********************'};
me.request( playerSeasonData ,function( error, response, data ){
count ++;
)};
}
</code></pre>
<p>}</p>
| <p>The problem you are having is that your function is returning before all the http requests have been completed.</p>
<p>Consider promisifying <code>me.request</code> via <code>bluebird</code> and then return a <code>Promise.all</code>. Here's an example: <a href="http://bluebirdjs.com/docs/api/promise.all.html" rel="nofollow">http://bluebirdjs.com/docs/api/promise.all.html</a></p>
|
How do I convert this over to an .ascx page? <p>I have this code working fine in a web app .cshtml file. However, I need to be able to convert this over to an .ascx file.</p>
<p>It's the @using expressions and the ajax.beginform that are causing me the issues. </p>
<p>Thank you.</p>
<pre><code>@{
ViewBag.Title = "Async File Upload";
}
<h2>Async File Upload</h2>
@using (Ajax.BeginForm("AsyncUpload", "dnndev.me/fileupload/Upload", new AjaxOptions() { HttpMethod = "POST" }, new { enctype="multipart/form-data"}))
{
@Html.AntiForgeryToken()
<input type="file" name="files" id="fu1"/>
<input type="submit" value="Upload File" />
}
<div class="progress">
<div class="progress-bar">0%</div>
</div>
<div id="status"></div>
<style>
.progress {
position:relative;
width:400px;
border:1px solid #ddd;
padding:1px;
}
.progress-bar {
width:0px;
height:20px;
background-color:#57be65;
}
</style>
@section scripts{
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function () {
var bar = $('.progress-bar');
var percent = $('.progress-bar');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function () {
status.empty();
var percentValue = '0%';
bar.width(percentValue);
percent.html(percentValue);
},
uploadProgress: function (event, position, total, percentComplete) {
var percentValue = percentComplete + '%';
bar.width(percentValue);
percent.html(percentValue);
},
success: function (d) {
var percentValue = '100%';
bar.width(percentValue);
percent.html(percentValue);
$('#fu1').val('');
alert(d);
},
complete: function (xhr) {
status.html(xhr.responseText);
}
});
})();
</script>
}
</code></pre>
| <p>Ok. Instead of fighting this and trying to make it work inside DotNetNuke, I took a different approach.</p>
<p>The ultimate goal behind this was to have an asynchronous file upload function in DNN so the user had some sort of feedback while a file was being uploaded. These are fairly big files -- 50-200mb -- and without feedback, especially on a slower link, the user did not know what was going on.</p>
<p>So, what I did was...</p>
<p>On my DNN server, I added a new site *outside of the dnn site * -- upload.mydomain.com, for instance -- and created an IIS application pointing to my MVC. The application simply provides asynchronous file uploads. It works great as a standalone so onto step 2.</p>
<p>I had to integrate it into DNN. So, I created a virtual directory in the upload.mydomain.com pointing to my DNN portals folder where the users upload their files into their own portals.</p>
<p>I created a DNN module called MyUpload and in the view.ascx of that module, I put in an iframe pointing to my upload application url. </p>
<p>In the script in the upload application view page (shown in my question), I added a couple of parent.PostMessage functions -- one when the download is in progress and one when the download has finished.</p>
<p>On the DNN module side, I write a listener that monitors the iframe post messages. </p>
<p>When the user clicks the upload button in the iframe (the MVC upload app), the listener in the module gets a "status" response and does a couple of things. The upload starts and the progress bar is displayed so the user gets some feedback. When the upload is finished uploading the file to the appropriate portal and folder (the upload MVC app has access to the DNN portals folder and subfolder because of the virtual directory), the MVC posts another message back to the parent with a status of "success".</p>
<p>The parent gets that message and goes on from there, processing the uploaded file in the appropriate manner. </p>
<p>That's essentially it. </p>
<p>-- MVC Script --</p>
<pre><code>@section scripts{
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
function parentExists() {
return (parent.location == window.location) ? false : true;
}
(function () {
var bar = $('.progress-bar');
var percent = $('.progress-bar');
var status = $('#status');
var running = false;
$('form').ajaxForm({
beforeSend: function () {
status.empty();
var percentValue = '0%';
bar.width(percentValue);
percent.html(percentValue);
},
uploadProgress: function (event, position, total, percentComplete) {
if (running === false) {
running = true;
parent.postMessage("status|running","*");
}
var percentValue = percentComplete + '%';
bar.width(percentValue);
percent.html(percentValue);
},
success: function (d) {
var percentValue = '100%';
bar.width(percentValue);
percent.html(percentValue);
alert(d);
//alert($('#fu1').val());
parent.postMessage("status|success|filename|" + $('#fu1').val(), "*");
$('#fu1').val('');
},
complete: function (xhr) {
status.html(xhr.responseText);
}
});
})();
</script>
}
</code></pre>
<p>--Module listener --</p>
<pre><code><script type="text/javascript">
handleStatusResponse = function (e) {
var response = e.data.split('|');
var action = response[0];
if (action === 'status') {
var status = response[1];
if (status === "success") {
var filename = response[3].split('\\')[2];
$('#hfFilename').val(filename);
$('#btnCreateAlbum').click();
}
else if (status === "running") {
ShowProgress();
}
else {
console.log("Unknown message: " + e.data);
}
}
}
addEventListener('message', handleStatusResponse, false);
</script>
</code></pre>
|
Extra white space at the bottom of the page <p>I have some extra space appearing at the bottom of a website and not sure how. Does anyone know what is causing this?</p>
<p><a href="http://192.99.37.125/~maggiemcflys/our-story/" rel="nofollow">http://192.99.37.125/~maggiemcflys/our-story/</a></p>
<p>The goal is to remove the extra white space.</p>
| <p>Change your CSS to the following:-</p>
<pre><code>#content {
bottom: -5px;
padding: 0 10% 0 30%;
position: relative;
vertical-align: middle;
width: 100%;
}
</code></pre>
<p>Ive added bottom: -5px to remove the space.</p>
<p>The issue is to do with the follow line of code:-</p>
<pre><code><div id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>
</code></pre>
<p>Its causing the white space.</p>
<p>specifically the following CSS:-</p>
<pre><code>.ui-datepicker {
margin: 5px auto 0;
}
</code></pre>
|
Obtaining field's object for displaying validation error message in redux-form <p>I would like to do sync validation, but I have no ideas how to obtain the field's object</p>
<p><em>validate.js</em></p>
<pre><code>const validate = (values) => {
const errors = {};
if (!values.firstName) {
errors.firstName = 'Firstname is required';
} else if (values.firstName.length < 5 || values.firstName.length > 10) {
errors.firstName = 'Firstname must be between 5 - 10';
}
return errors;
}
export default validate;
</code></pre>
<p><em>SimpleReduxForm.js</em></p>
<pre><code>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { reduxForm, Field } from 'redux-form'
import validate from './validate'
const fields = [ 'firstName', 'lastName', 'age' ]
@reduxForm({
form: 'simpleReduxForm',
fields,
validate
})
export default class SimpleReduxForm extends Component {
render() {
const { handleSubmit, invalid, pristine, submitting } = this.props
const { fields } = this.props
console.log(fields)
return (
<div>
<form onSubmit={ handleSubmit(this.handleFormSubmit) }>
<Field name="firstName" component="input" type="text" />
<Field name="lastName" component="input" type="text" />
<Field name="age" component="input" type="number" />
<input type="submit" value="Submit" disabled={ pristine || invalid || submitting }/>
</form>
</div>
)
}
}
</code></pre>
<p>The output of <code>console.log(fields)</code> from the source code above as below</p>
<p><a href="http://i.stack.imgur.com/EcbbA.png" rel="nofollow"><img src="http://i.stack.imgur.com/EcbbA.png" alt="enter image description here"></a></p>
<blockquote>
<p>It's just an array not object</p>
</blockquote>
<p>I have seen <a href="https://github.com/erikras/react-redux-universal-hot-example/blob/master/src/components/SurveyForm/SurveyForm.js" rel="nofollow">sample coding</a> from the documentation as below but I have no ideas how to get mine to work</p>
<pre><code>const { fields: { firstName, lastName } } = this.props
...
{ firstName.touched && firstName.error && <div>{ firstName.error }</div> }
</code></pre>
<p>Please advise, thanks</p>
| <p>There is a <a href="http://redux-form.com/6.0.5/examples/syncValidation/" rel="nofollow">good example</a> of how to do this on the redux-forms website. The gist is that you should render a component for your <code>Field</code> which will then have access to that input's data. For example, here's one of mine using some <code>twitter-bootstrap</code> error styling.</p>
<pre><code>const renderField = ({ input, label, type, meta: { touched, invalid, error } }) => (
<div class={`form-group ${touched && invalid ? 'has-error' : ''}`}>
<label>{label}</label>
<input {...input} placeholder={label} type={type} className="form-control" />
<div class="text-danger">
{touched ? error: ''}
</div>
</div>
);
</code></pre>
<p>Note that you just need to pull out <code>touched</code>, <code>invalid</code>, etc instead of <code>object.property.touched</code>, etc.</p>
<p>I use this from my <code>Field</code> declaration like so:</p>
<pre><code><Field name="name" type="text" component={renderField} label="Name" />
</code></pre>
|
CSS VW and VH - maintain ratio <p>I have a page that contains a DIV which maintains an aspect ratio. I have some text within the div that uses VW on the font size which maintains the text size when the page width changes - which is great.</p>
<p>But when the user changes the window height - I cannot get it to respond in the same way - because VW and VH don't play together.</p>
<p>Is there some CSS or Javascript trickery to get this to work? Ideally on the fly in case the user changes the browser size whilst on the site?</p>
<p>Here is said problem: </p>
<p><a href="https://jsfiddle.net/Lp8jynfr/1/" rel="nofollow">https://jsfiddle.net/Lp8jynfr/1/</a></p>
<pre><code><style>
.page-wrapper{
width: 100vw;
height: 68.60vw; /* height:width ratio = 9/16 = .5625 */
max-height: 100vh;
max-width: 145.7vh; /* 16/9 = 1.778 */
margin: auto;
position: absolute;
top:0;bottom:0; /* vertical center */
left:0;right:0; /* horizontal center */
border: 5px solid #000;
}
.text{
position: absolute;
width:100%;
top:36%;
left:0;
right:0;
font-size: 5.6vw;
color:#2d90db;
text-align:center;
}
</style>
<div class="page-wrapper">
<div class="text">
This is some text I want resized
</div>
</div>
</code></pre>
| <p>I ended up doing some Jquery to get this to work, it works pretty smoothly</p>
<p>I added an attribute to the DIV to tell the Jquery a font size, then did some calculations on the height of the parent container to get it to scale depending on the height of the DIV</p>
<pre><code>$(window).on("resize", function () {
$('.resize').height(function(){
$height = $(this).parent().parent().height();
$datasize = $(this).attr("data-size");
$fontsize = $height/100 * $datasize+"px"
$(this).css("font-size",$fontsize);
});
}).resize();
<div class='resize' data-size="9">Some text I want to resize</div>
</code></pre>
|
$(window).height() not working <p>JQuery Links being used:</p>
<pre><code><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src="jquery.min.js"></script>
</code></pre>
<p>JS:</p>
<pre><code>var windowHeight = $(window).height();
var menuBarHeight = $("#menubar").height();
alert(windowHeight);
alert(menuBarHeight);
</code></pre>
<p>HTML:</p>
<pre><code><!DOCTYPE html>...
</code></pre>
<p>CSS:</p>
<pre><code>#menubar {
width: 100%;
height: 40px;
background-color: #e0e0e0;
border-bottom: 1px solid grey;
}
</code></pre>
<p>I have used the <a href="http://stackoverflow.com/questions/12787380/jquery-window-height-function-does-not-return-actual-window-height">this question</a> as reference, however the solution there doesn't work for me. I'm trying to workout the distance of the window and a menu bar and using the data I will subtract one from the other so as to give me the height to use for another container on the rest of the page.</p>
<p>If it helps I've attached the HTML Doctype tag at the top and have also attached the css stylying of the #menubar. I've tryed on chrome and Firefox on a windows 10 machine.</p>
| <p>Check this code (with the correct jquery lib):</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() {
var windowHeight = $(window).height();
var menuBarHeight = $("#menubar").height();
alert(windowHeight);
alert(menuBarHeight);
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#menubar {
width: 100%;
height: 40px;
background-color: #e0e0e0;
border-bottom: 1px solid grey;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css">
<div id="menubar"></div></code></pre>
</div>
</div>
</p>
|
Return by reference PHP <p>In documentation i see how we set 2 <code>&</code>, why?</p>
<p>And can say me please what difference beetween</p>
<p><em>this 1:</em></p>
<pre><code>function &func()
{
static $static = 0;
$static++;
return $static;
}
$var1 = func();
echo "var1:", $var1; // 1
</code></pre>
<p>and <em>this 2:</em></p>
<pre><code>function func()
{
static $static = 0;
$static++;
return $static;
}
$var1 = func();
echo "var1:", $var1; // 1
</code></pre>
<p><strong>Or alternative variant</strong></p>
<p><em>this 1:</em></p>
<pre><code>function &func()
{
static $static = 0;
$static++;
return $static;
}
$var1 = &func();
echo "var1:", $var1; // 1
</code></pre>
<p>and <em>this 2:</em></p>
<pre><code>function func()
{
static $static = 0;
$static++;
return $static;
}
$var1 = &func();
echo "var1:", $var1; // 1
</code></pre>
| <p>There is only a difference between the first <code>this 2</code> and the second <code>this 1</code>. All others are wrongly tried <code>return by reference</code>. </p>
<p>The second <code>this 2</code> even throws a PHP notice (<code>Notice: Only variables should be assigned by reference in ... on line ...</code>).</p>
<p>The difference is that the first <code>this 2</code> returns by value while the second <code>this 1</code> returns by reference. Since it is a reference, the variable can be changed outside the function.</p>
<pre><code>function &func()
{
static $static = 0;
$static++;
return $static;
}
$var1 = &func();
echo "var1:", $var1; // 1
$var1 = 10;
$var1 = &func();
echo "\nvar1:", $var1; // 11
</code></pre>
<p><a href="https://3v4l.org/uJHSF" rel="nofollow">https://3v4l.org/uJHSF</a></p>
<p>evals for all snippets (with second function call):<br>
1st this 1: <a href="https://3v4l.org/p6erT" rel="nofollow">https://3v4l.org/p6erT</a><br>
1st this 2: <a href="https://3v4l.org/9OcaC" rel="nofollow">https://3v4l.org/9OcaC</a><br>
2nd this 1: <a href="https://3v4l.org/uJHSF" rel="nofollow">https://3v4l.org/uJHSF</a><br>
2nd this 2: <a href="https://3v4l.org/qJ3qO" rel="nofollow">https://3v4l.org/qJ3qO</a></p>
<p>See also the PHP manual: <a href="https://secure.php.net/manual/en/language.references.return.php" rel="nofollow">https://secure.php.net/manual/en/language.references.return.php</a></p>
|
Combining 2 SQL statements into 1 <p>I want to select employees who earns more than their managers. I have these SQL statements I wrote below, but how exactly would I combine these to make one statement?</p>
<pre><code>SELECT E.Salary
FROM Employee E
WHERE E.ManagerId = E.Id
SELECT *
FROM Employee M
WHERE M.Salary > E.Salary AND M.ManagerId != M.Id
</code></pre>
| <pre><code>SELECT E.Salary, M.*
FROM Employee E
inner join Mamanger M on E.ManagerId = M.Id and E.Salary > M.Salary
</code></pre>
|
output of fmod function c++ <p>Given:</p>
<pre><code>#include <iostream>
#include <cmath>
#include <limits>
using namespace std;
int main() {
// your code goes here
double h = .1;
double x = 1;
int nSteps = abs(x / h);
double rem = fmod(x, h);
cout<<"fmod output is "<<rem<<endl;
if(abs(rem)<std::numeric_limits<double>::epsilon())
cout<<"fmod output is almost near 0"<<endl;
rem = remainder(x,h);
cout<<"remainder output is "<<rem<<endl;
if(abs(rem)<std::numeric_limits<double>::epsilon())
cout<<"remainder output is almost near 0"<<endl;
return 0;
}
</code></pre>
<p>Given <code>int(x/h) == 10</code>, I would have expected the <code>fmod()</code> result to be near 0 but what i get is .0999999999. It is a significant difference. The result of remainder() still seem acceptable. Code could be tried at <a href="http://ideone.com/9wBlva" rel="nofollow">http://ideone.com/9wBlva</a></p>
<p>Why this significant difference for fmod() result?</p>
| <p>The problem you're seeing is that the version of <code>fmod</code> you're using appears to follow the implementation defined at <a href="http://en.cppreference.com/w/cpp/numeric/math/fmod" rel="nofollow">cppreference</a>:</p>
<pre><code>double fmod(double x, double y)
{
double result = std::remainder(std::fabs(x), (y = std::fabs(y)));
if (std::signbit(result)) result += y;
return std::copysign(result, x);
}
</code></pre>
<p><code>std::remainder</code> computes a very very small result, nearly zero (-5.55112e-17 when using 1 and 0.1 for me, -1.11022e-16 for 2 and 0.2). However, what's important is that the result is <em>negative</em>, which means <a href="http://en.cppreference.com/w/cpp/numeric/math/signbit" rel="nofollow"><code>std::signbit</code></a> returns true, causing <code>y</code> to get added to the result, effectively making the result equal to <code>y</code>.</p>
<p>Note that the documentation of <code>std::fmod</code> doesn't say anything about using <code>std::remainder</code>:</p>
<blockquote>
<p>The floating-point remainder of the division operation x/y calculated by this function is exactly the value x - n*y, where n is x/y with its fractional part truncated.</p>
</blockquote>
<p>So if you compute the value yourself, you do end up with zero (even if you use <code>std::round</code> on the result instead of pure integer truncation)</p>
<p>We see similar problems when <code>x</code> is 2 and <code>y</code> is 0.2</p>
<pre><code>double x = 2;
double y = .2;
int n = static_cast<int>(x/y);
double result = x - n*y;
std::cout << "Manual: " << result << std::endl;
std::cout << "fmod: " << std::fmod(x,y) << std::endl;
</code></pre>
<p>Output (<a href="http://coliru.stacked-crooked.com/a/249620f2da07a9de" rel="nofollow">gcc demo</a>) is </p>
<blockquote>
<p>Manual: 0 <br/>
fmod: 0.2</p>
</blockquote>
<p>However the problem is not relegated to only gcc; I also see it in MSVC and clang. In clang there is sometimes different behavior if one uses <code>float</code> instead of <code>double</code>.</p>
<p>This really small negative value from <code>std::remainder</code> comes from the fact that neither 0.1 nor 0.2 can be represented exactly in floating point math. If you change x and y to, say 2 and 0.25, then all is well.</p>
|
How to scrape in Ruby when the page elements keep changing and shifting. <p>I'm writing a program to download the images from an imgur album: I had just begun to write the actual image-link-code:</p>
<pre><code>#The imports.
require 'open-uri'
require 'nokogiri'
url = ARGV[0]
#The title.
open(url) do |f|
$doc = Nokogiri::HTML(f)
title = $doc.at_css('title').text.strip.clone
re = /\/[a]\/\w{5}/
s2 = url.match re
puts title
puts s2
end
href = $doc.xpath("//img")
puts href
</code></pre>
<p>When I ran into a major problem: the page I download isn't the page source.</p>
<p>For example: This album: <a href="http://imgur.com/a/tGRvr/layout/grid" rel="nofollow">http://imgur.com/a/tGRvr/layout/grid</a> has the following code for it's images:</p>
<p><code><span class="post-grid-image pointer" data-href="//i.imgur.com/zh6I7k2.png" data-title="" style="transform: translate(0px, 0px) scale(1); z-index: 0; background-image: url(&quot;//i.imgur.com/zh6I7k2b.jpg&quot;);"></span></code></p>
<p>And yet when I look in the page source, or run the code for span elements, all the images are missing:
</p>
<pre><code> <div class="post-images is-owner">
<div class="post-action nodisplay"></div>
</div>
</div>
</code></pre>
<p>The HTML is active, and changes based on how my browser is. There aren't any images in the page source, and everything's loaded using some weird java system. How can I scrape active elements, when there aren't even any active elements to scrape?</p>
<p>And what's the difference between <code>inspect</code> and 'view-source'? That's what started this whole problem. </p>
| <p>It's dynamic HTML. Mechanize and/or Nokogiri can't help you unless you can build the final version of the page then pass it to them.</p>
<p>Instead you have to use something that can interpret JavaScript and apply CSS, such as a browser. The WATIR project would be the first thing to investigate. "inspect" and "view-source" both reflect the page after the browser has processed the JavaScript and CSS in it, which often has little bearing on what the actual page looked like prior to that. Search SO for <code>[ruby] [watir]</code>.</p>
<p>Use <code>wget</code>, <code>curl</code> or <code>nokogiri</code> to retrieve the page so you can see the raw HTML. </p>
<p><code>$doc.at_css('title')</code> should be using the <code>title</code> method: <code>doc.title</code>. </p>
<p>Don't use a global like <code>$doc</code>. Learn about variable scoping then decide if a global is the right way to go.</p>
<p>Instead of <code>open</code> with a block:</p>
<pre><code>open(url) do |f|
$doc = Nokogiri::HTML(f)
title = $doc.at_css('title').text.strip.clone
re = /\/[a]\/\w{5}/
s2 = url.match re
puts title
puts s2
end
</code></pre>
<p>Do this instead:</p>
<pre><code>doc = Nokogiri::HTML(open(url))
title = doc.title
</code></pre>
<p>When working with URIs/URLs, use the built-in URI class since it's a well debugged tool:</p>
<pre><code>require 'uri'
url = URI.parse('http://imgur.com/a/tGRvr/layout/grid')
url.path # => "/a/tGRvr/layout/grid"
.split('/') # => ["", "a", "tGRvr", "layout", "grid"]
</code></pre>
<p>Knowing that, you can do:</p>
<pre><code>url.path.split('/')[2] # => "tGRvr"
</code></pre>
|
Why can't I deploy UWP app on a new Lumia phone? (developer mode enabled) <p>I created an app and I could run it on my Lumia 640 for testing. I have not submitted my App to Windows Store yet, as the debugging is unfinished. I just deployed it on my phone with <code>Developer Mode</code>enabled and it ran just fine.</p>
<p>But now I bought a new phone (same model), enabled <code>Developer Mode</code> and tried to deploy. However, <strong>when I tried installing the App on the new phone, it won't display on my App list.</strong> Restarting the phone did nothing, Logged in with my Microsoft account for the phone and nothing. I just don't know what I'm missing.</p>
<p>Has anyone else experienced this issue?</p>
| <p>I'm missing the files in <code>Dependencies</code> folder which will create with the .appx file. I need to install these files first, and now all fine.</p>
|
JSONSimple Overwriting <p>I am attempting to iterate through a hash map and create a json string from the values. Im using the JSONSimple library to do so. I have the structure I want, but the values are being overwritten. The structure I am ending up with is </p>
<pre><code>{
"new_id":{
"coordinates_list":{
"Coordinates: ":[
"lat: 27.0",
"lon: 28.0"
]
},
"t0vhf40cv86t":[
"123"
]
}
}
</code></pre>
<p>But there should be additional values in the JSON. Only the last row of the hash map is being included. Do I need to add another JSONObject that I write to?</p>
<pre><code>JSONObject obj = new JSONObject(); // final json object written out
double lat = 20.00; // test data
double lon = 21.00; // test data
for (Map.Entry<String, List<String>> entry : data.entrySet()){
JSONObject childObj = new JSONObject();
JSONObject coordObj = new JSONObject();
JSONArray entities = new JSONArray();
JSONArray coordinates = new JSONArray();
String key = entry.getKey();
List<String> values = data.get(key);
for(String value : values){
entities.add(value);
}
childObj.put(key,entities);
// increments the test data
lat = lat +1;
lon = lon + 1;
coordinates.add("lat: " + lat);
coordinates.add("lon: " + lon);
coordObj.put("Coordinates: " ,coordinates);
childObj.put("coordinate list ", coordObj);
obj.put("new_id" , childObj);
}
</code></pre>
| <p>You are always using "new_id" as the key on the "obj.put" line. For the first map entry, you set the value for that key on the JSON object. For each subsequent entry, you are replacing the value for that key, not adding a new key. That is why only the last entry in the map is represented in the JSON.</p>
<p>I'm not sure exactly what you're trying to accomplish, but you likely either need to use a different key each time through the loop or use a JSONArray instead of a JSONObject so that you don't need keys at all.</p>
|
Migrating from EJB with Spring to POJO <p>While migrating from EJB with spring to POJO , I read every where that just changing this configuration will work :</p>
<pre><code><bean id="sapFeedBean" class="org.springframework.ejb.access.SimpleRemoteStatelessSessionProxyFactoryBean" lazy-init="true">
<property name="jndiName" value="ejb/sapBean" />
<property name="resourceRef" value="false" />
<property name="businessInterface" value="com.aa.inflightsales.sap.SapBusiness" />
<property name="lookupHomeOnStartup" value="false" />
</bean>
</code></pre>
<p>but how to do this , I am trying to create bean of the POJO class , but how can I define the business interface , as interface injection is not supported by spring.</p>
| <p>This is a kind of <strong><code>deprecated approach</code></strong> to create a bean..</p>
<p>Its better if you use <strong>JavaConfig</strong>..
Have a look at the following link </p>
<p>It will give you a clear idea</p>
<p><a href="https://dzone.com/articles/consider-replacing-spring-xml" rel="nofollow">https://dzone.com/articles/consider-replacing-spring-xml</a></p>
|
Change type of calculated field in select query (sqlite) <p>im sure i am not the first one to ask this but i can't find the answer to this:
I haver a select query on a datatable in a sqlite database. </p>
<pre><code>select *, ((int_EndTime)-(int_StartTime))/60 as dou_usage_min FROM tbl_unautho_usage;
</code></pre>
<p>when i run this i get all the fields from the datatable including a new column calculated from to integer columns with unix time stamp values. However, i want my calculated column to be of the type double. With the query above i get a type integer.</p>
<pre><code>select *, ((int_EndTime as float)-(int_StartTime as float))/60 as dou_usage_min FROM tbl_unautho_usage;
</code></pre>
<p>Afterwards I tried to change the column type of my integer-columns to float, but this gies me the following error:</p>
<pre><code>near "as": syntax error:
</code></pre>
<p>i got the idea for that from the following post:
<a href="http://stackoverflow.com/questions/7802209/how-to-cast-computed-column-with-correct-decimal-result">How to cast computed column with correct decimal/$ result</a></p>
| <p>Try multiplying a value used within the arithmetic operation by <code>1.0</code>.</p>
<pre><code>select
*,
((int_EndTime*1.0)-(int_StartTime*1.0))/60 as dou_usage_min
FROM tbl_unautho_usage;
</code></pre>
<p>Probably only one value multiplied will be sufficient.</p>
|
Controller redirection doesn't change view <p>I'm doing a simple RedirectAction in my controler and in this new Controller i'm calling the new View, however in the Browser the View is not changing, i can see in the cshtml the code getting there, but i don't know what i'm missing.</p>
<pre><code>public ActionResult ExecuteBreakdown(string param1)
{
return RedirectToAction("ShowMatrix", "BreakdownMatrix", new { param = param1 });
}
public ActionResult ShowMatrix(string param1 )
{
...lots of code
return View("ShowMatrix", priceMatrix);
}
</code></pre>
<p>I'm not being redirect to the ShowMatrix View.</p>
| <p>You need to return something like a <code>PartialView</code> in your redirect to action call. However, the call needs to be scoped to a parent view that can display the partial properly. You can't just load what you send over like that.</p>
|
Xcode error NSException <p>I'm currently trying to run on Xcode an app I ve made with Qt, but when I try to run it on Xcode i get this Exception :</p>
<pre><code> dyld: warning, Ignoring DYLD_IMAGE_SUFFIX because DYLD_ROOT_PATH is used.
2016-10-10 15:37:04.777 CMP[2206:654538] *** Assertion failure in void _UIApplicationMainPreparations(int, char **, NSString *__strong, NSString *__strong)(), /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3512.60.7/UIApplication.m:3702
2016-10-10 15:37:04.783 CMP[2206:654538] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Unable to instantiate the UIApplication subclass instance. No class named NSApplication is loaded.'
*** First throw call stack:
(
0 CoreFoundation 0x06a27494 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x07c4fe02 objc_exception_throw + 50
2 CoreFoundation 0x06a2732a +[NSException raise:format:arguments:] + 138
3 Foundation 0x05eba390 -[NSAssertionHandler handleFailureInFunction:file:lineNumber:description:] + 102
4 UIKit 0x04703177 _UIApplicationMainPreparations + 645
5 UIKit 0x04702e73 UIApplicationMain + 90
6 CMP 0x0004f6f6 qt_main_wrapper + 678
7 libdyld.dylib 0x0b53fa25 start + 1
8 ??? 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
</code></pre>
<p>anyone can help please ?</p>
| <p>In your app's info.plist, make sure you change the NSPrincipalClass key to the name of your subclass. This'll make Cocoa instantiate the correct class when the applications loads - you shouldn't have to do anything other than that to get your subclass working. Also, take a look at this link it may also add some insights to your question. <a href="http://www.cocoawithlove.com/2009/01/demystifying-nsapplication-by.html" rel="nofollow">Demystifying NSApplication</a></p>
|
Trouble registering a custom taxonomy for my Custom Post Type <p>I have a custom post type of 'Employees' and am trying to register custom categories for this custom post type. Here is my php:</p>
<pre><code>//---------------------------------------------------//
//---- REGISTER CUSTOM POST TYPES ------------------//
//--------------------------------------------------//
// Register Employees Custom Post Type
function employees_custom_post_type() {
$labels = array(
'name' => 'Employees',
'singular_name' => 'Employee',
'menu_name' => 'Employees',
'name_admin_bar' => 'Employee',
'archives' => 'Item Archives',
'parent_item_colon' => 'Parent Item:',
'all_items' => 'All Items',
'add_new_item' => 'Add New Item',
'add_new' => 'Add New',
'new_item' => 'New Item',
'edit_item' => 'Edit Item',
'update_item' => 'Update Item',
'view_item' => 'View Item',
'search_items' => 'Search Item',
'not_found' => 'Not found',
'not_found_in_trash' => 'Not found in Trash',
'featured_image' => 'Featured Image',
'set_featured_image' => 'Set featured image',
'remove_featured_image' => 'Remove featured image',
'use_featured_image' => 'Use as featured image',
'insert_into_item' => 'Insert into item',
'uploaded_to_this_item' => 'Uploaded to this item',
'items_list' => 'Items list',
'items_list_navigation' => 'Items list navigation',
'filter_items_list' => 'Filter items list',
);
$args = array(
'label' => 'Employee',
'description' => 'A List of CenterPoint Employees categorized by role',
'labels' => $labels,
'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', ),
'taxonomies' => array( 'team_categories' ),
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'post_type', $args );
}
add_action( 'init', 'employees_custom_post_type', 0 );
//-----------------------------------//
//----REGISTER CUSTOM TAXONOMIES-----//
//-----------------------------------//
function custom_taxonomy() {
$labels = array(
'name' => 'Team Categories',
'singular_name' => 'Team Category',
'menu_name' => 'Taxonomy',
'all_items' => 'All Items',
'parent_item' => 'Parent Item',
'parent_item_colon' => 'Parent Item:',
'new_item_name' => 'New Item Name',
'add_new_item' => 'Add New Item',
'edit_item' => 'Edit Item',
'update_item' => 'Update Item',
'view_item' => 'View Item',
'separate_items_with_commas' => 'Separate items with commas',
'add_or_remove_items' => 'Add or remove items',
'choose_from_most_used' => 'Choose from the most used',
'popular_items' => 'Popular Items',
'search_items' => 'Search Items',
'not_found' => 'Not Found',
'no_terms' => 'No items',
'items_list' => 'Items list',
'items_list_navigation' => 'Items list navigation',
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
);
register_taxonomy( 'team_categories', array( 'employees_custom_post_type' ), $args );
}
add_action( 'init', 'custom_taxonomy', 0 );
</code></pre>
<p>My custom taxonomy is not showing up in the admin. What am I doing wrong?</p>
| <p>You should give the proper name on this line:
register_post_type( 'post_type', $args );
Shouldnt it be <code>employees_custom_post_type</code>?</p>
|
Android SQLite: Replace old database with a new one or use migration scripts <p>I have an Android app that uses a SQLite database and <a href="http://www.activeandroid.com" rel="nofollow">Active Android</a> as ORM. On each app update I need to ship my database with new/updated data. This is what i've been doing</p>
<ol>
<li>I have a <strong>my_app.db</strong> database</li>
<li>I make modifications on the rows, tables, etc. of the <strong>my_app.db</strong></li>
<li>I save the modified <strong>my_app.db</strong> as <strong>my_app_v2.db</strong> ( and so on )</li>
<li>I replace the <strong>my_app.db</strong> file of the assets folder with the <strong>my_app_v2.db</strong> and set it as the default database</li>
<li>I compile and run the program using the newly created <strong>my_app_v2.db</strong></li>
</ol>
<p>So when the user gets the app, it will be using the <strong>my_app_v2.db</strong> with new contents.</p>
<p>I know that Active Android <a href="https://github.com/pardom/ActiveAndroid/wiki/Schema-migrations" rel="nofollow">supports migration scripts</a>, but on each database update I need to add/update about 2000+ records. So for each database update I would need a migration script with 2000+ insert/update statements, it means that for 3+ consecutive upgrades the app would have to execute about 6000+ statements.</p>
<p>I want to know if my approach of replace the whole database with a new one is a bad practice and the migrations scripts should be prefered.</p>
| <p>You dont need to do that (renaming stuff or anything)</p>
<p>You just need to change your database version and write a sql command to alter your previous table to migrate from version A to B.</p>
<p>Look at this link: </p>
<p><a href="http://stackoverflow.com/questions/8133597/android-upgrading-db-version-and-adding-new-table">Android: upgrading DB version and adding new table</a></p>
|
The request has exceeded the allowable time limit & Java Heap Space Null errors <p>I know this topic seems to be discussed many times, but I have tried all the methods mentioned to no avail.</p>
<p>I am keeping getting the errors:</p>
<blockquote>
<p>The request has exceeded the allowable time limit Tag: CFQUERY
<br>The error occurred on line 152.</p>
</blockquote>
<p>and also</p>
<blockquote>
<p>Java heap space null <br>The error occurred on line -1.</p>
</blockquote>
<p>on the same html page.</p>
<p>I believe the Java heap space error is causing the timeout or vice versa. </p>
<p>The program where the time out occur is </p>
<pre><code> <CFQUERY DATASOURCE="#datasource#" USERNAME="#username#" PASSWORD="#password#" NAME="myQuery" CACHEDWITHIN="#CreateTimeSpan(0,0,5,0)#">
SELECT tableA.productid, tableA.userid, tableA.salesid, tableA.productname, tableA.price, tableA.units, tableA.currency, tableA.terms, tableA.description, tableA.pic, tableA.minorder, tableA.salesid, tableB.id, tableB.company, tableB.city, tableB.state, tableB.country, tableB.contact, tableB.skype
FROM tableA LEFT OUTER JOIN tableB
ON tableA.userid = tableB.userid
WHERE tableA.category = <cfqueryparam value = "#cat#" cfsqltype = "cf_sql_integer" maxLength = "2">
ORDER by tableA.ranks DESC
</CFQUERY>
</code></pre>
<p>which I don't know how it can be further "optimized"? It's only retrieving about 28,000 resulting records, <em>not</em> 2 millions. I am using MySQL database.</p>
<p>I have increased my MaxPermSize from 256MB to 512MB but it seems the problem is still occurring, especially when search engines coming to site to index. I am running on CF9 on a server with 6GB RAM. Here are some of my settings in CF:</p>
<ul>
<li>Minimum and Maximum JVM Heap Size are both set at 512MB. </li>
<li>Timeout Requests after ( seconds) set at 60</li>
<li>JVM version 1.7.0_67 </li>
<li>JVM Arguments:
<blockquote>
<p>-server -Dsun.io.useCanonCaches=false -XX:-UseGCOverheadLimit -XX:MaxPermSize=512m -XX:+UseParallelGC -Xbatch -Dcoldfusion.rootDir={application.home}/../ -Dcoldfusion.libPath={application.home}/../lib</p>
</blockquote></li>
</ul>
<p>Any suggestion is welcomed. Thanks in advance.</p>
<p>ADDITIONAL INFO:</p>
<ol>
<li>There are 26 categories of products</li>
<li>Each category has 20-50K records and is increasing daily</li>
<li>People may or may not accessing all 26 different categories at different time during the day</li>
<li>Not all categories are updated daily but some categories are</li>
</ol>
| <p>With 20-40k products per category at 20 categories with an unknown row size, you have some real architectural decisions to make on your data caching (if you do use a cache). Currently, each category id parameter will be a unique cache of that query with a time to live of five minutes consuming some amount of heap space. In addition, it has to be copied out of cache during a request and will consume memory until it can be collected. Also note that permgen is not related to heap size. </p>
<p>I would recommend not caching to see how the DB server handles it by only asking for the records for that page. Built in query cache is very situational and this is not one of those situations. 30k records might not seem like much until you realize you have product descriptions and other large text blocks that are half a meg each. I would highly recommend going with at least a gig or two of heap if you can for any typical commerce site with a robust catalog. (You say "I am running on CF9 on a server with 6GB RAM." Hopefully some of that is free to allocate to the JVM). In this situation, more memory is only going to put off the problem until a later date, if at all. </p>
<p>Also, pull permgen back to 256. 512 permgen is pretty high, even for a big enterprise app. </p>
<p>Here is how your app is currently functioning when a request comes in. </p>
<ol>
<li>The query tag is hit and results are returned
<ol>
<li>Cache hit - results are copied out of the cache taking some wasteful amount of megabytes</li>
<li>Cache miss - results are streamed in from the database taking some wasteful amount of megabytes and are additionally copied into the cache region (but you avoid the database load time as well as transfer time, I suspect most of your time is spent during transfer rather than querying) </li>
</ol></li>
<li>You utilize a fraction of the query</li>
<li>The query is garbage collected</li>
</ol>
<p>Under light load, your server is probably barely keeping up. Who knows how often your cache region is able to avoid churn. </p>
<p><strong>Additional follow-up:</strong></p>
<p>It sounds like you are doing all this simply for the rowcounts for pagination. You can actually put your total row counts into the query that is returning records for just one page as a subquery. If you want to split into two queries -- one for the row counts and one for the records for this row, that former is a good contender for caching. It is data that won't change often, and if it does, it really doesn't matter if you are slightly behind. In addition, it is super small and actually makes sense to cache over asking the DB all the time.</p>
|
What's wrong with this class method? <pre><code>class Person:
def __init__(self, name):
self.name = name
def greet(name, other_name):
return "Hi {0}, my name is {1}".format(other_name, name)
</code></pre>
<p>Why doesn't this work? I am trying to access my name in the class and say hi my name is [myname] [yourname]</p>
| <p>Your actual problem is that you are defining your instance method <code>greet</code> as:</p>
<pre><code>def greet(name, other_name):
</code></pre>
<p>Instance methods in Python take the <code>instance</code> as first argument in your method definitions. What you are doing here now, is calling that instance <code>name</code>. However, in your class's <code>__init__</code>, you are using <code>self</code> to refer to your instance object. This is where your main problem is coming up. </p>
<p>So, when you actually try to call your method, you are most likely getting something like this: </p>
<pre><code>Hi bob, my name is <__main__.Person object at 0x1018ff2b0>
</code></pre>
<p>So, you are actually printing out your instance object of your <code>Person</code> class. Again, you named this <code>name</code>. It's like printing out <code>self</code>. </p>
<p>There are two things you need to correct here. The first, you need to properly define your instance <code>greet</code> method keeping your instance object name consistent.</p>
<pre><code>def greet(self, other_name):
</code></pre>
<p>Then, you need to refer to your instance attributes referring to your instance and accessing the attributes from that object: </p>
<p>So, you want to access <code>name</code> in your <code>greet</code> method, it has to be as <code>self.name</code>.</p>
<p>So:</p>
<pre><code>"Hi {0}, my name is {1}".format(other_name, self.name)
</code></pre>
<p>To have a better grasp on all this, you should read more on how classes work in Python. Here is the tutorial section on it:</p>
<p><a href="https://docs.python.org/3/tutorial/classes.html" rel="nofollow">https://docs.python.org/3/tutorial/classes.html</a></p>
|
How to array_push unique values inside another array <p>I have two arrays:</p>
<pre><code>$DocumentID = array(document-1, document-2, document-3, document-4,
document-5, document-4, document-3, document-2);
$UniqueDocumentID = array();
</code></pre>
<p>I want to push the unique objects inside of <code>$documentid</code> array to <code>$UniqueDocumentID</code> array. </p>
<p>I can't use <code>array_unique()</code> as it copies the key of its predecessor array and I want sequential keys inside the <code>$UniqueDocumentID</code> array.</p>
| <p>You could <code>foreach()</code> through <code>$DocumentID</code> and check for the current value in <code>$UniqueDocumentID</code> with <code>in_array()</code> and if not present add it. Or use the proper tool:</p>
<pre><code>$UniqueDocumentID = array_unique($DocumentID);
</code></pre>
<p>To your comment about wanting sequential keys:</p>
<pre><code>$UniqueDocumentID = array_values(array_unique($DocumentID));
</code></pre>
<p>The long way around:</p>
<pre><code>$UniqueDocumentID = array();
foreach($DocumentID as $value) {
if(!in_array($value, $UniqueDocumentID)) {
$UniqueDocumentID[] = $value;
}
}
</code></pre>
|
What is the best way to composite several rectangle structs together into one large rectangle <p>Say I have 2 rectangles (originX, originY, width, height)</p>
<p>0,0,100,100</p>
<p>100,100,100,100</p>
<p>What is the best way to get the rectangle that contains both?</p>
<p>i.e: 0,0,200,200</p>
<p>Here is a crappy paint picture to illustrate what I mean</p>
<p><a href="http://i.stack.imgur.com/Dyefj.png" rel="nofollow"><img src="http://i.stack.imgur.com/Dyefj.png" alt="enter image description here"></a></p>
<p><strong>My plan now is to:<br>
1) Find the smallest origin, that is the origin of the return rect<br>
2) Find the highest originY+height, that is the upper bound of the return rect<br>
3) Find the highest originX+width, that is the right bound of the return rect</strong> </p>
<p>But my issue is that there could potentially be thousands of rectangles, so I want to make sure I have the best solution</p>
<p>I think I'm having a hard time finding a solution because I'm wording this poorly. In my mind, this would be something like compositing rectangles-- but is there another way to describe what I'm trying to do here?</p>
| <p>No matter what, you will have to look at each rectangle to achieve you answer. If you fail to look at even one, you could miss a point that is outside of your bounds. So no matter what the best solution you can find will be O(n).</p>
<p>Since we are looking for an O(n) solution, it is pretty simple: just iterate over each rectangle. Store the minimum and maximum x and y found so far. Note that maximum x and y are defined in this case by <code>originX + width</code> and <code>originY + height</code>. After iterating over all rectangles, the rectangle formed by the points <code>minX</code>, <code>minY</code>, <code>maxX</code>, <code>maxY</code> will be your solution.</p>
|
date & time not loading on page load <p>I have an html page with a date and time input on it, just straight HTML5</p>
<pre><code><input type="date" id='date' name='date' style='text-align:center' required />
</code></pre>
<p>and</p>
<pre><code><input type='time' id='time' name='time' style='text-align:center' required />
</code></pre>
<p>I have the following js code</p>
<pre><code> function gDate(){
(function () {
var date = new Date().toISOString().substring(0, 10),
field = document.querySelector('#date');
field.value = date;
})()
var time = (new Date()).toTimeString().split(' ')[0];
document.getElementById('time').value=time;
}
</code></pre>
<p>I have it setup to run on document.Ready with Jquery</p>
<pre><code><script>
$(document).ready(function(){
gDate();
});
</script>
</code></pre>
<p>I do have gDate() being loaded from a separate .js page, it works only when I hit refresh. </p>
<p>How can I make it work when the page is loaded. I have tried </p>
<pre><code><body onLoad="gDate()">
</code></pre>
<p>but that makes no difference either.</p>
| <p>Make sure that jQuery is included, below code snippet works just fine, check developer console in your web browser to check for errors.</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 gDate(){
(function () {
var date = new Date().toISOString().substring(0, 10),
field = document.querySelector('#date');
field.value = date;
})()
var time = (new Date()).toTimeString().split(' ')[0];
document.getElementById('time').value=time;
}
$(document).ready(function(){
gDate();
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" id='date' name='date' style='text-align:center' required />
<input type='time' id='time' name='time' style='text-align:center' required /></code></pre>
</div>
</div>
</p>
|
How to make push, unshift, pop and shift to work only with local array in javascript? <p>I have a function to describe my problem:</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 testingFunc(value) {
var temp = value;
console.log("temp before: " + JSON.stringify(temp));
console.log("arrayTest before: " + JSON.stringify(arrayTest));
temp.unshift(123);
console.log("temp after unshift: " + JSON.stringify(temp));
console.log("arrayTest after unshift: " + JSON.stringify(arrayTest));
temp.push(456);
console.log("temp after push: " + JSON.stringify(temp));
console.log("arrayTest after push: " + JSON.stringify(arrayTest));
temp.shift();
console.log("temp after shift: " + JSON.stringify(temp));
console.log("arrayTest after shift: " + JSON.stringify(arrayTest));
temp.pop();
console.log("temp after pop: " + JSON.stringify(temp));
console.log("arrayTest after pop: " + JSON.stringify(arrayTest));
return temp;
}
var arrayTest = [1,2,3,4,5];
var arrayTestTwo;
arrayTestTwo = testingFunc(arrayTest);
console.log("arrayTest after testingFunc: " + JSON.stringify(arrayTest));
console.log("arrayTestTwo: " + JSON.stringify(arrayTestTwo));</code></pre>
</div>
</div>
</p>
<p>As you can see, <code>arrayTest</code> will change too if <code>temp</code> change by using <code>push</code>, <code>unshift</code>, <code>pop</code> and <code>shift</code> to edit it's data.</p>
<p>But I want those function to work ONLY with <code>temp</code> and ignore <code>arrayTest</code>.</p>
<p>Is it possible? Also is it possible to work with object contains functions?</p>
<p>And why is this happen?</p>
| <p>When you assign an array to a variable (or passing it as an argument to a function), you are only storing a <em>reference</em> to that array. If two or more variables are referencing the same array, making changes to one will affect all the others as well:</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 original = [];
var modified = original;
console.log(original, modified); // [] []
modified.push(1, 2, 3);
console.log(original, modified); // [1,2,3] [1,2,3]</code></pre>
</div>
</div>
</p>
<p>The way to solve this is to make a <em>copy</em> of the array. To make a copy of an array, you just call <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice" rel="nofollow"><code><em>array</em>.slice()</code></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>var original = [];
var modified = original.slice();
console.log(original, modified); // [] []
modified.push(1, 2, 3);
console.log(original, modified); // [] [1,2,3]</code></pre>
</div>
</div>
</p>
|
Jmeter csv config for file upload <p>I'm using Jmeter for testing file uploads. This works great when I upload just one file, but I want to be able to loop through a list of files. I see Jmeter has a CSV based config capability, but I can't figure out how to include a file as one of the params.</p>
<p>How can I specify a list of different files for jmeter to loop through, uploading one per request?</p>
| <p>You need to pass:</p>
<ul>
<li>either relative or full path to the file being uploaded</li>
<li>upload input name</li>
<li>file MIME type</li>
</ul>
<p>So if your CSV file will look like:</p>
<pre><code>c:/testfiles/test.txt,upload,text/plain
c:/testfiles/test.jpg,upload,image/jpeg
etc.
</code></pre>
<p>And CSV Data Set Config is configured as:</p>
<p><a href="http://i.stack.imgur.com/dtt1u.png" rel="nofollow"><img src="http://i.stack.imgur.com/dtt1u.png" alt="CSV Data Set"></a></p>
<p>Your HTTP Request Sampler configuration should look somehow like</p>
<p><a href="http://i.stack.imgur.com/rwFgU.png" rel="nofollow"><img src="http://i.stack.imgur.com/rwFgU.png" alt="HTTP Request Sampler"></a> </p>
<p>References:</p>
<ul>
<li><a href="http://jmeter.apache.org/usermanual/component_reference.html#CSV_Data_Set_Config" rel="nofollow">CSV Data Set Config</a></li>
<li><a href="https://www.blazemeter.com/blog/how-performance-test-upload-and-download-scenarios-apache-jmeter" rel="nofollow">Performance Testing: Upload and Download Scenarios with Apache JMeter</a></li>
</ul>
|
Linking 'muted speaker' icon to volume slider when value = 0? <p>I have a speaker icon besides my volume slider, and I would like the icon to change when the volume value is at 0, to a second (muted) speaker icon. I've tried different variations which didn't work. How do I do that? Thanks!</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 volumeslider;
volumeslider = document.getElementById("volumeslider");
// Add Event Handling
volumeslider.addEventListener("mousemove", setvolume);
// Functions
function setvolume(){
audio.volume = volumeslider.value / 100;
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>input[type=range] {
-webkit-appearance: none;
display: inline-block;
vertical-align: top;
width: 60%;
margin: 10px 0;
}
input[type=range]:focus {
outline: none;
}
input[type=range]::-webkit-slider-runnable-track {
width: 100%;
height: 10px;
cursor: pointer;
animate: 0.2s;
background: #000000;
}
input[type=range]::-webkit-slider-thumb {
border: 1px solid #000000;
height: 20px;
width: 10px;
border-radius: 1px;
background: #ffffff;
cursor: pointer;
-webkit-appearance: none;
margin-top: -10px;
}
input[type=range]:focus::-webkit-slider-runnable-track {
background: #666666;
}
input[type=range]::-moz-range-track {
width: 100%;
height: 10px;
cursor: pointer;
animate: 0.2s;
background: #000000;
}
input[type=range]::-moz-range-thumb {
border: 1px solid #000000;
height: 20px;
width: 10px;
border-radius: 1px;
background: #666666;
cursor: pointer;
}
input[type=range]::-ms-track {
width: 100%;
height: 10px;
cursor: pointer;
animate: 0.2s;
background: transparent;
border-color: transparent;
border-width: 16px 0;
color: transparent;
}
input[type=range]::-ms-fill-lower {
background: #2a6495;
border: 0.2px solid #010101;
border-radius: 2.6px;
}
input[type=range]::-ms-fill-upper {
background: #3071a9;
border: 0.2px solid #010101;
border-radius: 2.6px;
}
input[type=range]::-ms-thumb {
border: 1px solid #000000;
height: 20px;
width: 10px;
border-radius: 1px;
background: #ffffff;
cursor: pointer;
}
input[type=range]:focus::-ms-fill-lower {
background: #3071a9;
}
input[type=range]:focus::-ms-fill-upper {
background: #367ebd;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <input id="volumeslider" type="range" min="0" max="100" value="100" step="1">
<img src="https://maxcdn.icons8.com/Android/PNG/48/Mobile/speaker-48.png" width="25" height="32"></code></pre>
</div>
</div>
</p>
| <p>Use JQs attr method to just swap the image source. Also, make sure the src path to the images is relative to the HTML document if you are using an external JS document. </p>
<p><strong>JS:</strong></p>
<pre><code> volumeslider.addEventListener("mousemove", checkMute);
</code></pre>
<p>//check for mute each time the slider is dragged. </p>
<pre><code>function checkMute(){
if (audio.volume == 0){
$( ".speaker" ).attr("src", "images/speaker.png");
}else{
$( ".speaker" ).attr("src", "images/speakermute.png");
}
}
</code></pre>
|
WPF DataTemplate.Triggers don't evaluate <p>Trying a simple DataTemplate implementation that doesn't work for some reason. It seems like the Bindings inside the conditions are never evaluated, even on the initial load. Any input is appreciated. </p>
<pre><code> <DataTemplate x:Key="ReadinessCellTemplate">
<StackPanel Orientation="Horizontal">
<Grid>
<Grid.Style>
<Style TargetType="Grid">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding Readiness}" Value="{x:Static db:ReadinessState.DEVELOPMENT}">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
<Ellipse Width="14" Height="14" HorizontalAlignment="Center" VerticalAlignment="Center" Fill="#FF1B468A" />
<TextBlock TextAlignment="Center" Text="D" Foreground="White" />
</Grid>
<Path x:Name="PART_ShapePath" Height="14" Width="14" Fill="#FF1B468A">
<Path.ToolTip>
<ToolTip x:Name="PART_StatusToolTip" />
</Path.ToolTip>
</Path>
</StackPanel>
<DataTemplate.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding LastModifiedTimestamp, Converter={StaticResource IsNullConverter}, diag:PresentationTraceSources.TraceLevel=High}" Value="True" />
<Condition Binding="{Binding LastFailedBuildTimestamp, Converter={StaticResource IsNullConverter}}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter TargetName="PART_ShapePath" Property="Visibility" Value="Collapsed" />
</MultiDataTrigger>
<DataTrigger Binding="{Binding LastFailedBuildTimestamp, Converter={StaticResource IsNullConverter}}" Value="False">
<Setter TargetName="PART_ShapePath" Property="Visibility" Value="Visible" />
<Setter TargetName="PART_ShapePath" Property="Data" Value="M9.0 0.0L0.0 16.0L18.0 16.0L9.00004001084 0.0ZM9.90797917744 14.0L8.0 14.0L8.0 12.0L10.0 12.0L10.0 14.053956628ZM9.43709923716 11.0L8.48917922657 11.0L8.0 6.87502426276L8.0 4.0L10.0 4.0L10.0 6.87502426276L9.43709923716 11.3799755923Z" />
<Setter TargetName="PART_StatusToolTip" Property="Content">
<Setter.Value>
<StackPanel>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding LastFailedBuildTimestamp, TargetNullValue=UNSPECIFIED, StringFormat={}When: {0}}" />
<TextBlock Text="{Binding LastBuildError, TargetNullValue=UNSPECIFIED, StringFormat={}Why: {0}}" />
</StackPanel>
</StackPanel>
</Setter.Value>
</Setter>
</DataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding LastModifiedTimestamp, Converter={StaticResource IsNullConverter}}" Value="False" />
<Condition Binding="{Binding LastFailedBuildTimestamp, Converter={StaticResource IsNullConverter}}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter TargetName="PART_ShapePath" Property="Visibility" Value="Visible" />
<Setter TargetName="PART_ShapePath" Property="Data" Value="M 0,11 0,14 3.0056497,14 11.706214,5.220339 8.7005652,2.2146893 0,11 0,11 Z M 14,2.9265537 C 14.316384,2.6101695 14.316384,2.1355932 14,1.819209 L 12.180791,0 C 11.864407,-0.31638417 11.38983,-0.31638417 11.073446,0 L 9.6497174,1.4237288 12.655366,4.4293786 14,3 14,3 Z" />
<Setter TargetName="PART_StatusToolTip" Property="Content">
<Setter.Value>
<StackPanel>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding LastModifiedTimestamp, TargetNullValue=UNSPECIFIED, StringFormat={}When: {0}}" />
<TextBlock Text="{Binding LastModifiedBy, TargetNullValue=UNKNOWN, StringFormat={}Modified by: {0}}" />
</StackPanel>
</StackPanel>
</Setter.Value>
</Setter>
</MultiDataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</code></pre>
<p><strong>EDIT:</strong> The Datacontext is set to the object with the following properties' definitions:</p>
<pre><code>public ReadinessState Readiness
{
get { return _payload.Readiness; }
set
{
bool t = _payload.Readiness != value;
if (t)
{
_payload.Readiness = value;
OnPropertyChanged("Readiness");
}
}
}
public DateTimeOffset? LastModifiedTimestamp
{
get
{
return _payload?.LastModifiedTimestamp;
}
set
{
if (_payload != null && _payload.LastModifiedTimestamp != value)
{
LastModifiedBy = LockingSession?.Username;
_payload.LastModifiedTimestamp = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("LastModifiedTimestamp"));
}
}
}
public DateTimeOffset? LastFailedBuildTimestamp
{
get
{
return _payload?.LastFailedBuildTimestamp;
}
set
{
if (_payload != null && _payload.LastFailedBuildTimestamp != value)
{
_payload.LastFailedBuildTimestamp = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("LastFailedBuildTimestamp"));
}
}
}
public string LastModifiedBy
{
get
{
return _payload?.LastModifiedBy;
}
private set
{
if (_payload != null && _payload.LastModifiedBy != value)
{
_payload.LastModifiedBy = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("LastModifiedBy"));
}
}
}
public string LastBuildError
{
get
{
return _payload?.LastBuildError;
}
set
{
if (_payload != null && _payload.LastBuildError != value)
{
_payload.LastBuildError = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("LastBuildError"));
}
}
}
</code></pre>
<p>The binding to Readiness works fine, but LastModifiedTimestamp isn't. IsNullConverter never gets called.</p>
| <p>I ended up taking the easy out and put the triggers in the style of the element I tried to manipulate:</p>
<pre><code> <Path x:Name="PART_ShapePath" Height="14" Width="16" Fill="#FF1B468A">
<Path.Style>
<Style TargetType="Path">
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding LastModifiedTimestamp, Converter={StaticResource IsNullConverter}}" Value="True" />
<Condition Binding="{Binding LastFailedBuildTimestamp, Converter={StaticResource IsNullConverter}}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter Property="Visibility" Value="Collapsed" />
</MultiDataTrigger>
<DataTrigger Binding="{Binding LastFailedBuildTimestamp, Converter={StaticResource IsNullConverter}}" Value="False">
<Setter Property="Visibility" Value="Visible" />
<Setter Property="Data" Value="M9.0 0.0L0.0 16.0L18.0 16.0L9.00004001084 0.0ZM9.90797917744 14.0L8.0 14.0L8.0 12.0L10.0 12.0L10.0 14.053956628ZM9.43709923716 11.0L8.48917922657 11.0L8.0 6.87502426276L8.0 4.0L10.0 4.0L10.0 6.87502426276L9.43709923716 11.3799755923Z" />
<Setter Property="ToolTip">
<Setter.Value>
<StackPanel>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding LastFailedBuildTimestamp, TargetNullValue=UNSPECIFIED, StringFormat={}When: {0}}" />
<TextBlock Text="{Binding LastBuildError, TargetNullValue=UNSPECIFIED, StringFormat={}Why: {0}}" />
</StackPanel>
</StackPanel>
</Setter.Value>
</Setter>
</DataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding LastModifiedTimestamp, Converter={StaticResource IsNullConverter}}" Value="False" />
<Condition Binding="{Binding LastFailedBuildTimestamp, Converter={StaticResource IsNullConverter}}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter Property="Visibility" Value="Visible" />
<Setter Property="Data" Value="M 0,11 0,14 3.0056497,14 11.706214,5.220339 8.7005652,2.2146893 0,11 0,11 Z M 14,2.9265537 C 14.316384,2.6101695 14.316384,2.1355932 14,1.819209 L 12.180791,0 C 11.864407,-0.31638417 11.38983,-0.31638417 11.073446,0 L 9.6497174,1.4237288 12.655366,4.4293786 14,3 14,3 Z" />
<Setter Property="ToolTip">
<Setter.Value>
<StackPanel>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding LastModifiedTimestamp, TargetNullValue=UNSPECIFIED, StringFormat={}When: {0}}" />
<TextBlock Text="{Binding LastModifiedBy, TargetNullValue=UNKNOWN, StringFormat={}Modified by: {0}}" />
</StackPanel>
</StackPanel>
</Setter.Value>
</Setter>
</MultiDataTrigger>
</Style.Triggers>
</Style>
</Path.Style>
</Path>
</code></pre>
|
How to readjust Constraint Layout <p>In my app, I have a custom layout that use Constraint Layout to display two views as follow.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.constraint.Guideline
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/guideline2"
android:orientation="horizontal"
tools:layout_editor_absoluteY="444dp"
tools:layout_editor_absoluteX="0dp"
app:layout_constraintGuide_percent="0.5"/>
<CategorySelectionLayout
android:id="@+id/categoryList"
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="horizontal"
android:gravity="center_vertical"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent" />
<CategoryNavigationLayout
android:id="@+id/navigation"
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="horizontal"
android:gravity="center_vertical"
android:paddingLeft="@dimen/one_grid"
tools:layout_manager="android.support.v7.widget.LinearLayoutManager"
tools:listitem="@layout/order_selection_item"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintBottom_toTopOf="@+id/guideline2" />
</android.support.constraint.ConstraintLayout>
</code></pre>
<p>Now imagine when there's nothing to display inside categoryList, I'd like to hide it(View.GONE) then resize the constraint layout to only use the space required for navigation layout.</p>
<p>I have tried to set visibility inside custom view. </p>
<pre><code>this.visibility = View.GONE
this.parent.requestLayout()
</code></pre>
<p>The view is now hidden but parent did not adjust the size accordingly.</p>
<p>So how do I force this ConstraintLayout to readjust it's size?</p>
| <p>The problem you encounter is simply that your second view is constrained by the guideline -- as is the first view. The guideline itself is constrained to the container.</p>
<p>What that means is that it doesn't matter that you mark your first view as <code>GONE</code> -- yes, it will disappear, but this will not impact the layout at all:</p>
<ul>
<li>the guideline is constrained to the parent, so it doesn't care</li>
<li>the view that is visible is constrained to the parent and the guideline,
so doesn't care either.</li>
</ul>
<p>So it's perfectly normal that nothing changes other than the view disappearing.</p>
<p>To do what you want, you could instead do something like that:</p>
<pre><code> final View viewA = findViewById(R.id.viewA);
final View guideline = findViewById(R.id.guideline);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) guideline.getLayoutParams();
if (viewA.getVisibility() == View.GONE) {
viewA.setVisibility(View.VISIBLE);
params.guidePercent = 0.5f;
} else {
viewA.setVisibility(View.GONE);
params.guidePercent = 0;
}
guideline.setLayoutParams(params);
}
});
</code></pre>
<p>This will change the position of the guideline, which will make the layout react.</p>
<p>I'm pasting the XML just to be exhaustive, but it's pretty much what you had:</p>
<p>
</p>
<pre><code><android.support.constraint.Guideline
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/guideline"
android:orientation="horizontal"
tools:layout_editor_absoluteY="303dp"
tools:layout_editor_absoluteX="0dp"
app:layout_constraintGuide_percent="0.50248754" />
<View
android:id="@+id/viewA"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@color/colorAccent"
android:text="Button"
app:layout_constraintBottom_toTopOf="@+id/guideline"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="@+id/viewB"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="8dp"
android:background="@color/colorPrimary"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginEnd="24dp"
android:layout_marginRight="24dp"
android:text="Toggle"
app:layout_constraintBottom_toBottomOf="@+id/viewB"
app:layout_constraintRight_toRightOf="@+id/viewB" />
</code></pre>
<p></p>
<p><a href="http://i.stack.imgur.com/50V1p.png" rel="nofollow"><img src="http://i.stack.imgur.com/50V1p.png" alt="enter image description here"></a></p>
|
Videos Not auto playing on mobiles and tablets <p>I have created a website, first proper website, with bootstrap. Almost got the website to where i want it to be. I have a video on the main page (.mp4 1080p), which i have set to loop and auto play. Works perfect on laptops, but cant seem to get it to work on properly on phones and tablets. </p>
<p>Tried it on an Ipad and and Iphone, and the auto play doesnt work, i have to click the play button. I have looked into this and it is supposed to work on anything above IOS10, which they both were, and doesnt have any soundtrack, which is also the case. On my android phone it just shows up as a black box and i cant play or pause or anything. </p>
<p>Any help would be appreciated. the website is actually live www.dtlaerialservices.co.uk, i can place the code here if required.</p>
<pre><code><div class="container-fluid">
<div align="center" class="embed-responsive embed-responsive-16by9">
<video autoplay loop class="embed-responsive-item">
<source src="videos/loop.mp4" type="video/mp4">
</video>
</code></pre>
| <p>This is a very common problem, and it's an encoding issue. You will need to encode your video using <strong>H264</strong> as the video codec, and <strong>AAC</strong> as the audio codec.</p>
<p>When you use H264 as your video codec, you will also need to choose a profile. Higher profiles require more CPU power to decode and are able to generate better looking videos at same bitrate. You should always choose the best profile your target devices support.</p>
<p>For example, the max supported profile for Desktop browsers, iPhone 4S+, iPad 2+, Android 4.x+ tablets, Xbox 360, Playstation 3 is <strong>High profile</strong>.</p>
<p>Most devices also have a maximum resolution and bitrate they can handle. That is usually expressed in as a H.264 level.</p>
<p>You can re-encode your video using the <strong>ffmpeg</strong> utility.</p>
<p>I personally use a website called <a href="https://cloudconvert.com/mp4-to-mp4" rel="nofollow">CloudConvert</a>, you just have to set the conversion options to:</p>
<ul>
<li>Video Codec: H264</li>
<li>Audio Codec: AAC</li>
<li>Leave the other options at their default values</li>
</ul>
<p>There is also good information <a href="https://www.virag.si/2012/01/web-video-encoding-tutorial-with-ffmpeg-0-9/" rel="nofollow">here</a>.</p>
|
Elseif returns #VALUE <p>Ok, so all I want to do is create a function to optimize how I can segment my PivotTable data. This data comes in different forms like "245896321 - Name", "name" or "name23123" and I want it to return the persons full name if the cells contains specific texts (person last name), but it only returns #VALUE!</p>
<p>Thanks in advance! You're beautiful! </p>
<p>Also I apologize if my coding hurts your eyes just started my adventure into the coding world two days ago, if you want to suggest modifications feel free! :)</p>
<pre><code>Function Financeiro (Line) as String
'=IF(ISNUMBER(SEARCH("*Person*", Line)), "Person Name")
If Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("*Ormelli*", Line)) Then
Financeiro = "Fernando Ormelli"
ElseIf Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("*Fortuna*", Line)) Then
Financeiro = "Ricardo Fortuna"
ElseIf Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("*Manocchio*", Line)) Then
Financeiro = "Ricardo Manocchio"
ElseIf Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("*Stanquini*", Line)) Then
Financeiro = "Helder Stanquini"
ElseIf Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("*Ivanete*", Line)) Then
Financeiro = "Ivanete Leite"
ElseIf Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("*Freitas*", Line)) Then
Financeiro = "João Freitas"
ElseIf Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("*Khan*", Line)) Then
Financeiro = "Marcelo Khan"
ElseIf Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("*Filho*", Line)) Then
Financeiro = "Marco Filho"
ElseIf Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("*Rocha*", Line)) Then
Financeiro = "Natalia Rocha"
ElseIf Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("*Carvalho*", Line)) Then
Financeiro = "Vinicius Carvalho"
ElseIf Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("*SAE*", Line)) Then
Financeiro = "SAE"
ElseIf Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("*Raphael*", Line)) Then
Financeiro = "Raphael Vieira"
Else
Financeiro = "Manual"
End If
End Function
</code></pre>
| <p><code>Application.WorksheetFunction.Search</code> will throw a runtime error if there's no match: try instead something like:</p>
<pre><code>If Application.WorksheetFunction.IsNumber(Application.Search("*Ormelli*", Line)) Then
'...
</code></pre>
<p>Omitting the <code>WorksheetFunction</code> switches the behavior from triggering a runtime error to instead returning an error value.</p>
<p>Or just use:</p>
<pre><code>If Line Like "*Ormelli*" Then
'...
</code></pre>
<p>which I think is easier to follow.</p>
|
ZF2, controller doesn't fill the form elements from hydrated objects that are attached to the form <p>In ZF2, I have a form that has two fieldsets. The 2 fieldsets are basically for party-related info (party = person or company) and phone-related info. The fieldsets are called using the init method of the form like this</p>
<pre><code>class PhoneRegistrationForm extends RegistrationForm implements InputFilterAwareInterface
{
public function __construct()
{
parent::__construct();
$this
->setAttribute('method', 'post')
->setHydrator(new ClassMethods(false))
->setObject(new Phone());
$this->add([
'type' => 'Zend\Form\Element\Button',
'name' => 'submitButton',
'attributes' => [
'id' => 'submit-phone-button',
'class' => 'btn2 submit-button',
'type' => 'submit',
],
'options' => [
'label' => 'СоÑ
ÑаниÑÑ',
],
]);
}
public function init()
{
$this->add([
'type' => 'Parties\Forms\Fieldsets\PhoneFieldset',
'name' => 'phoneFieldset'
]);
$this->add([
'type' => 'Parties\Forms\Fieldsets\PartyIdAndRolesFieldset',
'name' => 'partyFieldset'
]);
}
}
</code></pre>
<p>In the controller's edit action, I create and hydrate the PhoneObject and PartyObject with the values from the database (PhoneObject and PartyObjects are just collection of getters and setters). I then set the hydrated objects to the fieldsets:</p>
<pre><code>$this->form->get('phoneFieldset')->setObject($phone);
$this->form->get('partyFieldset')->setObject($party);
</code></pre>
<p>And here is my problem, if I return the instance of form to the controller, the form inputs have no values that come from the attached hydrated objects.</p>
<p>How to get the form inputs filled with the values from the hydrated objects attached to fieldsets?</p>
<p>I tried binding <code>$this->form->bind($phone)</code>, but to no avail. The fieldsets have <code>ClassMethods()</code> hydrator set too.</p>
<p>What could the problem be? Any clues? </p>
<p>EDIT: after answer by @hooli, this is the code for the fieldset that I use.</p>
<pre><code>class PhoneFieldsetFactory extends Fieldset implements InputFilterProviderInterface
{
public function __invoke(FormElementManager $formElementManager)
{
$this
->setHydrator(new ClassMethods())
->setObject(new Phone());
$this->add([
'type' => 'hidden',
'name' => 'id',
]);
$this->add(
$formElementManager
->get('Parties\Forms\Elements\ContactMechanismTypeSelect',
['mechanismType' => 'ÑелеÑон'])
);
$this->add(
$formElementManager
->get('Parties\Forms\Elements\CountrySelect')
);
$this->add(
$formElementManager
->get('Parties\Forms\Elements\ContactMechanismPurposeTypeMultiCheckbox',
['mechanismType' => 'ÑелеÑон'])
);
$this->add([
'type' => 'text',
'name' => 'areaCode',
'attributes' => [
'id' => 'area-code',
'placeholder' => '1234',
],
'options' => [
'label' => 'Ðод облаÑÑи'
],
]);
$this->add([
'type' => 'text',
'name' => 'phoneNbr',
'attributes' => [
'id' => 'phone-nbr',
'placeholder' => '1234567890',
],
'options' => [
'label' => 'ÐÐ¾Ð¼ÐµÑ ÑелеÑона',
],
]);
$this->add([
'type' => 'text',
'name' => 'extension',
'attributes' => [
'id' => 'extension',
'placeholder' => '1234567890',
],
'options' => [
'label' => 'ÐобавоÑнÑй',
],
]);
$this->add([
'type' => 'text',
'name' => 'comment',
'attributes' => [
'id' => 'comment',
'placeholder' => 'обÑий ÑелеÑон оÑганизаÑии',
],
'options' => [
'label' => 'ÐÑимеÑание',
],
]);
return $this;
}
}
</code></pre>
| <p>THIS IS NOT A REALLY GOOD SOLUTION, PLEASE FEEL FREE TO SUGGEST BETTER VARIANTS! I WILL MAKE YOUR ANSWER ACCEPTED IF IT'S BETTER.</p>
<p>After a day of trials and errors still couldn't figure out why the form inputs don't get filled based on the objects attached to the fieldsets. I found, though, a workaround for this.</p>
<p>A ZF2 <code>Fieldset</code> implements the method <code>populateValues()</code>. If you use something like this</p>
<pre><code>$this->form->get('neededFieldset')->populateValues(
$this->form->getHydrator()->extract($objectWhoseValuesWillBeExtracted));
</code></pre>
<p>you'll have the form's inputs filled with the corresponding object's data.</p>
|
Where to Add text file on an Android Sudio Project to place internal comments that won't be deployed on APK <p>I want to add a text file on Android Studio where to place internal comments, ideas, development status, pendings, etc. </p>
<p>The issue is that I don't want this file to be part of deployment APK's, but I want to have it inside Android Studio project for simplicity.</p>
<p>I found somewhere that suggest to put it at resources folder: <code>res/raw</code>, but this content will be deployed on APK and I don't want it.</p>
<p>Thanks in advance</p>
| <p>Create a <code>notes/</code> directory off of the project root. Or a <code>docs/</code> directory. Or whatever you want. </p>
<p>Everything inside of <code>src/</code> for a module is a candidate for being included in an APK. Conversely, stuff in directories that Android Studio does not know about (e.g., <code>notes/</code>, <code>docs/</code>, <code>super-sekrit-stuff/</code>) will not be included in an APK, unless you do something specific in the Gradle build files to request that they be included.</p>
|
Android - Set Image by 2 Constrained Variables <p>First off, I've been coding for all of a few months, so I'm sorry if any of the following is very basic... I'm pretty terrible with Java.</p>
<p>I'm looking to pick an image from an imaginary "grid/array" based on two variables (x and y, to keep it simple) and display that image, using gestures(fling) to move in between different images. I have no red lines in my code, but everytime I start the Activity I get the error code at the bottom.</p>
<p>I also am not sure how to use Integer.MAX_VALUE and Integer.MIN_VALUE to constrain the two variables so that the app doesn't try to pull for a value that doesn't exist. X can be from 1-5, and y can be from 1-3, and I don't know how to constrain them... filenames are "seat11.png" through "seat53.png".</p>
<p>Here are the relevant code samples:</p>
<p>Setting integers:</p>
<pre><code>private GestureDetectorCompat gestureDetector;
public ImageView seatImage;
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
int x = 3;
int y = 1;
String seatNumber = "R.drawable.seat" + x + y;
int seat = Integer.valueOf(seatNumber);
</code></pre>
<p>Relevant gesture:</p>
<pre><code>@Override
public boolean onFling (MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
//swipe right//
x = x + 1;
seatImage.setImageResource(seat);
} else {
//swipe left//
x = x - 1;
seatImage.setImageResource(seat);
}
}
result = true;
}
else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
//swipe down//
y = y - 1;
seatImage.setImageResource(seat);
} else {
//swipe up//
y = y + 1;
seatImage.setImageResource(seat);
}
}
result = true;
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
</code></pre>
<p>With a double tap to return to the "home" image:</p>
<pre><code>@Override
public boolean onDoubleTap(MotionEvent e) {
x = 3;
y = 1;
seatImage.setImageResource(seat);
return true;
}
</code></pre>
<p>I'm getting the following error text:</p>
<pre><code>java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.flextronics.doordisplaydemo/com.flextronics.doordisplaydemo.FlexSeat}: java.lang.NumberFormatException: Invalid int: "R.drawable.seat32"
Caused by: java.lang.NumberFormatException: Invalid int: "R.drawable.seat32"
</code></pre>
<p>I've tried just about everything I can think of (and find in other answers) and I'm at a total loss. The code provided <strong>SEEMS</strong> to be the closest to correct that I've gotten.</p>
| <p>This here:</p>
<pre><code>String seatNumber = "R.drawable.seat" + x + y;
int seat = Integer.valueOf(seatNumber);
</code></pre>
<p>Is trying to convert the string to a number, but that won't work as the string does not contain a number. What you're looking for is this:</p>
<pre><code>int seat = getResources().getIdentifier("seat" + x + y, "drawable", getPackageName());
</code></pre>
<p>From: <a href="http://stackoverflow.com/a/19093447/360211">http://stackoverflow.com/a/19093447/360211</a></p>
|
Propagating arguments to decorator which combines other decorators <p>I have a scenario like:</p>
<pre><code>@decorator_one(1)
@foo
@bar
def my_decorated_func():
pass
</code></pre>
<p>I am trying to condense this into something like:</p>
<pre><code>@my_custom_decorator(1)
def my_decorated_func():
pass
</code></pre>
<p>This is straightforward if I have decorators that do not have <code>(1)</code> option:</p>
<pre><code>def my_custom_decorator(f):
@decorator_one
@foo
@bar
def wrapped():
pass
return wrapped
</code></pre>
<p>However I am uncertain how to properly propagate the argument to the first wrapper. </p>
<p>In this case, I am comfortable assuming that if I pass 1 to my_custom_decorator that it will always and only be the arg for decorator_one.</p>
| <p><code>@decorator_one(1)</code> means that there is a callable that returns a decorator; call it a decorator <em>factory</em>. <code>decorator_one(1)</code> returns the decorator that is then applied to the function.</p>
<p>Just pass on the arguments from your own decorator factory:</p>
<pre><code>def my_custom_decorator(*args, **kwargs): # the factory
def decorator(f): # the decorator
@decorator_one(*args, **kwargs)
@foo
@bar
def wrapped():
pass
return wrapped
return decorator
</code></pre>
<p>I used <code>*args, **kwargs</code> to pass on arbitrary arguments to the wrapped decorator factory <code>decorator_one()</code>, but you could also use explicitly named paramaters.</p>
|
Virtualenv within single executable <p>I currently have an executable file that is running Python code inside a zipfile following this: <a href="https://blogs.gnome.org/jamesh/2012/05/21/python-zip-files/" rel="nofollow">https://blogs.gnome.org/jamesh/2012/05/21/python-zip-files/</a></p>
<p>The nice thing about this is that I release a single file containing the app. The problems arise in the dependencies. I have attempted to install files using pip in custom locations and when I embed them in the zip I always have import issues or issues that end up depending on host packages. </p>
<p>I then started looking into virtual environments as a way to ensure package dependencies. However, it seems that the typical workflow on the target machine is to source the activation script and run the code within the virtualenv. What I would like to do is have a single file containing a Python script and all its dependencies and for the user to just execute the file. Is this possible given that the Python interpreter is actually packaged with the virtualenv? Is it possible to invoke the Python interpreter from within the zip file? What is the recommended approach for this from a Python point of view?</p>
| <p>You can create a bash script that creates the virtual env and runs the python scripts aswell. </p>
<pre><code>!#/bin/bash
virtualenv .venv
.venv/bin/pip install <python packages>
.venv/bin/python script
</code></pre>
|
Android GridView Height Autofill the Remaing Space <p>Is it possible for a GridView to auto adjust to occupy the remaining empty space of its parent layout? If yes how ? </p>
| <p>Yeah. It is possible.</p>
<p>Let's consider following xml,</p>
<pre><code><RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
//First View or layout
<RelativeLayout
android:id="@+id/first_layout"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#000">
</RelativeLayout>
//Second View or layout
<RelativeLayout
android:id="@+id/second_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/first_layout"
android:background="#8b3737">
</RelativeLayout>
</RelativeLayout>
</code></pre>
<p>In your Activity,</p>
<pre><code> RelativeLayout layout_one=(RelativeLayout)findViewById(R.id.first_layout);
RelativeLayout layout_two=(RelativeLayout)findViewById(R.id.second_layout);
</code></pre>
<p>when you set,</p>
<pre><code> layout_one.setVisibility(View.GONE);
</code></pre>
<p>then the second Layout/View will occupy the whole parent space.</p>
<p>NOTE: I took relative layouts for examples. It can be any view. But the parent should be a RelativeLayout.</p>
<p>If you want second layout to be hidden and first layout should fill parent,</p>
<p>Then the XML will be,</p>
<pre><code><RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
//First View or layout
<RelativeLayout
android:id="@+id/first_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/second_layout"
android:background="#000">
</RelativeLayout>
//Second View or layout
<RelativeLayout
android:id="@+id/second_layout"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#8b3737">
</RelativeLayout>
</RelativeLayout>
</code></pre>
<p>when you set,</p>
<pre><code> layout_two.setVisibility(View.GONE);
</code></pre>
<p>then the first Layout/View will occupy the whole parent space.</p>
<p>NOTE: At least one Layout/View should have static height(in this case).</p>
<p>I hope it will help you.</p>
<p>All the best.</p>
|
Elm Http Request on Init <p>I'm pretty new to Elm, but slowly getting familiar with it. I'm doing some simple Http Requests, which are successful in every aspect (I get the data to display, etc.)</p>
<p>For the moment I can only get my fetchData to trigger onClick, I would like to initialize this on init, but I'm having trouble wrapping my head around this.</p>
<p>....here is my fetchData function:</p>
<pre><code>fetchData : Cmd Msg
fetchData =
Http.get repoInfoListDecoder "http://example/api"
|> Task.mapError toString
|> Task.perform ErrorOccurred DataFetched
</code></pre>
<p>Which is currently trigger in the view by a onClick event:</p>
<pre><code>.....
, button [ onClick FetchData ] [ text "Load Data" ]
.....
</code></pre>
<p>I want to avoid requesting the data by a button, instead I want the data to load when the app is initialized. Here is my init:</p>
<pre><code>init =
let
model =
{ message = "Welcome", repos = [] }
in
model ! []
</code></pre>
<p>And my update (kind of stripped...for example's sakes): </p>
<pre><code>update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
NoOp ->
model ! []
...........
FetchData ->
{ model | message="hi" } ! [fetchData]
...........
DataFetched repos ->
{ model | repos = repos, message = "The data has been fetched!" } ! []
</code></pre>
<p>Does this makes sense? I'm just having difficulty initializing fetchData when the app loads, so I can display my data without having to hit a button to fetch it. </p>
<p>Thanks in advance!</p>
| <p>When you use <a href="http://package.elm-lang.org/packages/elm-lang/html/1.1.0/Html-App#program">Html.App.program</a>, your <code>init</code> returns the initial data for your Model and some kind of Command to be executed.</p>
<p>Commands are side-effects, like HTTP requests.</p>
<p>Try changing <code>init</code> so it runs a Command right away:</p>
<pre><code>init: (Model, Cmd Msg)
init =
let
model =
{ message = "Welcome", repos = [] }
in
model ! [ fetchData ]
</code></pre>
|
Configuration from Spring Config Server overrides server port vm argument <p>I have the following services:</p>
<ol>
<li>Spring Cloud Config Server</li>
<li>Eureka Discovery Service</li>
<li>Event Service (spring boot app)</li>
</ol>
<p>I use "Config First" mode. It means I start Config Server first and after that I start Discovery Service.</p>
<p>Then I run event service. It takes configuration from Config Server. In configuration I specify server.port property equals to 8081.</p>
<p>I see that my event service is being registered in discovery service.</p>
<p>The issue comes when I'm trying to start one more instance of event service. To run it on a different port, I use -Dserver.port vm argument. So my command looks like:</p>
<p><code>java -jar event-service.jar -Dserver.port=8082</code></p>
<p>But application fails to start, saying that 8081 is already in use. It seems like event service uses configuration from config server and this configuration takes precedence over VM arguments. But I was thinking that it should be vice-verca.</p>
| <p>The order of your command line arguments is wrong: the <code>system variable</code> must be before the jarfile:</p>
<pre><code>$ java -jar -Dserver.port=8082 event-service.jar
</code></pre>
<h1>3 ways to override properties from the command line</h1>
<ul>
<li>Environment variable: <code>$ server_port=8082 java -jar event-service.jar</code>;</li>
<li>System variable: <code>$ java -jar -Dserver.port=8082 event-service.jar</code>;</li>
<li>Command line argument: <code>$ java -jar event-service.jar --server.port=8082</code>.</li>
</ul>
<p>Notice that for <code>environment variable</code>, the <code>dots</code> are replaced with <code>underscores</code>.</p>
<p>source: <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html" rel="nofollow">https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html</a></p>
|
Python elif not working in order I want <p><code>Transaction_Code</code> == <code>"W"</code>, <code>"w"</code>, <code>"D"</code> or <code>"d"</code></p>
<p>if not, it should be running <code>Process_Invalid_Code(Previous_Balance)</code></p>
<p>What is happening, however is if input for <code>Transaction_Code</code> != <code>"W"</code>, <code>"w"</code>, <code>"D"</code> or <code>"d"</code>, it then continues to run the <code>"What is your previous balance?"</code> and <code>"How much is the transaction amount?"</code> input... </p>
<p>ONLY THEN, after you give input for those does it run <code>Invalid_Transaction_Code</code></p>
<p>What I WANT to happen is for it to throw <code>Invalid_Transaction_Code ("Invalid Transaction Code!")</code> etc. BEFORE without wasting the users time asking for Previous Balance and Transaction..</p>
<p>Does that make sense?</p>
<p>Here is the code</p>
<pre><code>#The main function definition
def main():
Name = input("What is your name? ")
Account_ID = input("What is your account ID? ")
Transaction_Code = input("Press W or w for Withdrawal, Press D or d for Deposit: ")
Previous_Balance = float(input("What is your previous balance? "))
Transaction_Amount = float(input("How much is the transaction amount? "))
if Transaction_Code == "W" or Transaction_Code == "w":
Withdrawal_Process(Previous_Balance, Transaction_Amount)
elif Transaction_Code == "D" or Transaction_Code == "d":
Deposit_Process(Previous_Balance, Transaction_Amount)
else:
Process_Invalid_Code(Previous_Balance)
#Defines the Deposit Process
def Deposit_Process(Previous_Balance, Transaction_Amount):
New_Balance = Transaction_Amount + Previous_Balance
Print_Function(New_Balance)
#Defines the Withdrawal Process
def Withdrawal_Process(Previous_Balance, Transaction_Amount):
if Transaction_Amount > Previous_Balance:
print("Invalid Transaction: Not Sufficient Funds!")
New_Balance = Previous_Balance
Print_Function(New_Balance)
else:
New_Balance = Previous_Balance - Transaction_Amount
Print_Function(New_Balance)
#The Invalid Code Function Definition
def Process_Invalid_Code(Previous_Balance):
New_Balance = Previous_Balance
print ("Invalid Transaction Code!")
print ("Please type W or w for Withdrawal")
print ("or type D or d for Deposit")
Print_Function(New_Balance)
#Defines the Print Function
def Print_Function(New_Balance):
print ("Your balance is now $", format(New_Balance, '.2f'))
#Call the main function
main()
</code></pre>
| <p>Since all of your desired actions need <code>Previous_Balance</code> you must ask for it in any case:</p>
<pre><code>def main():
# never used, lets ask anyway
Name = input("What is your name? ")
# we need this information at a minimum
Previous_Balance = float(input("What is your previous balance? "))
Transaction_Code = input("Press W or w for Withdrawal, Press D or d for Deposit: ")
# if its a withdrawal/deposit, find the amount and account
if Transaction_Code.upper() in "WD":
# we never use this Account_ID ...
Account_ID = input("What is your account ID? ")
Transaction_Amount = float(input("How much is the transaction amount? "))
if Transaction_Code.upper() == "W":
Withdrawal_Process(Previous_Balance, Transaction_Amount)
else:
Deposit_Process(Previous_Balance, Transaction_Amount)
else:
# they've entered a bad code
Process_Invalid_Code(Previous_Balance)
</code></pre>
|
How to enable the select option text to go to the next line in firefox? <p>How to enable the select option text to go to the next line in firefox?</p>
<p>In chrome, the text goes to the next line for the option element but it does not go in firefox. I have tried a lot of css classes but does not work. I have provided the image and the code below. Really appreciate your help. Thanks in advance.</p>
<p>Below are the 2 images:</p>
<p><a href="http://i.stack.imgur.com/oU5zn.png" rel="nofollow">chrome </a> (correct)</p>
<p><a href="http://i.stack.imgur.com/mY48b.png" rel="nofollow">firefox</a> (incorrect - want to fix this one)</p>
<p>Code:</p>
<pre><code><select class="detail-ta" id="detail-ta2" size="10">
<option style="text-overflow: clip; overflow: visible; white-space: -moz-pre-wrap; white-space: pre-wrap; margin-bottom: 1px;"></option>
</select>
</code></pre>
| <p>For me it works using only CSS but it has a bug that the last word is covered by the scroll bar in Firefox.
You specify the width and also add display:inline-block</p>
<pre><code> white-space: -moz-pre-wrap; /* Firefox */
white-space: pre-wrap; /* other browsers */
width:150px;
display:inline-block
</code></pre>
|
Using Pandas to Create DateOffset of Paydays <p>I'm trying to use Pandas to create a time index in Python with entries corresponding to a recurring payday. Specifically, I'd like to have the index correspond to the first and third Friday of the month. Can somebody please give a code snippet demonstrating this?</p>
<p>Something like:</p>
<pre><code>import pandas as pd
idx = pd.date_range("2016-10-10", periods=26, freq=<offset here?>)
</code></pre>
| <p>try this:</p>
<pre><code>In [6]: pd.date_range("2016-10-10", periods=26, freq='WOM-1FRI').union(pd.date_range("2016-10-10", periods=26, freq='WOM-3FRI'))
Out[6]:
DatetimeIndex(['2016-10-21', '2016-11-04', '2016-11-18', '2016-12-02', '2016-12-16', '2017-01-06', '2017-01-20', '2017-02-03', '2017-02-17',
'2017-03-03', '2017-03-17', '2017-04-07', '2017-04-21',
'2017-05-05', '2017-05-19', '2017-06-02', '2017-06-16', '2017-07-07', '2017-07-21', '2017-08-04', '2017-08-18', '2017-09-01',
'2017-09-15', '2017-10-06', '2017-10-20', '2017-11-03',
'2017-11-17', '2017-12-01', '2017-12-15', '2018-01-05', '2018-01-19', '2018-02-02', '2018-02-16', '2018-03-02', '2018-03-16',
'2018-04-06', '2018-04-20', '2018-05-04', '2018-05-18',
'2018-06-01', '2018-06-15', '2018-07-06', '2018-07-20', '2018-08-03', '2018-08-17', '2018-09-07', '2018-09-21', '2018-10-05',
'2018-10-19', '2018-11-02', '2018-11-16', '2018-12-07'],
dtype='datetime64[ns]', freq=None)
</code></pre>
|
overriding a method in UICollectionViewLayout in Swift with an error <p>I need to make a change to an app that we are developing and am not a full-time iOS dev. I'm trying to get a pinterest like interface for an iOS app and am working through the tutorial here: <a href="https://www.raywenderlich.com/107439/uicollectionview-custom-layout-tutorial-pinterest" rel="nofollow">https://www.raywenderlich.com/107439/uicollectionview-custom-layout-tutorial-pinterest</a></p>
<p>In their custom UICollectionViewLayout, they override <code>layoutAttributesForElementsinRect</code> but I'm getting an error from the XCode 8 compiler (although running with Use Legacy Swift Language Version set to Yes). </p>
<p>The error I get is: <code>Method does not override any method from its superclass</code></p>
<p>The abbreviated code is: </p>
<pre><code>class PinterestLayout: UICollectionViewLayout {
....
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
// Loop through the cache and look for items in the rect
for attributes in cache {
if CGRectIntersectsRect(attributes.frame, rect ) {
layoutAttributes.append(attributes)
}
}
return layoutAttributes
}
</code></pre>
<p>If I switch the method to private it compiles but doesn't work and if I remove the override, it gives me a conflict. I do want to override the underlying method but am not sure how to get this to work. </p>
| <p>You have the wrong method signature. This is actually the reason the <code>override</code> keyword exists. It ensures an API change will be caught like this, rather than the override silently not occurring, leading to hard to diagnose issues.</p>
<p>It should be</p>
<pre><code>override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]?
</code></pre>
|
Log4net ADONetAppender - View parameter values? <p>Is it possible to view the AdoNetAppenderParameter values when debugging log4net?</p>
<p>If so, how?</p>
<p>Thanks!</p>
| <p>In the sourcecode from <a href="https://github.com/apache/log4net" rel="nofollow">https://github.com/apache/log4net</a> you will find the file AdoNetAppender.cs:</p>
<p>In the <code>virtual public void Prepare(IDbCommand command)</code> the parameters are assigned:</p>
<pre><code>IDbDataParameter param = command.CreateParameter();
// Set the parameter properties
param.ParameterName = ParameterName;
if (!m_inferType)
{
param.DbType = DbType;
}
if (Precision != 0)
{
param.Precision = Precision;
}
if (Scale != 0)
{
param.Scale = Scale;
}
if (Size != 0)
{
param.Size = Size;
}
// Add the parameter to the collection of params
command.Parameters.Add(param);
</code></pre>
<p>When you debug that you can check the parameter-objects.</p>
|
does groupby concatenate the columns? <p>i have a "1000 rows * 4 columns" DataFrame:</p>
<pre><code>a b c d
1 aa 93 4
2 bb 32 3
...
1000 nn 78 2
**[1283 rows x 4 columns]**
</code></pre>
<p>and I use groupby to group them based on 3 of the columns:</p>
<pre><code>df.groupby(['a','b','c']).sum()
print(df)
a b c d
1 aa 93 12
2 bb 32 53
...
1000 nn 78 38
**[1283 rows x 1 columns]**
</code></pre>
<p>however the result give me a "1000 rows * 1 columns" Dataframe. SO my question is if Groupby concatenate columns as one Column? if yes how can I prevent that. I want to plot my data after grouping it but i can't since it only see one column instead of all 4.</p>
<p>edit: when i call the columns i only get the last column, it means it can't read 'a','b','c' as columns, why is that and how can i markl them as column again.</p>
<pre><code>df.columns
Index([u'd'], dtype='object')
</code></pre>
| <p>you can do it this way:</p>
<pre><code>df.groupby(['a','b','c'], as_index=False).sum()
</code></pre>
<p>or:</p>
<pre><code>df.groupby(['a','b','c']).sum().reset_index()
</code></pre>
|
How to write a function of type a-> b -> b -> b for folding a tree <p>Some background: I have a foldT function (like foldr but for trees) of the following type in Haskell. </p>
<pre><code>foldT :: (a -> b -> b -> b) -> b -> Tree a -> b
</code></pre>
<p>This foldT only takes type (a -> b -> b -> b) as an input function.</p>
<p>I am trying to find a way to convert my tree into a list, and cannot figure out a way to make my append function take the form (a -> b -> b -> b). </p>
<p>The following is ineffective because it is not the correct type: </p>
<pre><code>append x y z = append x:y:z
</code></pre>
<p>Any help would be appreciated. </p>
<p>Thank you!</p>
| <p>As you haven't posted it, I will assume your tree is...</p>
<pre><code>data Tree a = Leaf | Node a (Tree a) (Tree a)
</code></pre>
<p>... and that the <code>a -> b -> b -> b</code> argument to <code>foldT</code> takes the fields of the <code>Node</code> constructor in the same order they were declared.</p>
<blockquote>
<p>I am trying to find a way to convert my tree into a list</p>
</blockquote>
<p>Let's begin tackling this by following the types:</p>
<pre><code>foldT :: (a -> b -> b -> b) -> b -> Tree a -> b
</code></pre>
<p>You want to flatten it into a list, so the result type of your function must be <code>[a]</code>:</p>
<pre><code>treeToList :: Tree a -> [a]
</code></pre>
<p>That give us a good idea on how to continue:</p>
<pre><code>treeToList t = foldT f z t
</code></pre>
<p>With:</p>
<pre><code>f :: a -> [a] -> [a] -> [a]
z :: [a]
t :: Tree a
</code></pre>
<p>Now, onward to the arguments. <code>z</code> is what will be inserted in lieu of the valueless <code>Leaf</code>s, and so it must be <code>[]</code>. As for <code>f</code>, it must combine the sublists created from the left and right branches with the value directly in the <code>Node</code>. Assuming an in-order traversal, we have:</p>
<pre><code> treeToList t = foldT (\x l r -> l ++ x : r) [] t
</code></pre>
<p>Or, without mentioning <code>t</code>:</p>
<pre><code> treeToList = foldT (\x l r -> l ++ x : r) []
</code></pre>
<p>And that's it. One caveat is that repeatedly using left-nested <code>(++)</code> (which will happen in this case, as <code>foldT</code> walks down the branches recursively) can get quite inefficient. In a situation in which you would care about performance it would be worth considering alternative ways of implementing the concatenating function, such as <a href="https://hackage.haskell.org/package/dlist-0.8.0.2/docs/Data-DList.html" rel="nofollow">difference lists</a>.</p>
<p>P.S.: A note about terminology. Saying that a function is "like foldr but for trees" is ambiguous, as there are two well-known kinds of functions analogous to <code>foldr</code>. First, you have the methods of the <code>Foldable</code> class (cf. <a href="http://stackoverflow.com/a/39977162/2751851">Benjamin Hodgson's answer</a>), which flatten the tree into a list as they fold it, no matter what you do. Then there are the more powerful <em>catamorphisms</em>, such as the <code>foldT</code> you are using, which are able to make use of the tree structure.</p>
|
PyQt5: Access to QClipboard (or app object) from inside a widget <p>I'm trying to access the clipboard (via QClipboard) in a PyQT5 application, but from a widget a few layers deep. The app object usually provides the clipboard via <code>app.clipboard()</code> but I don't have access to the app object that deep. Is there a way to access either the clipboard or <code>app</code> that doesn't involve passing <code>app</code> all the way down?</p>
| <p>There are two ways to do this:</p>
<pre><code>from PyQt5.QtWidgets import qApp
</code></pre>
<p>or:</p>
<pre><code>from PyQt5.QtWidgets import QApplication
qApp = QApplication.instance()
</code></pre>
<p>The latter is a static method which is inherited from <code>QtCore.QCoreApplication</code>. But then again, <code>clipboard()</code> also static, so another solution would be:</p>
<pre><code>clipboard = QApplication.clipboard()
</code></pre>
|
Exposing a class with a constructor containing a nested private class in constructor using Boost Python <p>I'm new to Boost Python and I'm looking to expose a class that looks like this: </p>
<pre><code>///Header File structure
class A
{ public:
A();
~A();
void B();
private:
class Impl;
std::unique_ptr Impl impl_;
};
///Class Implementation
class A::Impl
{
public:
void C();
}
A::A():impl_(new Impl)
{
}
A::~A()
{
}
void A::B()
{
void C();
}
</code></pre>
<p>Can someone suggest how to do it since the current methods I've tried gives errors since Impl is private and also an accessing already deleted function error:</p>
<pre><code>BOOST_PYTHON_MODULE(libA)
{
class_<A::Impl>("Impl")
.def("C", &A::Impl::C)
class_<A>("A",init<std::unique_ptr>)
.def("B", &A::B)
}
</code></pre>
| <p>The whole point of the pimpl idiom is that it's private and completely transparent to the users of the class. You don't expose it.</p>
<p>What you do need to do is make it clear that <code>A</code> isn't copyable:</p>
<pre><code>class_<A, noncopyable>("A", init<>())
.def("B", &A::B)
;
</code></pre>
|
Python - Selenium : Scroll down not working because of PopUp <p>I am writing a python script using selenium to login to Facebook and then do some scrapping. For that purpose, <strong>I have to scroll down to the bottom of the page. I think the pop that you can see in the picture is the cause of this.</strong>
Here is the snippet of code which does the following thing</p>
<pre><code>elem = driver.find_element_by_id("email")
elem.send_keys(usr)
elem = driver.find_element_by_id("pass")
elem.send_keys(pwd)
elem.send_keys(Keys.RETURN)
driver.get("https://www.facebook.com/jatin.wadhwa.52/friends?source_ref=pb_friends_tl")
time.sleep(10)
element_new = driver.find_element_by_tag_name('html')
element_new.send_keys(Keys.ESCAPE)
element_new.send_keys(Keys.END)
#driver.execute_script("window.scrollTo(0, 1000);")
f = driver.find_elements_by_xpath("//ul")
</code></pre>
<p><a href="http://i.stack.imgur.com/ryA44.png" rel="nofollow"><img src="http://i.stack.imgur.com/ryA44.png" alt="Picture of Pop up on browser"></a></p>
| <p>Solved.</p>
<p>Adding this will resolve and woulndt allow any such pop ups.</p>
<pre><code> chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications" : 2}
chrome_options.add_experimental_option("prefs",prefs)
#driver = webdriver.Chrome(chrome_options=chrome_options)
driver = webdriver.Chrome(r"C:\Users\jatin\Downloads\chromedriver_win32\chromedriver.exe",chrome_options=chrome_options)
</code></pre>
|
Swift FBSDK Get user country <p>I am currently implementing Facebook login for my app, and I am trying to fetch the following info from the profile:</p>
<p>first name,
last name,
gender,
and country.</p>
<p>However, I can only seem to fetch everything except the user country. I have tried to set my parameters to my FBSDKGraphRequest like this:</p>
<pre><code>let parameters = ["fields": "email, gender, user_location, id, first_name, last_name, picture.type(large)"]
</code></pre>
<p>as well as my readPermissions to: </p>
<pre><code>loginButton.readPermissions = ["public_profile", "email", "user_location", "user_friends", "user_education_history", "user_birthday"]
</code></pre>
<p>What am I doing wrong here? How can I obtain the country of the user?</p>
<p>Help is greatly appreciated!</p>
| <p>Your readPermissions <code>user_location</code> is correct but the parameter name for country/location is not <code>user_location</code>.<br> It is <code>location</code>. <br></p>
<pre><code>let parameters = ["fields": "id,location,name,first_name,last_name,picture.type(large),email,birthday,gender,bio,relationship_status"]
</code></pre>
<p>Make sure you have added a <strong>place</strong> in your Facebook account and made that <strong>public</strong> in which your are logging in and you will be done. Try with the same facebook account from which you have created the facebook app.</p>
<p>You can get your location with a warning message(as shown screenshot later below) for testing purposes. But before submitting your app to appstore, you need to go through the Login Review from facebook as <code>user_location</code> is not a pre-Approved permission.</p>
<blockquote>
<p><strong>For More Details go to Graph API Explorer</strong></p>
</blockquote>
<p>You can go to the <a href="https://developers.facebook.com/tools/explorer" rel="nofollow">Graph API Explorer</a> and try out with your app. Generate a token by clicking on <strong>Get Token</strong> and <strong>Get User Access Token</strong>. On clicking it will open the permission checkboxes. Keep <strong>user_location</strong> checked.</p>
<p><a href="https://i.stack.imgur.com/vnWJQ.png" rel="nofollow"><img src="https://i.stack.imgur.com/vnWJQ.png" alt="Graph Api Explorer Page"></a></p>
<p><a href="https://i.stack.imgur.com/SeLQL.png" rel="nofollow"><img src="https://i.stack.imgur.com/SeLQL.png" alt="enter image description here"></a></p>
<p>Next just click on Submit with the following <strong>Get</strong> Parameters. Make sure that the <strong>location</strong> parameter is there and you can see a JSON like this as shown.<br>There is a <strong>location</strong> dictionary with <strong>name</strong> key which consist of your country and city name.</p>
<pre><code>{
"id": "338058996547981",
"name": "Rajan Maheshwari",
"birthday": "04/29/1990",
"location": {
"id": "106517799384578",
"name": "New Delhi, India"
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/mH5N7.png" rel="nofollow"><img src="https://i.stack.imgur.com/mH5N7.png" alt="enter image description here"></a></p>
<p><strong>NOTE: - Also you have to make sure that you have entered a place in your Facebook profile and made that public.</strong></p>
<p><a href="https://i.stack.imgur.com/o9mEW.png" rel="nofollow"><img src="https://i.stack.imgur.com/o9mEW.png" alt="enter image description here"></a></p>
<p>When you will run the app with the permissions, you will get a Facebook authentication with a warning screen like this.</p>
<p><a href="https://i.stack.imgur.com/AonBE.png" rel="nofollow"><img src="https://i.stack.imgur.com/AonBE.png" alt="enter image description here"></a></p>
<p>It will ask for a <strong>Login Review</strong> as some of the permissions need review here. The basic permissions provided free by facebook which don't need any review are:- </p>
<p><a href="https://i.stack.imgur.com/tdtxu.png" rel="nofollow"><img src="https://i.stack.imgur.com/tdtxu.png" alt="enter image description here"></a></p>
<p>but for testing purposes you can get the location without any review. But before you will submit the iOS app to appstore, you need to pass the login review of Facebook in order to avoid that warning message and to fetch location of the user.</p>
|
How to count number of occurrences of a chracter in a string (list) <p>I'm trying to count the occurrence of each character for any given string input, the occurrences must be output in ascending order( includes numbers and exclamation marks)
I have this for my code so far, i am aware of the Counter function, but it does not output the answer in the format I'd like it to, and I do not know how to format Counter. Instead I'm trying to find away to use the count() to count each character. I've also seen the dictionary function , but I'd be hoping that there is a easier way to do it with count() </p>
<pre><code>from collections import Counter
sentence=input("Enter a sentence b'y: ")
lowercase=sentence.lower()
list1=list(lowercase)
list1.sort()
length=len(list1)
list2=list1.count(list1)
print(list2)
p=Counter(list1)
print(p)
</code></pre>
| <p>Just call <a href="https://docs.python.org/3/library/collections.html#collections.Counter.most_common" rel="nofollow"><code>.most_common</code></a> and reverse the output with <a href="https://docs.python.org/3/library/functions.html#reversed" rel="nofollow"><em>reversed</em></a> to get the output from least to most common:</p>
<pre><code>from collections import Counter
sentence= "foobar bar"
lowercase = sentence.lower()
for k, count in reversed(Counter(lowercase).most_common()):
print(k,count)
</code></pre>
|
Cannot convert NUMBER to SEQUENCE in Changefeed on SUM operation in RethinkDB <p>I am getting an error when listening on changes event while doing a SUM query, without the changes() method it works fine</p>
<p>What I expect this code to do is SUM each 'length' attribute on this table that matches the filter, and when there is a new item inserted in this table, SUM again and notify me. </p>
<pre><code>r.db('buckets')
.table("fs_files")
.filter({metadata: data})
.sum('length')
.changes()
.run(req._rdbConn, function(err, cursor) {
... notify me using socket.io (not important here)
});
</code></pre>
<p>What I get is</p>
<pre><code>name: 'ReqlQueryLogicError',
msg: 'Cannot convert NUMBER to SEQUENCE',
frames: [],
message: 'Cannot convert NUMBER to SEQUENCE in
</code></pre>
<p>Does anyone have a solution for this? Or is my logic wrong as the error message says?</p>
| <p>This will be possible only in version 2.4 as Daniel said <a href="https://github.com/rethinkdb/rethinkdb/issues/1118" rel="nofollow">here</a>.</p>
<p>Just for now you can try to use <code>fold</code>:</p>
<pre><code>r.db("buckets").table("fs_files").filter({metadata: data})('length')("num").changes({"includeInitial": true}).fold(0, function(acc, change) {
return acc.add(change("new_val").sub(change("old_val").default(0)))
}, {emit: function(prev, change, acc) {
return [acc]
}
}).run(con, function(err, cursor) {
if(!cursor)
return;
cursor.each(function(err, row) {
// here we go
})
});
</code></pre>
|
Is it possible to change the Menu in real time? <p>Depending on whatever arbitrary criteria I decide, is it possible to change the contents of the Menu (the triple-dot thing you click in the upper right, which drops down whatever settings you'd like to include).</p>
<p>Can this be done? Right now I don't know how to because I see lines like this:</p>
<pre><code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
</code></pre>
<p>and I don't know if I can "re-inflate" the menu in real time / change the options / etc.</p>
| <p>Thats the way I do it: </p>
<pre><code>@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(condition1){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_1, menu);
}else{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_2, menu);
}
return super.onPrepareOptionsMenu(menu);
}
</code></pre>
|
Best Way to Set Day to the First of the Month Using DateTime Without Inherent WithDayOfMonth Method <p>So, I'm trying to basically take 2 DateTime objects and set them to the first day of their respective months so that I can ultimately calculate the months between the two dates.</p>
<p>Example of the code:</p>
<pre><code>DateTime dt = new DateTime();
DateTime newDT = dt.withDayOfMonth(1);
</code></pre>
<p>And before anyone asks, the actual code coverts a Date object into a DateTime object which is used in another section of the code.</p>
<p>The issue is, when I do this in a unit test it seems to work just fine. However, when I try to test this using SOAP UI I can see in the course of debugging that I'm getting a runtime exception due to:</p>
<pre><code>method lookup failed for selector "withDayOfMonth" with signature "(I)Lorg/joda/time/DateTime;"
</code></pre>
<p>In the corresponding server.txt log file, I can see a stack trace which indicates a <strong>no such method</strong> has occured. </p>
<p>After further research, I've found that our app server currently employs an outdated version of the JodaTime jar (1.2.1), while my eclipse library contains the correct jar (1.6.2).</p>
<p>However, now the question becomes what's the best way to accomplish my goal here (to create a new DateTime object with the first day of the month set to 0) since I don't have access to the withDayOfMonth method provided by JodaTime?</p>
| <p>Calculate months from difference of the two month values. For example if <code>newDate</code> is 1st July 2016 and <code>oldDate</code> is 31st May 2016, <code>newDate.getMonth()</code> will return 7 and <code>oldDate.getMonth()</code> will return 5, and the difference will be rounded up as required.</p>
<pre><code>int months = newDate.getMonth() - oldDate.getMonth(); // 7 - 5 = 2
</code></pre>
|
how to write typescript definition file for this javascript library? <p>I need call the following javascript:</p>
<pre><code>var jslib = jslib || (function() {
var publicMethods = {
encrypt: function (algorithm, keyHandle, buffer) {
// implementation
}
};
return publicMethods;
})();
</code></pre>
<p>I am new to typescript, can you please share what the typescript definition will look like for the javascript above and invoke pattern?</p>
<p>Thanks in advance.</p>
| <p>I'm assuming the following directory structure</p>
<pre><code>âââ lib
â  âââ jslib.d.ts
â  âââ jslib.js
âââ src
  âââ t.ts
</code></pre>
<p>jslib.js</p>
<pre><code>var jslib = jslib || (function () {
var publicMethods = {
encript: function () {
return
}
};
return publicMethods;
})();
module.exports = jslib;
</code></pre>
<p>jslib.d.ts</p>
<pre><code>declare namespace jslib {
function encript(): void;
}
export = jslib;
</code></pre>
<p>t.ts</p>
<pre><code>import jslib = require('../lib/jslib');
jslib.encript();
</code></pre>
<p>Check with <code>node_modules/.bin/tsc --traceResolution</code></p>
<pre><code>======== Resolving module '../lib/jslib' from '/home/zjk/dev/webnote/ts1/src/t.ts'. ========
Explicitly specified module resolution kind: 'NodeJs'.
Loading module as file / folder, candidate module location '/home/zjk/dev/webnote/ts1/lib/jslib'.
File '/home/zjk/dev/webnote/ts1/lib/jslib.ts' does not exist.
File '/home/zjk/dev/webnote/ts1/lib/jslib.tsx' does not exist.
File '/home/zjk/dev/webnote/ts1/lib/jslib.d.ts' exist - use it as a name resolution result.
Resolving real path for '/home/zjk/dev/webnote/ts1/lib/jslib.d.ts', result '/home/zjk/dev/webnote/ts1/lib/jslib.d.ts'
======== Module name '../lib/jslib' was successfully resolved to '/home/zjk/dev/webnote/ts1/lib/jslib.d.ts'. ========
</code></pre>
<p>It is crucial to put <code>jslib.js</code> and <code>jslib.d.ts</code> in the same directory.</p>
|
Changing int array to char array <p>Hello all I'm having difficulty running some code under various circumstances. I have code that finds how many prime numbers there are, of all the numbers in an array, times how long it takes, and prints how many prime numbers there are. This all works fine, but then I need to run the same code, but with a char array. That is where the problems come in. Here is the code, with an array of ints:</p>
<pre><code>#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <stdio.h>
using namespace std;
static const int N = 1000;
int main()
{
int i, a[N];
clock_t start = clock();
for (i = 2; i < N; i++) a[i] = i;
for (i = 2; i < N; i++)
if (a[i])
for (int j = i; j*i < N; j++) a[i*j] = 0;
start = clock() - start;
int primes = 0;
for (i = 2; i < N; i++) {
if (a[i]) {
primes++;
cout << " " << i;
if (primes % 10 == 0)
cout << "\n";
}
}
printf("\nIt took %d clicks (%f seconds) to find all prime numbers.\n", start, ((float)start) / CLOCKS_PER_SEC);
cout << "The number of primes out of " << N << " integers is " << primes << endl;
return 0;
}
</code></pre>
<p>When I simply replace 'int' with "char" for the array, and set 'N' to something like 10, or 100 it works just fine, save for how the prime numbers look. Anything higher and nothing prints off. I know its not as simple as just changing where it says 'int' to 'char' but I am hopelessly lost on the subject. Doesnt help that I need to do this again, but changing the array to type bool (which doesnt make much sense to me either.)</p>
<p>Any kind of insight or simple solution would be wonderful. I will keep searching for something in the meantime. Thanks!</p>
| <p>The problem is that you're storing <code>i</code> into <code>a[i]</code>. When <code>a</code> is a <code>char</code> array, the maximum value of an element is <code>127</code> (if <code>char</code> defaults to <code>signed</code>) or <code>255</code> (if it's <code>unsigned</code>), assuming a typical system with 8-bit bytes. If it's signed, overflow results in implementation-defined behavior; if it's unsigned, overflow wraps around modulo <code>256</code>.</p>
<p>The only thing you care about is whether the value of the element is zero or non-zero, so there's no need to put different values in them. Just initialize them all to <code>1</code>.</p>
<pre><code>for (i = 2; i < N; i++) a[i] = 1;
</code></pre>
<p>This will also work when you change it to boolean.</p>
|
Plotting drc model in ggplot2; issue with seq( ) <p>My model does not continue towards the asymptotes when plotted in ggplot2, though it does in R base graphics. In ggplot2, it stops at certain points on the X axis (images included below), <strong>I am 90% certain this is related to <code>seq()</code>, data it posted at the bottom of this post</strong></p>
<p>I am using <code>predict()</code> to transform data from a drm (dose-response package) logit model. In the base graphics, the sigmoidal curve looks great, in ggplot2, not so much.<br>
<em>(I do not think you'll need it but just in case, data is included at bottom of this post)</em></p>
<pre><code>library(drc)
library(ggplot2)
</code></pre>
<p>fitting data to logit model</p>
<pre><code>mod1 <- drm(probability ~ (dose), weights = total, data = mydata1, type ="binomial", fct = LL.2())
plot(mod1,broken=FALSE,type="all",add=FALSE, col= "purple", xlim=c(0, 10000))
</code></pre>
<p><a href="http://i.stack.imgur.com/jefcW.jpg" rel="nofollow">Image of Base graphic 2-parameter logit</a></p>
<p>Extracting the data of the model using code from the author's demonstration (linked below), I have:</p>
<pre><code>newdata1 <-expand.grid(dose=exp(seq(log(0.5),log(100),length=200)))
pm1<- predict(mod1, newdata=newdata1,interval="confidence")
newdata1$p1 <-pm1[,1]
newdata1$pmin1 <-pm1[,2]
newdata1$pmax1 <- pm1[,3]
</code></pre>
<p>And finally the ggplot2 graphic.</p>
<pre><code>p1 <- ggplot(mydata1, aes(x=dose01,y=probability))+
geom_point()+
geom_ribbon(data=newdata1, aes(x=dose,y=p1,
ymin=pmin1,ymax=pmax1),alpha=0.2,color="blue",fill="pink") +
geom_step(data=newdata1, aes(x=dose,y=p1))+
coord_trans(x="log") + #creates logline for x axis
xlab("dose")+ylab("response")
</code></pre>
<p><a href="http://i.stack.imgur.com/HZt7I.jpg" rel="nofollow">Images 1&2 and 3&4 </a> show differences in my plot depending on seq.</p>
<p>When the following is used for <code>seq()</code>, the graphic gets pulled out past the data! <code>(seq(log(0.5),**log(10000)**,length=200)))</code> (images 1&2)</p>
<p>I don't understand <strong><code>seq()</code></strong> despite researching it. Would someone please <strong>help me understand what is going on with my plots?</strong></p>
<p>It appears that the first term in seq is defining the lower bound. but then what is the third term defining? You can see this in images 3&4 - The graphic is decent; I've somewhat obfuscated the issue, but it still doesn't continue towards infin. This is a slight issue because I will be co-plotting 8 logit models. </p>
<p>--
<strong>(I can't post more than two links, so bare with these titles)</strong></p>
<p>For anyone having trouble plotting drc/drm models with ggplot2, the following posts were very helpful: Search for
<strong>plotting-dose-response-curves-with-ggplot2-and-drc</strong><br>
and this title: <strong>plotting-dose-response-curves-with-ggplot2-and-drc</strong></p>
<p>I've followed the author of DRC's instructions, which can found in the supporting information of his article - Part of this code was used above. Article title: Dose-Response Analysis Using R, Christopher Ritz. PlosOne.</p>
<p><em>If this data is in an less than ideal format, let me know-</em></p>
<pre><code>> dput(mydata1)
structure(list(dose = c(25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L,
25L, 25L, 25L, 25L, 25L, 25L, 25L, 75L, 75L, 75L, 75L, 75L, 75L,
75L, 75L, 75L, 75L, 75L, 75L, 75L, 75L, 75L, 100L, 100L, 100L,
100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L,
100L, 150L, 150L, 150L, 150L, 150L, 150L, 150L, 150L, 150L, 150L,
150L, 150L, 150L, 150L, 150L, 200L, 200L, 200L, 200L, 200L, 200L,
200L, 200L, 200L, 200L, 200L, 200L, 200L, 200L, 200L), total = c(25L,
25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L,
25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L,
25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L,
25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L,
25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L,
25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L), affected = c(2L,
0L, 0L, 0L, 0L, 1L, 1L, 2L, 2L, 4L, 1L, 1L, 4L, 0L, 10L, 0L,
1L, 0L, 1L, 0L, 3L, 0L, 4L, 2L, 0L, 2L, 0L, 1L, 2L, 3L, 2L, 0L,
2L, 0L, 0L, 4L, 0L, 1L, 2L, 3L, 0L, 21L, 1L, 3L, 1L, 2L, 7L,
0L, 0L, 0L, 0L, 8L, 7L, 3L, 7L, 2L, 2L, 10L, 3L, 4L, 0L, 7L,
0L, 3L, 3L, 20L, 25L, 22L, 23L, 22L, 18L, 14L, 20L, 20L, 21L),
probability = c(0.08, 0, 0, 0, 0, 0.04, 0.04, 0.08, 0.08,
0.16, 0.04, 0.04, 0.16, 0, 0.4, 0, 0.04, 0, 0.04, 0, 0.12,
0, 0.16, 0.08, 0, 0.08, 0, 0.04, 0.08, 0.12, 0.08, 0, 0.08,
0, 0, 0.16, 0, 0.04, 0.08, 0.12, 0, 0.84, 0.04, 0.12, 0.04,
0.08, 0.28, 0, 0, 0, 0, 0.32, 0.28, 0.12, 0.28, 0.08, 0.08,
0.4, 0.12, 0.16, 0, 0.28, 0, 0.12, 0.12, 0.8, 1, 0.88, 0.92,
0.88, 0.72, 0.56, 0.8, 0.8, 0.84)), .Names = c("dose", "total",
"affected", "probability"), row.names = c(NA, -75L), class = "data.frame")
</code></pre>
| <p>This is a long comment. I think you mistook <code>dose</code> values to give <code>predict()</code> or <code>aes(x)</code> values.</p>
<pre><code>log10000 <- exp(seq(log(0.5), log(10000), length=200))
log1000 <- exp(seq(log(0.5), log(1000), length=200))
log10000df <- as.data.frame(cbind(dose = log10000, predict(mod1, data.frame(dose = log10000), interval="confidence")))
log1000df <- as.data.frame(cbind(dose = log1000, predict(mod1, data.frame(dose = log1000), interval="confidence")))
## a common part
p0 <- ggplot(mydata1, aes(x = dose, y = probability)) +
geom_point() + coord_trans(x="log") +
xlab("dose") + ylab("response") + xlim(0.5, 10001)
p10000 <- p0 + geom_line(data = log10000df, aes(x = dose, y = Prediction)) +
geom_ribbon(data = log10000df, aes(x = dose, y = Prediction, ymin = Lower, ymax = Upper),
alpha = 0.2, color = "blue", fill = "pink")
p1000 <- p0 + geom_line(data = log1000df, aes(x = dose, y = Prediction)) +
geom_ribbon(data = log1000df, aes(x = dose, y = Prediction, ymin = Lower, ymax = Upper),
alpha = 0.2, color = "blue", fill = "pink")
</code></pre>
<p><a href="https://i.stack.imgur.com/LcPTs.png" rel="nofollow"><img src="https://i.stack.imgur.com/LcPTs.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/xupVB.png" rel="nofollow"><img src="https://i.stack.imgur.com/xupVB.png" alt="enter image description here"></a></p>
|
swift share with function on completion <p>My app can share files with other apps, but the problem is that I need to delete the files after sharing them... I tried using the onCompletion function as below:</p>
<pre><code>let activityVC = UIActivityViewController(activityItems: objects, applicationActivities: nil)
view.present(activityVC, animated: true) {
try! FileManager.default.removeItem(at: targetURL)
}
</code></pre>
<p>The problem is that the onCompletion function executes after the action view disappears not after the whole process of sharing is finished, that's why if I delete the file and the sharing process is still ongoing it will be aborted.. an example is when using telegram for sharing; since telegram asks you to select a contact to send the file to, by that time the view has already disappeard (the function is executed and deleted the file before sharing it)...</p>
| <p>It's far too soon to do anything in the completion handler of presenting the controller.</p>
<p>Set the <code>completionWithItemsHandler</code> property of the <code>UIActivityViewController</code>. This will get called when the sharing process is complete.</p>
<pre><code>activityVC.completionWithItemsHandler = { (activityType: UIActivityType?, completed: Bool, returnedItems: [Any]?, error: Error?) -> Void in
if completed == true {
try! FileManager.default.removeItem(at: targetURL)
}
}
</code></pre>
|
Reading and analyzing string data for AI <p>I just wrote string reading and analyzing for a Jarvis AI that has been taught to remember certain phases.</p>
<p>My problem is that it has so many that the substrings within other phrases that are uncountable. I want to be able to say a certain phrase then for the AI to chart what I say after that phrase.</p>
<p>I want to fix two problems in this post.</p>
<h3>my problem</h3>
<p>i want to be able to Make my AI be able to tell the difference between when I say a sentence with <code>"this"</code> in it, and when I greet it with the greeting <code>"hi"</code></p>
<p>You can probably see why this is annoying, if it's not obvious enough, if I were to say "this is awesome"<code>it would see it as</code>"hi"`</p>
<p>Because "hi" is a substring of "this" which is in the sentence!</p>
<p>So what I'm thinking is can I say something like this (which is incorrect, I just want to give you an example)</p>
<pre><code>if esa [1] == "h" and esa in ("hi","hey"):
print ()
</code></pre>
<p>or </p>
<pre><code>if esa [0] == "h" and esa [1] == "i":
</code></pre>
<p>So what I want it to do is see if "h" is the first character in the string and if "i" is in the second, then work accordingly. This also happens with "hey" because <code>hey</code> is in "they"</p>
<p>can anyone help</p>
| <p>To attack your immediate problems ... NLP (natural language processing) generally processing the input with a lexicon (vocabulary), not string search. One popular tactic is to give each word or word family an index number, often simply the word's position (line number) in a dictionary file. The initial reading simply identifies each word; fancier applications also break down word families, so that "were" gets coded as "is / plural / past tense".</p>
<p>Regardless, you store your sentence as a string of word indices, such that "This is batman" might appear as [27086, 8334, 522] (FYI: I'm making up the index numbers). Now, when you test for the word "hi", you'll search for word 7930, and there's no conflict at all with 8334.</p>
<p>For the larger problem, see the comments we've given: NLP is a large field.</p>
|
Office 365 oAuth verify user is member of organization <p>I am building a web application for a client and logging in with Office 365 is a requirement for the client. I am having a difficult time deciphering what exactly I need to do to make it so that only users with an email address belonging to their Office 365 organization can authenticate with my app using oAuth. </p>
<p>Is there a way to do this? Or am I going to have to implement the AD 1.0 endpoints? Being able to pull the users' groups and other enterprise-related data would be great but for simplicity's sake, all I really need to do is verify that they are apart of an organization. </p>
<p>How would I do this using the AD 2.0 endpoints? </p>
| <p>The tenant id (<code>tid</code>) claim in the identity token would identify which organization (tenant) they belong to. But even easier than just checking the <code>tid</code> for every user would be to use the tenant-specific logon URL. So instead of the <code>/common/oauth2/v2.0/authorize</code> endpoint, use <code>/<tenantid>/oauth2/v2.0/authorize</code>.</p>
|
Avoid backreference replacement in php's preg_replace <p>Consider the below use of <code>preg_replace</code></p>
<pre><code>$str='{{description}}';
$repValue='$0.0 $00.00 $000.000 $1.1 $11.11 $111.111';
$field = 'description';
$pattern = '/{{'.$field.'}}/';
$str =preg_replace($pattern, $repValue, $str );
echo $str;
// Expected output: $0.0 $00.00 $000.000 $1.1 $11.11 $111.11
// Actual output: {{description}}.0 {{description}}.00 {{description}}0.000 .1 .11 1.111
</code></pre>
<h3>Here is a <a href="http://phpfiddle.org/main/code/dhxu-9k4r" rel="nofollow">phpFiddle showing the issue</a></h3>
<p>It's clear to me that the actual output is not as expected because <code>preg_replace</code> is viewing <code>$0, $0, $0, $1, $11, and $11</code> as back references for matched groups replacing <code>$0</code> with the full match and <code>$1 and $11</code> with an empty string since there are no capture groups 1 or 11.</p>
<p>How can I prevent <code>preg_replace</code> from treating prices in my replacement value as back references and attempting to fill them? </p>
<p>Note that <code>$repValue</code> is dynamic and it's content will not be know before the operation.</p>
| <p>Escape the dollar character before using a character translation (<code>strtr</code>):</p>
<pre><code>$repValue = strtr('$0.0 $00.00 $000.000 $1.1 $11.11 $111.111', ['$'=>'\$']);
</code></pre>
<p>For more complicated cases (with dollars and escaped dollars) you can do this kind of substitution <em>(totally waterproof this time)</em>:</p>
<pre><code>$str = strtr($str, ['%'=>'%%', '$'=>'$%', '\\'=>'\\%']);
$repValue = strtr($repValue, ['%'=>'%%', '$'=>'$%', '\\'=>'\\%']);
$pattern = '/{{' . strtr($field, ['%'=>'%%', '$'=>'$%', '\\'=>'\\%']) . '}}/';
$str = preg_replace($pattern, $repValue, $str );
echo strtr($str, ['%%'=>'%', '$%'=>'$', '\\%'=>'\\']);
</code></pre>
<p>Note: if <code>$field</code> contains only a literal string (not a subpattern), you don't need to use <code>preg_replace</code>. You can use <code>str_replace</code> instead and in this case you don't have to substitute anything.</p>
|
How to use counters and zip functions with a list of lists in Python? <p>I have a list of lists :</p>
<pre><code>results = [['TTTT', 'CCCZ'], ['ATTA', 'CZZC']]
</code></pre>
<p>I create a counter that stores number number of characters in each element in each list, only if the characters are ATGC [NOT Z]</p>
<pre><code>The desired output is [[4,3],[4,2]]
</code></pre>
<p>**</p>
<p>Code:</p>
<pre><code>counters = [Counter(sub_list) for sub_list in results]
nn =[]
d = []
for counter in counters:
atgc_count = sum((val for key, val in counter.items() if key in "ATGC"))
nn.append(atgc_count)
d = [i - 1 for i in nn]
correctionfactor = [float(b) / float(m) for b,m in zip(nn, d)]
print nn
print correctionfactor
"Failed" Output:
[0, 0]
<closed file 'c:/test/zzz.txt', mode 'r' at 0x02B46078>
Desired Output
nn = [[4,3],[4,2]]
correctionfactor = [[1.33, 1.5],[1.33,2]]
</code></pre>
<p>**</p>
<p>And then I calculate frequency of each character (pi), square it and then sum (and then I calculate het = 1 - sum). </p>
<pre><code>The desired output [[1,2],[1,2]] #NOTE: This is NOT the real values of expected output. I just need the real values to be in this format.
</code></pre>
<p>**
Code</p>
<pre><code>list_of_hets = []
for idx, element in enumerate(sample):
count_dict = {}
square_dict = {}
for base in list(element):
if base in count_dict:
count_dict[base] += 1
else:
count_dict[base] = 1
for allele in count_dict:
square_freq = (count_dict[allele] / float(nn[idx]))**2
square_dict[allele] = square_freq
pf = 0.0
for i in square_dict:
pf += square_dict[i] # pf --> pi^2 + pj^2...pn^2
het = 1-pf
list_of_hets.append(het)
print list_of_hets
"Failed" OUTPUT:
[-0.0, -0.0]
</code></pre>
<p>**
I need to multiply every elements in list_of_hets by correction factor</p>
<pre><code>h = [float(n) * float(p) for n,p in zip(correction factor,list_of_hets)
With the values given above:
h = [[1.33, 1.5],[1.33,2]] #correctionfactor multiplied by list_of_hets
</code></pre>
<p>Finally, I need to find the average value of every element in h and store it in a new list.</p>
<pre><code>The desired output should read as [1.33, 1.75].
</code></pre>
<p>I tried following this example (<a href="http://stackoverflow.com/questions/13783315/sum-of-list-of-lists-returns-sum-list">Sum of list of lists; returns sum list</a>). </p>
<pre><code>hs = [mean(i) for i in zip(*h)]
</code></pre>
<p>But I get the following error "TypeError: zip argument #1 must support iteration"</p>
<p>I understand that correcting the code at the first step may solve it. I tried to manually input the "desired outputs" and run the rest of the code, but no luck.</p>
| <p>The first part can be done like this:</p>
<pre><code>BASES = {'A', 'C', 'G', 'T'}
results = [['TTTT', 'CCCZ'], ['ATTA', 'CZZC']]
counts = [[sum(c in BASES for c in s) for s in pair] for pair in results]
>>> counts
[[4, 3], [4, 2]]
</code></pre>
<p>Once you have the counts, the correction factor can also be calculated with a list comprehension:</p>
<pre><code>correction_factors = [[i/float(i-1) for i in pair] for pair in counts]
>>> correction_factors
[[1.3333333333333333, 1.5], [1.3333333333333333, 2.0]]
</code></pre>
<p>but you do need to be careful of the case where a count is 1 as this will lead to a division by zero error. I'm not sure how you should handle that... would a value of <code>1</code> be appropriate?</p>
<pre><code>correction_factors = [[i/float(i-1) if i-1 else 1 for i in pair] for pair in counts]
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.