input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
MT4 Trade Panel - Issues <p>My English so limited, so I can't write a lot details. But I am trying to get "Hover" mouse hover effect. So which Object Functions help me for that.
You can see that effect below image.</p>
<p><a href="http://i.stack.imgur.com/Ai8rw.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ai8rw.png" alt="when click "Sell or Buy""></a></p>
<p>Thanks</p>
| <h2><sub>a short version:</sub> None</h2>
<hr>
<h2><a href="http://stackoverflow.com/a/39918282/3666197">The Full Story:</a></h2>
<p>In spite of a minimalistic composition of the initial Question text, one may realise that any automation, intended to work on top of the MetaTrader Terminal 4 MMI-Add-On elements, that are not integral part of the Chart's GUI-Objects, is not directly accessible from the <code>MQL4</code>-code-base.</p>
<p>Neither in a passive-observer role ( just reading some of the MMI-Add-On element's values ) nor in an active-agent/actor mode ( trying to click / type-in a value / etc ).</p>
<p>This said, one may investigate other technologies to handle the intended functionalities via some O/S-controlled resources, but this direction goes beyond the reach of the <code>MQL4</code>-language contructors.</p>
<p>For further details do not hesitate to click-through to follow the Headline URL.</p>
|
Uploading Android library to Bintray - userOrg parameter is ignored <p>I am trying to upload an Android library to Bintray using this guide:
<a href="https://inthecheesefactory.com/blog/how-to-upload-library-to-jcenter-maven-central-as-dependency/en" rel="nofollow">https://inthecheesefactory.com/blog/how-to-upload-library-to-jcenter-maven-central-as-dependency/en</a></p>
<p>Everything works fine until I try to run bintrayUpload, when I get the following error:</p>
<p>Execution failed for task ':MAS:bintrayUpload'.</p>
<blockquote>
<p>Could not create package 'user/maven/my-repo': HTTP/1.1 404 Not Found [message:Repo 'maven' was not found]</p>
</blockquote>
<p>I think the problem is that the repository is owned by the organisation on Bintray. But it's looking for it under the user.
ie. user/maven/my-repo should be organisation/maven/my-repo.</p>
<p>My local.properties looks like this:</p>
<pre><code>...
bintray.userOrg=organisation
bintray.user=user
bintray.apikey=key
bintray.gpg.password=password
...
</code></pre>
<p>My build.gradle for the library module looks like this:</p>
<pre><code>/*
* Copyright (c) 2016 CA. All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
*/
//noinspection GradleCompatible
// In order to build messaging using gradle 2 environment variables must be exportedd
// 1. prefix - this is the aar prefix, for example 'android'
// 2. versionName - this is the v.r.m formatted version name as used in the AndroidManifest.xml.
// For example, 1.1.0
plugins {
id "com.jfrog.bintray" version "1.7"
id "com.github.dcendents.android-maven" version "1.5"
}
apply plugin: 'com.android.library'
apply plugin: 'maven-publish'
ext {
bintrayRepo = 'maven'
bintrayName = 'mobile-app-services'
publishedGroupId = 'com.ca'
libraryName = 'MobileAppServices'
artifact = 'mobile-app-services'
libraryDescription = 'The Android Mobile SDK gives developers simple and secure access to the services of CA Mobile API Gateway and CA Mobile App Services. '
siteUrl = 'https://github.com/CAAPIM/Android-MAS-SDK'
gitUrl = 'https://github.com/CAAPIM/Android-MAS-SDK.git'
libraryVersion = '3.2.00'
developerId = 'devId'
developerName = 'Full Name'
developerEmail = 'user@email.com'
licenseName = 'The MIT License (MIT)'
licenseUrl = 'license.com'
allLicenses = ["MIT"]
}
println '------> Executing mas library build.gradle'
repositories {
mavenCentral()
flatDir {
dirs 'libs'
}
}
android {
compileSdkVersion 24
buildToolsVersion '24.0.2'
defaultConfig {
minSdkVersion 19
targetSdkVersion 24
versionCode 12
versionName "1.2"
}
lintOptions {
abortOnError false
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
task javadoc(type: Javadoc) {
source = android.sourceSets.main.java.srcDirs
println "Source: $source"
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
println "Classpath: $source"
options.memberLevel = org.gradle.external.javadoc.JavadocMemberLevel.PROTECTED
destinationDir = file("../docs/mas_javadoc/")
failOnError false
include '**/*MAS*.java'
include '**/Device.java'
include '**/ScimUser.java'
exclude '**/MASTransformable.java'
exclude '**/MASResultReceiver.java'
exclude '**/MASWebServiceClient.java'
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:24.2.1'
compile project(':MAG')
}
apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/installv1.gradle'
apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/bintrayv1.gradle'
</code></pre>
| <p>When uploading context to a Repository that is owned by an Organization, you have to comply with the Bintray REST API convention by using the following path: <strong>OrganizationName/RepoName</strong> and not <strong>UserName/RepoName</strong>.</p>
<p>I do not know what is the using of the 'maven' word in the path you wrote above.</p>
<p>For the case you have above the following Bintray REST API links can be helpful:</p>
<ul>
<li><p><a href="https://bintray.com/docs/api/#_create_package" rel="nofollow">create new Package</a> </p></li>
<li><p><a href="https://bintray.com/docs/api/#_maven_upload" rel="nofollow">upload maven content</a></p></li>
<li><p><a href="https://bintray.com/docs/api/#_upload_content" rel="nofollow">upload any content </a></p></li>
</ul>
<p>In the situation above The <strong>:subject</strong> refers to the Organization name (and not the Username). In any case that the Repository is under the user the <strong>:subject</strong> is referred to the Username.</p>
<p>For more details please follow the full <a href="https://bintray.com/docs/api/" rel="nofollow">Bintray REST API documentation</a>.</p>
<p>Another way to upload your file is by using the <a href="https://bintray.com" rel="nofollow">Bintray UI</a> which can be much more visible to understand the structure of your Repositories, Packages, Versions and Artifacts.</p>
|
Support for user certificate authentification in Azure AD <p>I'am searching for public/private key-based authentication for users with Azure-ActiveDirectory but can't find any hints in <a href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-authentication-scenarios/" rel="nofollow">Azure AD Authentification Scenarios</a>. Every user should bring his own key pair. Any suggestions how to achieve it?</p>
| <p>Azure AD supports OAuth 2.0 to authorize the third-party apps and the OAuth 2.0 support to acquire the token using the appâs client credential. </p>
<p>There are two ways to acquire the token for the client credential flow.
First is that using the keys which generated by the Azure portal like figure below:
<a href="http://i.stack.imgur.com/DNeL1.png" rel="nofollow"><img src="http://i.stack.imgur.com/DNeL1.png" alt="enter image description here"></a></p>
<p>And here is a figure about token request using the key(client_secret):
<a href="http://i.stack.imgur.com/8XYLk.png" rel="nofollow"><img src="http://i.stack.imgur.com/8XYLk.png" alt="enter image description here"></a></p>
<p>Another way is using the cert. Technical speaking, the cert is a pair of public/private key. We will store the information of public key with the app. When we require to prove we are the owner of the third-party apps, we need to sign the message with the private key and Azure AD with verify the messages with public key. </p>
<p>To store the cert information with apps, we need to change the manifest of app. Here is the detail steps to use a self-signed certificate from <a href="https://msdn.microsoft.com/en-us/office-365/get-started-with-office-365-management-apis?f=255&MSPPError=-2147217396#requesting-an-access-token-by-using-client-credentials" rel="nofollow">here</a>:</p>
<p>1.Generate a self-signed certificate:</p>
<pre class="lang-none prettyprint-override"><code>makecert -r -pe -n "CN=MyCompanyName MyAppName Cert" -b 03/15/2015 -e 03/15/2017 -ss my -len 2048
</code></pre>
<p>2.Open the Certificates MMC snap-in and connect to your user account.</p>
<p>3.Find the new certificate in the Personal folder and export the public key to a base64-encoded file (for example, mycompanyname.cer). Your application will use this certificate to communicate with AAD, so make sure you retain access to the private key as well.</p>
<p>Note You can use Windows PowerShell to extract the thumbprint and base64-encoded public key. Other platforms provide similar tools to retrieve properties of certificates.</p>
<p>4.From the Windows PowerShell prompt, type and run the following:</p>
<pre class="lang-powershell prettyprint-override"><code>$cer = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cer.Import("mycer.cer")
$bin = $cer.GetRawCertData()
$base64Value = [System.Convert]::ToBase64String($bin)
$bin = $cer.GetCertHash()
$base64Thumbprint = [System.Convert]::ToBase64String($bin)
$keyid = [System.Guid]::NewGuid().ToString()
</code></pre>
<p>5.Store the values for $base64Thumbprint, $base64Value and $keyid, to be used when you update your application manifest in the next set of steps.
Using the values extracted from the certificate and the generated key ID, you must now update your application manifest in Azure AD.</p>
<p>6.In the Azure Management Portal, select your application and choose Configure in the top menu.</p>
<p>7.In the command bar, click Manage manifest and select Download Manifest.</p>
<p><a href="http://i.stack.imgur.com/vX7y1.png" rel="nofollow"><img src="http://i.stack.imgur.com/vX7y1.png" alt="enter image description here"></a></p>
<p>8.Open the downloaded manifest for editing and replace the empty KeyCredentials property with the following JSON:</p>
<pre class="lang-js prettyprint-override"><code>"keyCredentials": [
{
"customKeyIdentifier": "$base64Thumbprint_from_above",
"keyId": "$keyid_from_above",
"type": "AsymmetricX509Cert",
"usage": "Verify",
"value": "$base64Value_from_above"
}
],
</code></pre>
<p>9.Save your changes and upload the updated manifest by clicking Manage manifest in the command bar, selectingUpload manifest, browsing to your updated manifest file, and then selecting it.</p>
<p>And below is the figure about token request using the cert:
<a href="http://i.stack.imgur.com/cyvj1.png" rel="nofollow"><img src="http://i.stack.imgur.com/cyvj1.png" alt="enter image description here"></a></p>
<p>In the article above, it generate the client_assertion from scratch. We can also use the ADAL library to help us and authenticate for a daemon apps:</p>
<pre class="lang-cs prettyprint-override"><code>string authority = $"https://login.microsoftonline.com/{tenant}";
var thumbprint="";
X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, thumbprint, false);
X509Certificate2 cert = fcollection[0];
var certCred = new ClientAssertionCertificate(clientId, cert);
var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority);
AuthenticationResult result = null;
try
{
result = await authContext.AcquireTokenAsync(resource, certCred);
}
catch (Exception ex)
{
}
return result.AccessToken;
</code></pre>
<p>And if you want to use the cert to authorize for the OAuth2.0 code grant flow, you also can refer the code sample <a href="https://github.com/Azure-Samples/active-directory-dotnet-graphapi-web.git" rel="nofollow">here</a>.</p>
|
Mercurial and BitBucket, "abort: repository default-push not found!" error message <p>I've some code on my laptop I would like to upload through Mercurial on my BitBucket repository.
I'm using a Linux CentOS 6 machine.</p>
<p>The problem is that if I type <code>$hg push</code>, I get the following error message:</p>
<pre><code>pushing to default-push
abort: repository default-push not found!
</code></pre>
<p>What should I do?</p>
<p>Thanks</p>
| <p>Mercurial doesn't know where you want to push to. Mercurial first looks for the destination in the push command (which could be either a repo on the filesystem, or a remote hg server):</p>
<p><code>hg push remoterepo</code></p>
<p>If it doesn't find a destination in the command, it will fall back on the defaults.</p>
<p>Normally, assuming this repository was cloned, the hgrc file (in .hg/) will indicate the default repository to be used.</p>
<p>However this assumes that the repository was created by cloning an existing repo.</p>
<p>If not, you can edit .hg\hgrc and add the default destination eg:</p>
<pre><code>[paths]
default-push=http://yourserver/
</code></pre>
|
setOnclickListener(this) ERROR <p>When I try to call setOnClickListener(this); 'this' gets an error. I have tried to declare it as other things but that didn't work. I am only trying to make multiple onClick events. </p>
<pre><code>import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageButton;
import android.view.View.OnClickListener;
import android.view.View;
public class MainActivity extends Activity {
ImageButton button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton one = (ImageButton) findViewById(R.id.img1);
one.setOnClickListener(this);<-error
ImageButton two = (ImageButton) findViewById(R.id.img1);
one.setOnClickListener(this);<-error
ImageButton three = (ImageButton) findViewById(R.id.img2);
two.setOnClickListener(this);<-error
}
public OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.img1:
button.setBackgroundResource(R.mipmap.checkmark);
break;
case R.id.img2:
button.setBackgroundResource(R.mipmap.checkmark);
break;
case R.id.img3:
button.setBackgroundResource(R.mipmap.checkmark);
break;
}
}
};
}
</code></pre>
| <p>Instead of <code>this</code>, reference your already created <code>onClickListener</code> class member. Also you have a bug in your 2nd and 3rd imagebutton where it is not getting any clicklistener or targeting the wrong resource id, here is all the fixes</p>
<pre><code>@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton one = (ImageButton) findViewById(R.id.img1);
one.setOnClickListener(onClickListener);
ImageButton two = (ImageButton) findViewById(R.id.img2);
two.setOnClickListener(onClickListener);
ImageButton three = (ImageButton) findViewById(R.id.img3);
three.setOnClickListener(onClickListener);
}
</code></pre>
|
Simple example of using FeaturesDlg in WIX <p>The only documentation for the FeaturesDlg I can find on the WIX site is a brief two-line description. I'm finding lots of esoteric, advanced samples of how to attempt to do difficult things, customizations, etc. I just want to know how to use it in the most simple, basic, easy way. I have four features, and I want the user to be able to choose which of them to install. That's all. Can anyone point me to a simple example? Do I need to have a Publish element and manually control the entire sequence of dialogs in order to use the FeaturesDlg?</p>
| <p>Use the <code>WixUI_FeatureTree</code> dialog set. See <a href="http://wixtoolset.org/documentation/manual/v3/wixui/wixui_dialog_library.html" rel="nofollow">Using Built-in WixUI Dialog Sets</a>.</p>
|
Unable to start apache <p>I've trying to start httpd 2.4 on OSX with SSL installed from</p>
<pre><code>brew install httpd24 --with-privileged-ports
</code></pre>
<p>and I'm trying to start it with an SSL certificate generated from letsencrypt. However, it's not starting. I've upped the log levels to see if they help. The error.log has</p>
<pre><code>[Thu Oct 06 21:33:18.256058 2016] [ssl:trace3] [pid 39588] ssl_engine_init.c(506): Creating new SSL context (protocols: TLSv1, TLSv1.1, TLSv1.2)
[Thu Oct 06 21:33:18.256159 2016] [ssl:trace1] [pid 39588] ssl_engine_init.c(768): Configuring permitted SSL ciphers [ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:!aNULL:!eNULL:!EXP]
[Thu Oct 06 21:33:18.256340 2016] [ssl:debug] [pid 39588] ssl_engine_init.c(949): AH01904: Configuring server certificate chain (1 CA certificate)
[Thu Oct 06 21:33:18.256345 2016] [ssl:debug] [pid 39588] ssl_engine_init.c(412): AH01893: Configuring TLS extension handling
[Thu Oct 06 21:33:18.256482 2016] [ssl:error] [pid 39588] AH02566: Unable to retrieve certificate www.myserver.com:443:0
</code></pre>
<p>and the ssl_engine.log has</p>
<pre><code>[Thu Oct 06 21:33:18.256029 2016] [ssl:trace2] [pid 39588] ssl_engine_rand.c(125): Init: Seeding PRNG with 144 bytes of entropy
[Thu Oct 06 21:33:18.256050 2016] [ssl:info] [pid 39588] AH01887: Init: Initializing (virtual) servers for SSL
AH00016: Configuration Failed
</code></pre>
<p>I've got openssl installed via homebrew as well as the openssl on OSX (OpenSSL 0.9.8zh 14 Jan 2016).
and the output from the libexec in httpd24/2.4.23_2</p>
<pre><code>otool -L mod_ssl.so
mod_ssl.so:
/usr/local/opt/openssl/lib/libssl.1.0.0.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1238.0.0)
</code></pre>
<p>which I've checked is there and is in 1.0.2j version.</p>
<p>The output from </p>
<pre><code>sudo apachectl configtest
Syntax OK
</code></pre>
<p>Any ideas what I've done wrong?</p>
| <p>I got it to restart in the end.</p>
<p>Somehow I had commented out the</p>
<pre><code>Listen 443
</code></pre>
<p>so it wasn't listening on 443, which I guess was what it was trying to tell me with</p>
<pre><code>Thu Oct 06 21:33:18.256482 2016] [ssl:error] [pid 39588] AH02566: Unable to retrieve certificate www.myserver.com:443:0
</code></pre>
|
How to concat two javascript variables and regex expression <p>I want to be able to concat two variables with a regular expression in the middle.</p>
<p>e.g.</p>
<pre><code>var t1 = "Test1"
var t2 = "Test2"
var re = new RegEx(t1 + "/.*/" + t2);
</code></pre>
<p>So the result I want is an expression that matches this..</p>
<pre><code>"Test1 this works Test2"
</code></pre>
<p>How do I get a result where I am able to match any text that has Test1 and Test2 on the ends?</p>
| <p>Try this (I use <a href="/questions/tagged/nodejs" class="post-tag" title="show questions tagged 'nodejs'" rel="tag">nodejs</a>):</p>
<pre><code>> var t1 = "Test1"
> var t2 = "Test2"
> var re = new RegExp('^' + t1 + '.*' + t2 + '$')
> re
/^Test1.*Test2$/
> re.test("Test1 this works Test2")
true
</code></pre>
<h3>Note</h3>
<ul>
<li><code>.*</code> as stated in comments, this means <em>any character</em> repeated from 0 to ~</li>
<li>the <em>slashes</em> are automagically added when calling the <code>RegExp</code> constructor, but you can't have nested unprotected <em>slashes</em> delimiters</li>
<li>to ensure <code>Test1</code> is at the beginning, i put <code>^</code> <em>anchor</em>, and for <code>Test2</code> at the end, I added <code>$</code> <em>anchor</em></li>
<li>the <em>regex</em> constructor is not <code>ReGex</code> but <code>RegExp</code> (note the trailing <code>p</code>)</li>
</ul>
|
How to add a Angular 2 component to an Angular 1 directive written in Coffeescript? (with webpack) <p>I have a case where I am am working in an Angular application written in coffee-script. I am trying to embed a new component in an existing ng1 directive written in coffee. According to the <a href="https://angular.io/docs/ts/latest/guide/upgrade.html" rel="nofollow">documentation</a> I should just have to...</p>
<p>1.) Rename file to .ts
2.) Add the following (ish)...</p>
<pre><code>import { HeroDetailComponent } from './hero-detail.component';
/* . . . */
angular.module('heroApp', [])
.directive('heroDetail', upgradeAdapter.downgradeNg2Component(HeroDetailComponent));
</code></pre>
<p>The problem is I am in coffeescript so I can't just do that. So I tried adding that in back ticks (to make it clear JS) like this...</p>
<pre><code>`import { HeroDetailComponent } from '../../../ng2/spinner/spinner.component';`
upgradeAdapter.downgradeNg2Component(HeroDetailComponent));
</code></pre>
<p>Then I change my .coffee loader to include </p>
<pre><code>{
test: /\.coffee$/,
loaders: ["coffee-loader", "coffee-import", "ts"]
},
</code></pre>
<p>But this throws a bunch of errors transpiling. Is there an easier way than transpiling all of the files and changing the extension? This would help so I can still merge.</p>
| <p>There were a few things wrong with my code but the real problem was the way coffee script requires imports. I changed it to something like this...</p>
<pre><code>{ NgSpinnerComponent } = require '../../../ng2/upgrade.adapter';
...
module.directive("ngSpinner", NgSpinnerComponent)
</code></pre>
<p>Where update adapter is...</p>
<pre><code>import { UpgradeAdapter } from '@angular/upgrade';
import { MyModule } from './my.module';
import { SpinnerComponent } from './spinner/spinner.component'
const upgradeAdapter = new UpgradeAdapter(MyModule);
var NgSpinnerComponent = upgradeAdapter.downgradeNg2Component( SpinnerComponent );
export {upgradeAdapter, NgSpinnerComponent}
</code></pre>
|
Reference a public static class in the global namespace in another assembly <p>In C#, is there a way to access a public static class in the global namespace in assembly A from assembly B (assuming assembly B references assembly A), <strong>when assembly B has public static class in the global namespace that has the same name</strong>? For example in <code>Bar.cs</code> in assembly A:</p>
<pre><code>using System.Diagnostics;
// NOTE: No namespace declared here - this is in the global:: ns
public static class Bar
{
public static void DoSomethingSilly()
{
Debug.WriteLine("I'm silly!");
}
}
</code></pre>
<p>How could I use this in <code>Bar.cs</code> in assembly B?</p>
<pre><code>public static class Bar
{
public static void DoSomethingSilly()
{
// call Bar.DoSomethingSilly() from assembly A here
}
}
</code></pre>
<p>I tried things like <code>global::Bar.DoSomethingSilly()</code>, which doesn't work in assembly B (it just gets me the reference back to assembly B). </p>
<p>I also know I could use reflection to get at it (something like <code>Assembly.GetType()</code>), but I'm more wondering if there's some native C# syntax for it. In the end I added a namespace around the code in assembly A, which I own and which was only in the global namespace because it was generated by another tool - adding the namespace didn't cause any problems, but I'm curious if there's syntax to allow this kind of referencing.</p>
| <p>Thanks to @Jon Skeet for this direction - extern alias is what can make this work. On the properties for the reference to the assembly, add an alias (for example <code>assemblyA</code>, or in the screen shot taken from <a href="https://blogs.msdn.microsoft.com/ansonh/2006/09/27/extern-alias-walkthrough/" rel="nofollow">here</a> <code>FooVersion1</code>):</p>
<p><a href="http://i.stack.imgur.com/ABWfF.png" rel="nofollow"><img src="http://i.stack.imgur.com/ABWfF.png" alt="property window example"></a></p>
<p>, and at the top of the .cs file add:</p>
<pre><code>extern alias assemblyA;
</code></pre>
<p>which will then allow either:</p>
<pre><code>assemblyA::Foo.DoSomethingSilly();
assemblyA.Foo.DoSomethingSilly();
</code></pre>
<p>I still went for adding a namespace to the generated code - it's more straightforward and avoids polluting the global namespace.</p>
|
How to one-hot-encode factor variables with data.table? <p>For those unfamiliar, one-hot encoding simply refers to converting a column of categories (i.e. a factor) into multiple columns of binary indicator variables where each new column corresponds to one of the classes of the original column. This example will explain it better:</p>
<pre><code>dt <- data.table(
ID=1:5,
Color=factor(c("green", "red", "red", "blue", "green"), levels=c("blue", "green", "red", "purple")),
Shape=factor(c("square", "triangle", "square", "triangle", "cirlce"))
)
dt
ID Color Shape
1: 1 green square
2: 2 red triangle
3: 3 red square
4: 4 blue triangle
5: 5 green cirlce
# one hot encode the colors
color.binarized <- dcast(dt[, list(V1=1, ID, Color)], ID ~ Color, fun=sum, value.var="V1", drop=c(TRUE, FALSE))
# Prepend Color_ in front of each one-hot-encoded feature
setnames(color.binarized, setdiff(colnames(color.binarized), "ID"), paste0("Color_", setdiff(colnames(color.binarized), "ID")))
# one hot encode the shapes
shape.binarized <- dcast(dt[, list(V1=1, ID, Shape)], ID ~ Shape, fun=sum, value.var="V1", drop=c(TRUE, FALSE))
# Prepend Shape_ in front of each one-hot-encoded feature
setnames(shape.binarized, setdiff(colnames(shape.binarized), "ID"), paste0("Shape_", setdiff(colnames(shape.binarized), "ID")))
# Join one-hot tables with original dataset
dt <- dt[color.binarized, on="ID"]
dt <- dt[shape.binarized, on="ID"]
dt
ID Color Shape Color_blue Color_green Color_red Color_purple Shape_cirlce Shape_square Shape_triangle
1: 1 green square 0 1 0 0 0 1 0
2: 2 red triangle 0 0 1 0 0 0 1
3: 3 red square 0 0 1 0 0 1 0
4: 4 blue triangle 1 0 0 0 0 0 1
5: 5 green cirlce 0 1 0 0 1 0 0
</code></pre>
<p>This is something I do a lot, and as you can see it's pretty tedious (especially when my data has many factor columns). Is there an easier way to do this with data.table? In particular, I assumed dcast would allow me to one-hot-encode multiple columns at once, when I try doing something like</p>
<pre><code>dcast(dt[, list(V1=1, ID, Color, Shape)], ID ~ Color + Shape, fun=sum, value.var="V1", drop=c(TRUE, FALSE))
</code></pre>
<p>I get column combinations</p>
<pre><code> ID blue_cirlce blue_square blue_triangle green_cirlce green_square green_triangle red_cirlce red_square red_triangle purple_cirlce purple_square purple_triangle
1: 1 0 0 0 0 1 0 0 0 0 0 0 0
2: 2 0 0 0 0 0 0 0 0 1 0 0 0
3: 3 0 0 0 0 0 0 0 1 0 0 0 0
4: 4 0 0 1 0 0 0 0 0 0 0 0 0
5: 5 0 0 0 1 0 0 0 0 0 0 0 0
</code></pre>
| <p>Using <code>model.matrix</code>:</p>
<pre><code>> cbind(dt[, .(ID)], model.matrix(~ Color + Shape, dt))
ID (Intercept) Colorgreen Colorred Colorpurple Shapesquare Shapetriangle
1: 1 1 1 0 0 1 0
2: 2 1 0 1 0 0 1
3: 3 1 0 1 0 1 0
4: 4 1 0 0 0 0 1
5: 5 1 1 0 0 0 0
</code></pre>
<p>This makes the most sense if you're doing modelling.</p>
<p>If you want to suppress the intercept (and restore the aliased column for the 1st variable):</p>
<pre><code>> cbind(dt[, .(ID)], model.matrix(~ Color + Shape - 1, dt))
ID Colorblue Colorgreen Colorred Colorpurple Shapesquare Shapetriangle
1: 1 0 1 0 0 1 0
2: 2 0 0 1 0 0 1
3: 3 0 0 1 0 1 0
4: 4 1 0 0 0 0 1
5: 5 0 1 0 0 0 0
</code></pre>
|
touch up inside (@IBAction) does not work with UIButton subclass <p>I created a subclass of <code>UIButton</code>:</p>
<pre><code>import UIKit
@IBDesignable
class CheckboxButton: UIButton {
@IBInspectable var checkboxBackgroundColor: UIColor = Project.Color.baseGray
@IBInspectable var textColor: UIColor = Project.Color.mainDarkText
@IBInspectable var checkboxHighlightedBackgroundColor: UIColor = Project.Color.main
@IBInspectable var highlightedTextColor: UIColor = Project.Color.mainBrightText
// MARK: - Properties
var isChecked: Bool = false {
didSet {
changeState()
}
}
// MARK: - Overrides
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
if isChecked {
isChecked = false
} else {
isChecked = true
}
return false
}
override func prepareForInterfaceBuilder() {
changeState()
}
// MARK: - @IBActions
// MARK: - Functions
private func setupView() {
isUserInteractionEnabled = true
changeState()
}
private func changeState() {
if isChecked {
backgroundColor = checkboxHighlightedBackgroundColor
self.setTitleColor(highlightedTextColor, for: .normal)
} else {
backgroundColor = checkboxBackgroundColor
self.setTitleColor(textColor, for: .normal)
}
}
}
</code></pre>
<p>Now I added a button inside the storyboard and gave it the class <code>CheckboxButton</code>. Everything works. Then I added an <code>IBAction</code> like this:</p>
<pre><code>@IBAction func pointBtnTapped(_ sender: CheckboxButton) {
print("tapped")
selectButton(withNumber: sender.tag)
}
</code></pre>
<p>But this doesn't work (nothing prints out). It works with a normal button, but not if the button is the subclass <code>CheckboxButton</code>. Do you have any ideas?</p>
<p>Edit: screenshots
<a href="https://www.dropbox.com/s/ewicc349ag9l6y2/Screenshot%202016-10-06%2023.41.39.png?dl=0" rel="nofollow">https://www.dropbox.com/s/ewicc349ag9l6y2/Screenshot%202016-10-06%2023.41.39.png?dl=0</a></p>
<p><a href="https://www.dropbox.com/s/vxevzscueproivc/Screenshot%202016-10-06%2023.42.33.png?dl=0" rel="nofollow">https://www.dropbox.com/s/vxevzscueproivc/Screenshot%202016-10-06%2023.42.33.png?dl=0</a>
(couldn't embed them here. Don't know why)</p>
<p>Thank you!</p>
| <p>You broke <code>UIButton</code> by overriding <code>beginTracking()</code> and always returning false. This brainwashes the button into thinking it's never being clicked.</p>
<p>What was your intent there? In any case, return <code>true</code> there and your code will fire the <code>@IBAction</code>.</p>
<p>EDIT: You're overthinking the issue by using a low-level method meant for highly customized behavior such as non-rectangular buttons. You just need:</p>
<p><a href="http://stackoverflow.com/questions/22882857/how-to-use-uibutton-as-toggle-button">How to use UIButton as Toggle Button?</a></p>
|
I am writing a program in C which searches the number stored in a txt file through a BST but there is mistake which I can't find <p>First portion of code is storing the integers in ans.txt
file through Binary Search Trees.</p>
<pre><code>/*code for storin the numbers in a particulr txt file */
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct root{
int val ;
struct root *left ;
struct root *right ;
};
void write(struct root *,int); // to write the numbers in a file
struct root *insrt(struct root *r,int val){
struct root *p,*q;
int ch,i=0;
FILE *fp;
if(r==NULL){
r=(struct root *)malloc(sizeof(struct root ));
p = r;
r->val=val;
r->left=r->right=NULL;
i++;
}
else{
if(val<r->val)
r->left=insrt(r->left,val);
else if(val>r->val)
r->right=insrt(r->right,val);
}
write(r,i);
return r;
}
void write(struct root *r,int i){
FILE *fp;
fp=fopen("texts/bst.txt","w");
fwrite(r,sizeof(struct root),1,fp);
fclose(fp);
}
void infile(struct root *r){ //storing the address of the root in ans.txt
FILE *fp;
fp=fopen("texts/ans.txt","a");
fprintf(fp,"%d\n",r->val);
}
void show(struct root *r){
if(r){
show(r->left);
printf("%d ",r->val);
infile(r);
show(r->right);
}
}
int main()
{
int val,i=0,n;
char y;
struct root *r;
printf("Enter the number: \n");
while((y=getchar())!=EOF){
if(y!=EOF){
scanf("%d",&val);
r=insrt(r,val);
i++;
}
}
show(r);
return 0;
}
</code></pre>
<p>This portion is the search where I'm trying to find the address of the
stored number and then from there I can apply the Binary Search Tree
method for finding the number but there are some mistakes which
I coundn't find. Please help me.</p>
<pre><code> /*code for search */
#include<stdio.h>
#include<stdlib.h>
struct root{
int val;
struct root *left;
struct root *right;
};
struct root *srch(struct root *r, int a){
if(r->val>a){
return srch(r->left,a);
}
else if (r->val<a){
return srch(r->right,a);
}
else
return r;
}
int main()
{
int num;
struct root *r,*f;
r=(struct root *)malloc(sizeof(struct root ));
FILE *fp;
fp=fopen("texts/bst.txt","rb");
fread(r,sizeof(struct root),1,fp);
fclose(fp);
printf("Enter the Number: ");
scanf("%d",&num);
f=srch(r,num);
if(f)
printf("Found");
else
printf("Not Found");
return 0;
}
</code></pre>
| <p>You have a few problem.<br>
1. <code>while((y=getchar())!=EOF){</code> : Discarded one character.<br>
2. <code>fwrite(r,sizeof(struct root),1,fp);</code> : Only nodes of the root is stored. Pointer can not be reproduced at the time of reading.<br>
3. <code>struct root *srch(struct root *r, int a){
if(r->val>a){</code> : First, you need to NULL check. </p>
<h2>Examples of changes:</h2>
<p>bst.h:</p>
<pre><code>#ifndef BST_H
#define BST_H
#define BST_TEXT_FILE "texts/ans.txt"
#define BST_BIN_FILE "texts/bst.dat"
struct root{
int val;
struct root *left;
struct root *right;
};
#endif
</code></pre>
<hr>
<p>input_store.h:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include "bst.h"
typedef enum ftype { Bin, Text } Ftype;
int fprint_bst(FILE *fp, struct root *r, Ftype type ){
if(r){
int count = 0;
count += fprint_bst(fp, r->left, type);
if(type == Text)
fprintf(fp, "%d\n", r->val);//write text
else
fwrite(&r->val, sizeof(r->val), 1, fp);write bin
count += fprint_bst(fp, r->right, type);
return count + 1;//count elements then it return
}
return 0;
}
void fwrite_bst(struct root *r){
FILE *fp;
int n;
fp = fopen(BST_TEXT_FILE, "wt");
n = fprint_bst(fp, r, Text);
fclose(fp);
fp = fopen(BST_BIN_FILE, "wb");
fwrite(&n, sizeof(n), 1, fp);//store number of elements
fprint_bst(fp, r, Bin);
fclose(fp);
}
struct root *insert(struct root *r, int val){
if(r == NULL){
r = malloc(sizeof(*r));
r->val = val;
r->left = r->right = NULL;
} else {
if(val < r->val)
r->left = insert(r->left, val);
else if(val > r->val)
r->right = insert(r->right, val);
}
return r;
}
void free_bst(struct root *r){
if(r){
free_bst(r->left);
free_bst(r->right);
free(r);
}
}
int main(void){
int val;
struct root *r = NULL;
printf("Enter the number: \n");
while(1 == scanf("%d", &val)){
r = insert(r, val);
}
fprint_bst(stdout, r, Text);
fwrite_bst(r);
free_bst(r);
return 0;
}
</code></pre>
<hr>
<p>search.c:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include "bst.h"
struct root *search(struct root *r, int a){
if(r == NULL)//need NULL check
return NULL;//and return NULL
if(r->val > a)
return search(r->left, a);
else if(r->val < a)
return search(r->right,a);
else
return r;
}
struct root *new_node(int val){
struct root *node = malloc(sizeof(*node));
if(!node){
fprintf(stderr, "fail malloc\n");
exit(EXIT_FAILURE);
}
node->val = val;
node->left = node->right = NULL;
return node;
}
struct root *create_bst(int n, int data[n]){
if(n == 0)
return NULL;
else if(n == 1)
return new_node(data[0]);
int mid = n / 2;//split [left part] mid [right part]
struct root *r = new_node(data[mid]);
r->left = create_bst(mid, data);
r->right = create_bst(n - mid -1, data+mid+1);
return r;
}
struct root *load(void){
int n;
FILE *fp = fopen(BST_BIN_FILE, "rb");
fread(&n, sizeof(n), 1, fp);//read number of elements
int *data = malloc(n * sizeof(*data));
fread(data, sizeof(*data), n, fp);
fclose(fp);
struct root *r = create_bst(n, data);
free(data);
return r;
}
int main(void){
int num;
struct root *f, *r = load();//Constitute the tree from the file
printf("Enter the Number: ");
scanf("%d", &num);
f = search(r, num);
if(f)
puts("Found");
else
puts("Not Found");
//free_bst(r);//Omitted because it is the same
return 0;
}
</code></pre>
|
Is there a List<T> like dynamic array that allows access to the internal array data in .NET? <p>Looking over the source of <code>List<T></code>, it seems that there's no good way to access the private <code>_items</code> array of items.</p>
<p>What I need is basically a dynamic <em>list</em> of <code>struct</code>s, which I can then modify in place. From my understanding, because C# 6 doesn't yet support <code>ref</code> return types, you can't have a <code>List<T></code> return a reference to an element, which requires copying of the whole item, for example:</p>
<pre><code>struct A {
public int X;
}
void Foo() {
var list = new List<A> { new A { X = 3; } };
list[0].X++; // this fails to compile, because the indexer returns a copy
// a proper way to do this would be
var copy = list[0];
copy.X++;
list[0] = copy;
var array = new A[] { new A { X = 3; } };
array[0].X++; // this works just fine
}
</code></pre>
<p>Looking at this, it's both clunky from syntax point of view, and possibly much slower than modifying the data in place (Unless the JIT can do some magic optimizations for this specific case? But I doubt they could be relied on in the general case, unless it's a special standardized optimization?)</p>
<p>Now if <code>List<T>._items</code> was protected, one could at least subclass <code>List<T></code> and create a data structure with specific modify operations available. Is there another data structure in .NET that allows this, or do I have to implement my own dynamic array?</p>
<p><strong>EDIT: I do not want any form of boxing or introducing any form of reference semantics.</strong> This code is intended for very high performance, and the reason I'm using an array of structs is to have them tighly packed on memory (and not everywhere around heap, resulting in cache misses).</p>
<p>I want to modify the structs in place because it's part of a performance critical algorithm that stores some of it's data in those structs.</p>
| <blockquote>
<p>Is there another data structure in .NET that allows this, or do I have to implement my own dynamic array?</p>
</blockquote>
<p>Neither.</p>
<p>There isn't, and <em>can't be</em>, a data structure in .NET that avoids the structure copy, because deep integration with the C# language is needed to get around the "indexed getter makes a copy" issue. So you're right to think in terms of directly accessing the array.</p>
<p>But you don't have to build your own dynamic array from scratch. Many <code>List<T></code>-like operations such as <code>Resize</code> and bulk movement of items are provided for you as static methods on type <code>System.Array</code>. They come in generic flavors, so no boxing is involved.</p>
<p>The unfortunate thing is that the high-performance <code>Buffer.BlockCopy</code>, which <em>should</em> work on any blittable type, actually contains a hard-coded check for primitive types and refuses to work on any structure.</p>
<p>So just go with <code>T[]</code> (plus <code>int Count</code> -- array length isn't good enough because trying to keep capacity equal to count is very inefficient) and use <code>System.Array</code> static methods when you would otherwise use methods of <code>List<T></code>. If you wrap this as a <code>PublicList<T></code> class, you can get reusability and both the convenience of methods for <code>Add</code>, <code>Insert</code>, <code>Sort</code> as well as direct element access by indexing directly on the array. Just exercise some restraint and never store the handle to the internal array, because it will become out-of-date the next time the list needs to grow its capacity. Immediate direct access is perfectly fine though.</p>
|
Writing JSON to file gives? <p>I have a JSON file with different names of countries and languages etc. I want to strip it down to just the information I need/want for what I am doing. For example I would like to turn</p>
<pre><code>[{
"name": {
"common": "Afghanistan",
"official": "Islamic Republic of Afghanistan",
"native": {
"common": "\u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627\u0646",
"official": "\u062f \u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627\u0646 \u0627\u0633\u0644\u0627\u0645\u064a \u062c\u0645\u0647\u0648\u0631\u06cc\u062a"
}
},
"tld": [".af"],
"cca2": "AF",
"ccn3": "004",
"cca3": "AFG",
"currency": ["AFN"],
"callingCode": ["93"],
"capital": "Kabul",
"altSpellings": ["AF", "Af\u0121\u0101nist\u0101n"],
"relevance": "0",
"region": "Asia",
"subregion": "Southern Asia",
"nativeLanguage": "pus",
"languages": {
"prs": "Dari",
"pus": "Pashto",
"tuk": "Turkmen"
},
"translations": {
"cym": "Affganistan",
"deu": "Afghanistan",
"fra": "Afghanistan",
"hrv": "Afganistan",
"ita": "Afghanistan",
"jpn": "\u30a2\u30d5\u30ac\u30cb\u30b9\u30bf\u30f3",
"nld": "Afghanistan",
"rus": "\u0410\u0444\u0433\u0430\u043d\u0438\u0441\u0442\u0430\u043d",
"spa": "Afganist\u00e1n"
},
"latlng": [33, 65],
"demonym": "Afghan",
"borders": ["IRN", "PAK", "TKM", "UZB", "TJK", "CHN"],
"area": 652230
}, ...
</code></pre>
<p>Into</p>
<pre><code>[{
"name": {
"common": "Afghanistan",
"native": {
"common": "\u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627\u0646"
}
},
"cca2": "AF"
}, ...
</code></pre>
<p>But when I try I get</p>
<pre><code>[{
"name": {
"common": "Afghanistan",
"native": {
"common": "?????????" <-- NOT WHAT I WANT
}
},
"cca2": "AF"
},
</code></pre>
<p>Here is the important code I used to strip out what I don't want.</p>
<pre><code>byte[] encoded = Files.readAllBytes(Paths.get("countries.json"));
String JSONString = new String(encoded, Charset.forName("US-ASCII"));
...
Writer writer = new OutputStreamWriter(new FileOutputStream("countriesBetter.json"), "US-ASCII");
writer.write(javaObject.toString());
writer.close();
</code></pre>
<p>I cannot figure out why it turns the text into question marks. I have tried several character sets to no avail. When I use UTF-8 i get <code>çÃ�úçÃâ óêçÃâ </code></p>
<p>Please help me. Thank you.</p>
| <p>\u0627 is unicode not ascii and you cannot represent the arabic characters in ascii - hence the ?. For differences between utf formats see <a href="http://stackoverflow.com/questions/4655250/difference-between-utf-8-and-utf-16">Difference between UTF-8 and UTF-16?</a> </p>
<p>when you write it UTF-8 you need to read in the same encoding so the "notepad" knows how to display the bytes it has. If you read it back into java using that encoding it will be unaltered.</p>
|
RegEx to match a single digit followed by a "." followed by another single digit <p>I am trying to find the RegEx in use with the preg_match function for a single digit followed by a "." followed by a single digit.</p>
<p>Example:</p>
<p>3.3 valid
44.4 invalid but would capture 4.4
4.664 invalid but would capture 4.6</p>
| <p>this regex should help you:</p>
<p><code>\d{1,1}[\.]{1}\d{1,1}</code></p>
<p>you can try other regex at <a href="http://www.regextester.com/?fam=95922" rel="nofollow">this site</a></p>
|
Add a checkbox to a dynamically added table row <p>I have a table which I add cells to dynamically. I want to add a checkbox as one of the cell elements. Specifically to element cell_0 of row0.
I tried <code>cell_0.innerHTML = <input type = "checkbox />;</code>but that didn't work.</p>
<pre><code>var row0 = document.getElementById("jobsTable").insertRow(0);
var cell_0 = row0.insertCell(0);
cell_0.innerHTML = <input type="checkbox"/> ;
var cell_1 = row0.insertCell(1);
cell_1.innerHTML = "CIT Suite";
var cell_2 = row0.insertCell(2);
cell_2.innerHTML = "Buildroot";
<table id="jobsTable" class="container" align="center" style="width:40%">
</table>
</code></pre>
<p>Any help is appreciated!</p>
| <p>You have to quote the html. <code>cell_0.innerHTML = '<input type="checkbox"/>';</code></p>
|
c# - using file.encrypt to save some persistent info locally? <p>I have a program that needs to save some user-unique information on each user's machine (I query the user for it upon first use). In my first draft of the program I simply saved that info in a text file (in a sub-folder of the program folder). But it is open text, and I'd like to change it so that it is not so easy to read.</p>
<p>After reading some articles in MSDN I thought that using File.Encrypt and File.Decrypt would do the job. I didn't want to hash the text, because I need to retrieve it and use it in my program in its open form. (As you can guess I have not worked with encryption before - which is also why I am not anxious to use something more complex - but will do so if it is my only alternative). </p>
<p>Here's my code, which is not working. I'd appreciate any feedback about what I am doing wrong...</p>
<pre><code>if (File.Exists(@"subfolder\a.txt"))
{
File.Decrypt(@"subfolder\a.txt");
string unique = File.ReadAllText(@"subfolder\a.txt");
File.Encrypt(@"subfolder\a.txt");
}
else
{
string unique =
Microsoft.VisualBasic.Interaction.InputBox("Please enter your
unique text ...", "Enter your unique text", "");
File.WriteAllText(@"creds\u.txt", username);
File.Encrypt(@"creds\u.txt");
}
</code></pre>
<p>Thanks.</p>
<p>A relative newbie....</p>
| <p>Ok, first think about your methdology here.</p>
<pre><code>If (the file exists) {
Decrypt the file
Read the contents
Encrypt it again
} else {
Enter text
Save as a different file name than above
Encrypt the file
}
</code></pre>
<p>When you decrypting the file, you are trying to decrypt the file on the disk leaving it unencrypted.
You then read the content, and encrypt it again.</p>
<p>This approach assumes that you are decrypting the file to the disk, then reading the contents, however this is not the correct usage.</p>
<p><a href="https://support.microsoft.com/en-us/kb/301070" rel="nofollow">https://support.microsoft.com/en-us/kb/301070</a></p>
<p>You mentioned you don't want to hash the data, but assuming that you will be using a suitable complex salt and key, you can store these in the program for use in a proven hashing algorithm.</p>
<p>Somebody could potentially retrieve these by decompiling the IL code, but it's still more secure than decrypting on the disk.</p>
<p>Have a read of the following article which will explain a few factors of secure hashing you might find useful.
<a href="https://crackstation.net/hashing-security.htm" rel="nofollow">https://crackstation.net/hashing-security.htm</a></p>
<p>Part of the issue you might have with <code>File.Encrypt</code> is that it is not universally supported across windows platforms, which to my mind makes it close to useless.</p>
<p>Fundamentally, if you're intending to decrypt the data for use in your program, I doubt your main concern is somebody cracking a network and getting access to company secrets, more keeping people from messing with configuration data or similar.
Hashes with salt using keys stored in code is perfectly fine for this, but will not satisfy any serious security concerns in an enterprise grade application.</p>
<p>This article will walk your through the process. Instead of asking for a password, you can store the cipher as a string in your program if you would like, although if you included a login prompt for your program, you could use the example code pretty much unchanged.</p>
<p><a href="https://msdn.microsoft.com/en-us/library/ms172831.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/ms172831.aspx</a></p>
|
Paypal Sandbox Testing Error <p>i am in PAYPAL SANDBOX mode [as a developer] trying to integrate paypal into my client website. [Simple case of putting a BUY button onto the page - which I have done successfully] --- and then testing the payment process works]. </p>
<p>Problem.......
When I test the BUY button it takes me to the SANDBOX payment page. From there I make a purchase [using my Eamil-buyer@gmail.com] account - set up by the Sandbox. The purchase goes through to PAY and from there i can make the payment which successfully registers in my Sandbox transactions log. However I have the following two problems on completing the purchase process---</p>
<ol>
<li><p>I get the error
Rapids::Exception (N6Rapids5Tools13PimpExceptionE): Pimp RC: 3514</p></li>
<li><p>I am not being returned from the Pay Now page to my Thank You page --- on my website.</p></li>
</ol>
<p>Please help. </p>
<p>Thank you</p>
| <p>Check to make sure both the buyer and seller sandbox accounts you are using are showing as "Verified". </p>
<p>If not, verify them and see if the error goes away.</p>
<p>If so, try testing a checkout in Incognito mode (or equivalent with your browser.) This will eliminate the use of any caching / cookies which can often cause conflicts with PayPal, especially on the sandbox.</p>
|
Inserting html tags on image at specific positions in html and css <p>I have this image Map.png. i want to write text these location boxes using html.
so that i can change it dynamically.
I just do not know how to that.. please give me a direction.
<a href="http://i.stack.imgur.com/rrFzo.png" rel="nofollow"><img src="http://i.stack.imgur.com/rrFzo.png" alt="enter image description here"></a></p>
| <p>Couple of ways to do this.</p>
<ol>
<li><p>Simplistic way would be using just css absolute property and top/left properties to position the location icons on top of the map.png. Add the map.png to a div and make the div css position relative. Add each location icon at top/left property and make sure location icon css position is absolute.</p></li>
<li><p>Better way would be to use <a href="https://developers.google.com/maps/" rel="nofollow">Google Map Api</a>. Draw the polygons for the states in you map.png on top of the Google map and then position Google location markers. Much slicker and very easy to use.</p></li>
</ol>
|
NSTextField margin and padding? (Swift) <p>I am wondering if thereâs a possibility to set a margin or padding for <code>NSTextField</code>? </p>
<p>I achieved a more or less custom looking textField (the first one in this screenshot)...</p>
<p><a href="http://i.stack.imgur.com/1NGV6.png" rel="nofollow"><img src="http://i.stack.imgur.com/1NGV6.png" alt="enter image description here"></a></p>
<p>... using this code:</p>
<pre><code>myTextField.wantsLayer = true
myTextField.layer?.cornerRadius = 2.0
myTextField.layer?.borderWidth = 1.0
myTextField.layer?.borderColor = CGColor(red: 0.69, green: 0.69, blue: 0.69, alpha: 1.0)
</code></pre>
<p>However, it feels like I have to add some padding on the left side so that the numbers are not too close to the border. Is that even possible?</p>
| <p>I usually do this just by putting the textField in a container view. You can give the view any corner radius, border, etc you want, and then just constrain the textField to the inside with whatever padding you want. Just make sure you change the textField's border style to 'none' or you'll be able to see it inside your view.</p>
<p>There might be a way to change the content inset like you can with a button, but I've never been able to find it.</p>
|
Extract JSON array in Redshift when the object name is a variable value <p>Apologies up front if I use incorrect terminology, I'm relatively new to JSON. I'm querying data from Amazon Redshift.</p>
<p>The following is an example of the JSON data I'm seeing:</p>
<p>{"id":{"names":["name1", "name2", "name3"]</p>
<p>I want to get the object containing the names (of which there can be up to 15). Normally this does the trick without a hitch:</p>
<p>select json_extract_path_text(column, 'id', 'names')</p>
<p>I'm hitting a snag in this case, however. The "id" is a variable number...it's actually a customer ID number. This means the ID is going to be different in every case, so one row might contain:</p>
<p>{"12345":{"names":["Lisa", "Dave", "Sean"]</p>
<p>while the next row might contain:</p>
<p>{"6789":{"names":["Phil", "Jenny"]</p>
<p>The JSON functions that Redshift supports aren't working out. How can I get the "names" object when the path element is different every time? </p>
| <p>You could try Redshift User Defined Functions(UDFS). Easy, Simple to test & manage for such requirement. UDFs could be refined to support different params & details.</p>
<pre><code> CREATE FUNCTION dynamic_json_extract_path_text (txt VARCHAR(20000) ) RETURNS VARCHAR(20000) IMMUTABLE AS $$
import json
try:
data = json.loads(txt)
for d in data:
return json.dumps(data[d]['names'])
return ''
except:
return ''
$$ LANGUAGE plpythonu;
</code></pre>
|
Consistent Cluster Order with Kmeans in R <p>This might not be possible, but Google has failed me so far so I'm hoping someone else might have some insight. Sorry if this has been asked before.</p>
<p>The background is, I have a database of information on different cities, so like name, population, pollution, crime, etc by year. I'm querying it to aggregate the data on a per-city basis and outputting the result to a table. That works fine.</p>
<p>The next step is I'm running the kmeans() function in R on the data set to find clusters, in testing I've found that 5 clusters is almost always a good choice via the "elbow method".</p>
<p>The issue I'm having is that these clusters have distinct meanings/interpretations, so I want to tag each row in the original data set with the cluster's interpretation for that row, not the cluster number. So I don't want to identify row 2 with "cluster 5", I want to say "low population, high crime, low income".</p>
<p>If R would output the clusters in the same order, say having cluster 5 always equate to the cluster of cities with "low population, high crime, low income", that would work fine, but it doesn't. For instance, if you run code like this:</p>
<pre><code>> a = kmeans(city_date,centers=5)
> b = kmeans(city_date,centers=5)
> c = kmeans(city_date,centers=5)
</code></pre>
<p>The run this code:</p>
<pre><code>a$centers
b$centers
c$centers
</code></pre>
<p>The clusters will all contain the same data set, but the cluster number will be different. So if I have a mapping table in SQL that has cluster number and interpretation, it won't work, because when I run it one day it might have the "low population, high crime, low income" cluster as 5, and the next it might be 2, the next 4, etc.</p>
<p>What I'm trying to figure out is if there is a way to keep the output consistent. The data set gets updated so it won't even be the same every time, and since R doesn't keep the cluster order consistent even with the same data set, I am wondering if it will be possible at all.</p>
<p>Thanks for any help anyone can provide. On my end my current idea is to output the $centers data to a SQL table, then order the table by the various metrics, each time the one with the highest/lowest getting tagged as such, and then concatenating the results to tag the level. This may work but isn't very elegant.</p>
| <p>Usually k-means are initialized randomly few times to avoid local minimums. If you want to have resulting clusters ordered, you have to order them manually after k-means algorithm stops to work.</p>
|
syncing two mysql db table <p>So, I have two mysql db tables: "table_original" and "table_copy"</p>
<p>Here is my current setup:</p>
<p>Every night, <code>table_original</code> gets updated from another server with information. It either removes the old db row or adds a new line it with unique post_id (there won't be no two identical post_id even if row is removed).</p>
<p>Then, certain information along with the post_id is copied into <code>table_copy</code>. Thus two are linked by the <code>post_id</code>.</p>
<p>So far, the <code>table_original</code> has ~20,000 rows while <code>table_copy</code> has ~40,000.</p>
<p>I just noticed that <code>table_copy</code> has not been being updated from the first table but only have been adding rows instead of removing anything that was removed from the first table.</p>
<p>In order to sync them, my initial approach was to check each row from <code>table_original</code> against the <code>table_copy</code> then if post_id exists, then do nothing, if not, remove the row from the <code>table_copy</code>.</p>
<p>My concern is that, the <code>table_original</code> will get updated every night: either older post_id row will be removed and/or add new rows. Unfortunately there is no way for me to know what is being done before it is done. Meaning, I have to wait till the db is updated to see what was removed and added.</p>
<p>Then, every time the first table is updated, then I have to check every rows against the second table to update them. The table will only get bigger and I am concerned that this approach might not be the best.</p>
<p>What do you guys suggest that I can do?</p>
<p>Thanks!</p>
| <p>To delete the rows in table_copy that are not present in table_original:</p>
<pre><code>DELETE t1.* FROM table_copy AS t1
LEFT OUTER JOIN table_original AS t2 USING (post_id)
WHERE t2.post_id IS NULL;
</code></pre>
<p>I recommend you create a dummy table with a few rows so you can experiment with this kind of query and increase your confidence with it before you run it against your real data!</p>
<p>See <a href="http://dev.mysql.com/doc/refman/5.7/en/delete.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.7/en/delete.html</a> for more docs on the multi-table DELETE statement.</p>
<p>To keep them in sync every night automatically, use triggers:</p>
<pre><code>CREATE TRIGGER copy_on_ins AFTER INSERT ON table_original
FOR EACH ROW
INSERT INTO table_copy SET post_id = NEW.post_id, other_columns = NEW.other_column;
CREATE TRIGGER copy_on_upd AFTER UPDATE ON table_original
FOR EACH ROW
UPDATE table_copy SET other_column = NEW.other_column
WHERE post_id = NEW.post_id;
CREATE TRIGGER copy_on_del AFTER DELETE ON table_original
FOR EACH ROW
DELETE FROM table_copy WHERE post_id = OLD.post_id;
</code></pre>
<p>See <a href="http://dev.mysql.com/doc/refman/5.7/en/create-trigger.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.7/en/create-trigger.html</a></p>
<hr>
<p>Re your comment:</p>
<p>Knowing which post_ids were deleted is tricky. Since they are no longer in the database, you'd either need to:</p>
<ul>
<li>Infer that they were once there, if you find a gap between post_id values that are still in the database. But this is no guarantee, because id values may never be used if an insert fails.</li>
<li>Check a log of some kind. Some people use a trigger to append to an audit table. Or else code their application that deletes posts to create a log.</li>
<li>Read through deletion events using the <a href="http://dev.mysql.com/doc/refman/5.7/en/mysqlbinlog.html" rel="nofollow">mysqlbinlog</a> tool. This is kind of advanced.</li>
</ul>
|
Entity Framework: The 'ComplexType.Field' property does not exist or is not mapped to type 'Entity' <p>I have a problem with mapping properties on value objects/complex types to entities. I have a user entity which has a complex type property called Credential, which in turn has properties: Email, UserName, Password and SecurityStamp. I am trying to map properties from complex type to entities, and the source code is shown below:</p>
<pre><code>public class User
{
public string Id { get; protected set; }
public Credential Credential { get; protected set; }
// unrelated properties and methods omitted for simplicity
}
public sealed class Credential: ValueObject<Credential>
{
public string Email { get; private set; }
public string UserName { get; private set; }
public string Password { get; private set; }
public string SecurityStamp { get; private set; }
public Credential() { }
public Credential(string email, string userName, string password, string securityStamp)
{
Email = email;
UserName = userName;
Password = password;
SecurityStamp = securityStamp;
}
public class CoreContext: DbContext
{
public IDbSet<User> Users { get; set; }
public CoreContext(string connectionString) : base(connectionString) {}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<CoreContext>(null);
modelBuilder.ComplexType<Credential>().Property(ucr => ucr.Email).HasColumnName("Email");
modelBuilder.ComplexType<Credential>().Property(ucr => ucr.UserName).HasColumnName("UserName");
modelBuilder.ComplexType<Credential>().Property(ucr => ucr.Password).HasColumnName("Password");
modelBuilder.ComplexType<Credential>().Property(ucr => ucr.SecurityStamp).HasColumnName("SecurityStamp");
modelBuilder.Entity<User>().Property(u => u.Credential.Email).HasColumnName("Email");
modelBuilder.Entity<User>().Property(u => u.Credential.UserName).HasColumnName("UserName");
modelBuilder.Entity<User>().Property(u => u.Credential.Password).HasColumnName("Password");
modelBuilder.Entity<User>().Property(u => u.Credential.SecurityStamp).HasColumnName("SecurityStamp");
}
}
</code></pre>
<p>As you see, I was trying to map complex type properties to the entity. I started by configuring Credential as a complex type, and then configure the properties on entity User. However, I am receiving the following error:</p>
<pre><code>The 'Credential.Email' property does not exist or is not mapped for the type 'User'.
</code></pre>
<p>I dont understand why this happens. I've done everything I can to configure complex type mapping, why it wont work? Anyone have ideas on what I may have done wrong? </p>
| <p>Not been able to reproduce this:</p>
<p><strong>I've got this after add-migration with the same setup you have:</strong></p>
<pre><code>public override void Up()
{
CreateTable(
"dbo.Users",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Email = c.String(),
UserName = c.String(),
Password = c.String(),
SecurityStamp = c.String()
})
.PrimaryKey(t => t.Id);
}
</code></pre>
<p>The only thing I've removed is your base class on Credential: ValueObject because I don't have it. Everything looks good so maybe there's something wrong with that class?</p>
|
3-level hierarchy with bootstrap scrollspy? <p>I want to add another hierarchy level to my <a href="http://codepen.io/staypuftman/pen/PGYJKB" rel="nofollow">existing 2-level scrollspy</a>. I've tried nesting it by adding more levels but that didn't work at all.</p>
<pre><code> <ul class="nav nav-stacked">
<li><a href="#GroupASub1">Sub-Group 1</a></li>
<li><a href="#GroupASub2">Sub-Group 2</a></li>
</ul>
</code></pre>
<p>What is the best way to do this? Are there working examples of 3-level scrollspy that I haven't found yet?</p>
<p>Thank you very much for your time!</p>
| <p>Well, it's not very hard to nested to 3rd level just easily follow what you have done for 2nd level and do it for 3rd level. </p>
<p>For instance, I have a demo here <a href="http://codepen.io/mhadaily/pen/dpdvwp" rel="nofollow">http://codepen.io/mhadaily/pen/dpdvwp</a> which I have forked your work and nested to 3rd level. </p>
<p>I hope this sample code helps.</p>
<p>to clarify: I have changed this part </p>
<pre><code><section id="GroupA" class="group">
<h3>Group A</h3>
<div id="GroupASub1" class="subgroup clearfix">
<h4>Group A Sub 1</h4>
<hr>
<div class="clearfix">
<div id="GroupASubSub1" class="subsubgroup">
<h4>Group A SubSub 1</h4>
</div>
<div id="GroupASubSub2" class="subsubgroup">
<h4>Group A SubSub 2</h4>
</div>
</div>
</div>
<div id="GroupASub2" class="subgroup">
<h4>Group A Sub 2</h4>
</div>
</section>
</code></pre>
<p>and </p>
<pre><code> <li>
<a href="#GroupA">Group A</a>
<ul class="nav nav-stacked">
<li><a href="#GroupASub1">Sub-Group 1</a>
<ul class="nav nav-stacked">
<li><a href="#GroupASubSub1">SUBSub-Group 1</a></li>
<li><a href="#GroupASubSub2">SUbSub-Group 2</a></li>
</ul>
</li>
<li><a href="#GroupASub2">Sub-Group 2</a></li>
</ul>
</li>
</code></pre>
<p>and your css code to </p>
<pre><code>.group {
background: yellow;
width: 200px;
height: 800px;
}
.group .subgroup {
background: orange;
width: 150px;
height: 400px;
}
.group .subsubgroup {
background: blue;
width: 100px;
height: 150px;
}
.group .subsubgroup h4 {color:white}
</code></pre>
|
Use the transition-delay option (css) and JS to make a div move <p>I want to create a function that moves a block smoothly. I prefer to use the CSS option 'transition-duration' for this, but it doesn't seem to work for the position. I checked, and it does work for background-color...</p>
<p>CSS file</p>
<pre><code> #cart {
position: relative;
transition-duration: 0.5s;
background-color: green;
}
</code></pre>
<p>JS file</p>
<pre><code>function start() {
document.getElementById("cart").innerHTML = "test2";
document.getElementById("cart").style.left = "100";
document.getElementById("cart").style.background = "gray";
}
</code></pre>
<p>So the background-color does change in 2 seconds instead of instantly while the position just changes the instant you use the function. Is there a way to use the 'transition-duration' for the style.left in JS? Or do I have to use something else to make the div move smoothly?</p>
| <p>Use transition: left 0.5s linear; as you haven't said what property you're transitioning. </p>
<p>Also, put the styles you want to change to in a class and apply the class with js instead. </p>
<p>Also, you probably want to transition an absolute item inside a relative container, not apply 'left' to a relative element. </p>
|
Kubenetes doesn't recover service after minion failure <p>I am testing Kubernetes redundancy features with a testbed made of one master and three minions. </p>
<p><strong>Case:</strong> I am running a service with 3 replicas on minions 1 and 2 and minion3 stopped</p>
<p>[root@centos-master ajn]# <code>kubectl get nodes</code> </p>
<blockquote>
<p>NAME STATUS AGE<br>
centos-minion3 NotReady 14d<br>
centos-minion1 Ready 14d<br>
centos-minion2 Ready 14d </p>
</blockquote>
<p>[root@centos-master ajn]# <code>kubectl describe pods $MYPODS | grep Node:</code> </p>
<blockquote>
<p>Node: centos-minion2/192.168.0.107<br>
Node: centos-minion1/192.168.0.155<br>
Node: centos-minion2/192.168.0.107 </p>
</blockquote>
<p><strong>Test:</strong> After starting minion3 and stopping minion2 (on which 2 pods are running)</p>
<p>[root@centos-master ajn]# <code>kubectl get nodes</code> </p>
<blockquote>
<p>NAME STATUS AGE<br>
centos-minion3 Ready 15d<br>
centos-minion1 Ready 14d<br>
centos-minion2 NotReady 14d </p>
</blockquote>
<p><strong>Result:</strong> The service kind doesn't recover from minion failure and Kubernetes continue showing pods on the failed minion. </p>
<p>[root@centos-master ajn]# <code>kubectl describe pods $MYPODS | grep Node:</code> </p>
<blockquote>
<p>Node: centos-minion2/192.168.0.107<br>
Node: centos-minion1/192.168.0.155<br>
Node: centos-minion2/192.168.0.107 </p>
</blockquote>
<p><strong>Expected result (at least in my understanding):</strong> the service should have been built on the currently available minion 1 and 3</p>
<p>As far as I understand, the role of service kind is to make the deployment "globally" available so we can refer to them independently of where deployments are in the cluster.</p>
<p>Am I doing something wrong?</p>
<hr>
<p>I'm using the follwoing yaml spec: </p>
<p>apiVersion: v1<br>
kind: ReplicationController<br>
metadata:<br>
  name: nginx-www <br>
spec:<br>
  replicas: 3<br>
  selector:<br>
    app:  nginx<br>
  template:<br>
    metadata:<br>
      labels:<br>
        app: nginx<br>
    spec:<br>
      containers:<br>
      - name: nginx<br>
        image: nginx<br>
        ports:<br>
        - containerPort: 80 </p>
| <p>It looks like you're always trying to read the same pods that are referenced in <code>$MYPODS</code>. Pod names are created dynamically by the ReplicationController, so instead of <code>kubectl describe pods $MYPODS</code> try this instead:</p>
<p><code>kubectl get pods -l app=nginx -o wide</code></p>
<p>This will always give you the currently scheduled pods for your app.</p>
|
Getting from cart content the post ID <p>I am trying to grab the post id from WooCommerce cart content so I can access an advanced custom field number I have set. I am not able to find a post ID value only a product ID value which will not work.</p>
<p>This is my code:</p>
<pre><code>add_action('woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$service_charge =0;
$cart_contents =($woocommerce->cart->cart_contents);
foreach($cart_contents as $cart_contents =>$values) {
$post_values = $values['data']->post;
$post_id = $post_values->ID;
$value = get_field( 'service_charge', $post_id );
}
</code></pre>
<p>How can I get the post ID?</p>
<p>Thanks</p>
| <p>I have changed a little bit your code, and now you will get correctly the item ID to use with ACF plugin <strong><code>get_field(</code></strong>) function.</p>
<p>This is the code:</p>
<pre><code>add_action('woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$service_charge = 0;
// As you can have multiple items in cart we will save all values in an indexed array.
$service_charge_values_array = array();
foreach(WC()->cart->cart_contents as $item) {
$item_id = $item['data']->id;
// Each stored value has a corresponding key that is the item ID
$service_charge_values_array[$item_id] = get_field( 'service_charge', $item_id );
}
// . . .
}
</code></pre>
<p><em>The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.</em></p>
<p>This is tested and works.</p>
<hr>
<blockquote>
<p><strong>Update</strong></p>
<p>As you can have multiple items in your cart, I have changed the code a little bit and I store now the data in an array in which for each <strong><code>item ID</code></strong> is stored in the <strong><code>key</code></strong> with a corresponding <strong><code>value</code></strong> of <strong><code>'service_charge'</code></strong>.</p>
</blockquote>
|
php replace complete numbers <p>Hi hope somebody can help me, I have the following code but I send $data = 11, it sends me a 1010 instead of 100, is replacing the '1' two times, does anybody know how to fix this? thanks</p>
<pre><code>$search = ['1','2','3','11','12','13'];
$replace = ['10','25','50','100','250','500'];
return str_replace($search, $replace, $data);
</code></pre>
| <p>Try to make the reverse order and use a foreach with a $count check like the following:</p>
<pre><code>$search = ['13','12','11','3','2','1'];
$replace = ['500', '250', '100','50','25','10'];
for($i=0, $count=0; $i<count($search); $i++) {
$data = str_replace($search[$i], $replace[$i], $data, $count);
if ($count) {
return $data;
}
}
</code></pre>
|
how do I insert data to an arbitrary location in a binary file without overwriting existing file data? <p>I've tried to do this using the 'r+b', 'w+b', and 'a+b' modes for <code>open()</code>. I'm using with <code>seek()</code> and <code>write()</code> to move to and write to an arbitrary location in the file, but all I can get it to do is either 1) write new info at the end of the file or 2) overwrite existing data in the file.
Does anyone know of some other way to do this or where I'm going wrong here?</p>
| <p>What you're doing wrong is assuming that it can be done. :-)</p>
<p>You don't get to insert and shove the existing data over; it's already in that position on disk, and overwrite is all you get.</p>
<p>What you need to do is to mark the insert position, read the remainder of the file, write your insertion, and then write that remainder <em>after</em> the insertion.</p>
|
How to avoid .pyc files using selenium webdriver/python while running test suites? <p>There's no relevant answer to this question. When I run my test cases inside a test suite using selenium webdriver with python the directory gets trashed with .pyc files. They do not appear if I run test cases separately, only when I run them inside one test suite.How to avoid them?</p>
<pre><code>import unittest
from FacebookLogin import FacebookLogin
from SignUp import SignUp
from SignIn import SignIn
class TestSuite(unittest.TestSuite):
def suite():
suite = unittest.TestSuite()
suite.addTest(FacebookLogin("test_FacebookLogin"))
suite.addTest(SignUp("test_SignUp"))
suite.addTest(SignIn("test_SignIn"))
return suite
if __name__ == "__main__":
unittest.main()
</code></pre>
| <p><code>pyc</code> files are created any time you <code>import</code> a module, but not when you run a module directly as a script. That's why you're seeing them when you import the modules with the test code but don't see them created when you run the modules separately.</p>
<p>If you're invoking Python from the command line, you can suppress the creating of <code>pyc</code> files by using the <code>-B</code> argument. You can also set the environment variable <code>PYTHONDONTWRITEBYTECODE</code> with the same effect. I don't believe there's a way to change that setting with Python code after the interpreter is running.</p>
<p>In Python 3.2 and later, the <code>pyc</code> files get put into a separate <code>__pycache__</code> folder, which might be visually nicer. It also allows multiple <code>pyc</code> files to exist simultaneously for different interpreter versions that have incompatible bytecode (a "tag" is added to the file name indicating which interpreter uses each file).</p>
<p>But even in earlier versions of Python, I think that saying the <code>pyc</code> files are "trashing" the directory is a bit hyperbolic. Usually you can exempt the created files from source control (e.g. by listing <code>.pyc</code> in a <code>.gitignore</code> or equivalent file), and otherwise ignore them. Having <code>pyc</code> files around speeds up repeated imports of the file, since the interpreter doesn't need to recompile the source to bytecode if the <code>pyc</code> file already has the bytecode available.</p>
|
PHP form not inserting into mySQL database <p>hi guys thanks if you can tell me what error i need help guys thanks for help me </p>
<pre><code><?php
$servername = "localhost"; $username = "root"; $password = "";
$dbname = "kurd";
mysql_connect("localhost","root","","kurd") or die ("not connect data base");
mysql_select_db("kurd") or die ("no found table");
if(isset($_POST['submit'])){
$name = $_POST['name'];$lastname = $_POST['lastname'];
$password =_POST['password'];
$query =" INSERT INTO kurdstan (name,lastname,password) VALUES ('$name','$lastname','$password')";
if(mysql_query($query)){
echo "<h3>THANKS FOR INSERT DATA GOOD LUCK</h3>";
}
}
?>
</code></pre>
| <p>In your code add an <code>else</code> to,</p>
<pre><code>if(mysql_query($query)){
echo "<h3>THANKS FOR INSERT DATA GOOD LUCK</h3>";
}
</code></pre>
<p>resulting in,</p>
<pre><code>if(mysql_query($query)){
echo "<h3>THANKS FOR INSERT DATA GOOD LUCK</h3>";
}
else {
echo 'MYSQL Error: ' . mysql_error();
}
</code></pre>
<p>and you will probably see an error instead of your message which should help you to track down the problem.</p>
<p><strong>NOTE</strong></p>
<p>The <code>mysql</code> extension is now depreciated, you should use <code>mysqli</code> <a href="http://php.net/manual/en/book.mysqli.php" rel="nofollow">http://php.net/manual/en/book.mysqli.php</a> or PDO <a href="http://php.net/manual/en/book.pdo.php" rel="nofollow">http://php.net/manual/en/book.pdo.php</a>. You should also read up on SQL injection - your data needs escaping before being used in a query string.</p>
|
Node.js spawn ENOENT error <p>So I followed <a href="http://stackoverflow.com/questions/27688804/how-do-i-debug-error-spawn-enoent-on-node-js/27688805#27688805">this answer</a> and made it to the last step, correctly I think. But then what? I'm trying to run a node file, but it doesn't appear to be in the file listed at the PATH directory. How am I supposed to get it in that folder?</p>
<p>My node entry file:</p>
<pre><code>'use strict';
var express = require("express");
var child_process = require("child_process");
var app = express();
app.get("/go", function(req, res, next) {
var stream = child_process.spawn("node file.js").on("error", function(error) {
console.log("Error!!! : " + error);
throw error;
});
});
app.get("/", function(req, res, next) {
console.log("Hit main page.");
res.end("Got me.");
});
app.listen( (process.env.PORT || 4000), function() {
console.log("Example app listening on Heroku port " + process.env.PORT + " or local port 4000!");
});
</code></pre>
<p>And file.js, the file I'm attempting to open:</p>
<pre><code>'use strict';
function sayHello() {
console.log("Hello.");
}
sayHello();
</code></pre>
| <p>In your spawn method, you should have:</p>
<pre><code>app.get("/go", function(req, res, next) {
var stream = child_process.spawn("node", ["file.js"]).on("error", function(error) {
console.log("Error!!! : " + error);
throw error;
});
});
</code></pre>
|
Can't deserialize Asana User data into C# class <p>I'm trying to deserialize the data I'm getting from the users/me call in the Asana API as per below, but the object is returning null for all properties in the jsonResponse var. The data is there - I can see it if I read it as pure text. I've also tried using [JsonProperty("id")] attributes instead of [DataMember] for use with a JsonSerializer instead of DataContractJsonSerializer, but I get an exception: "Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Data2'."</p>
<p>What am I doing wrong? </p>
<p>Note: I've been creating the classes using <a href="http://www.xamasoft.com/json-class-generator" rel="nofollow">Xamasoft JSON Class Generator</a>; see the class below the GetUser method.</p>
<pre class="lang-cs prettyprint-override"><code> public AsanaObjects.Data2 GetUser()
{
AsanaObjects.Data2 result = null;
string url = "https://app.asana.com/api/1.0/users/me";
try
{
var uri = new Uri(url);
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CertificateCheck);
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
//Must use Tls12 or else exception: "The underlying connection was closed: An unexpected error occurred on a send." InnerException = {"Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."}
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Timeout = 10000;
webRequest.Method = "GET"; webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Accept = "application/json";
//webRequest.UseDefaultCredentials = true; //doesn't seem to make a difference
webRequest.Headers.Add("Authorization", "Bearer " + AsanaBroker.Properties.Settings.Default.AccessToken);
using (var response = webRequest.GetResponse())
{
//using (var responseStream = ((HttpWebResponse)response).GetResponseStream())
//{
// if (responseStream != null)
// {
// var reader = new System.IO.StreamReader(responseStream);
// string readerText = reader.ReadToEnd();
// //Example return data: {"data":{"id":12343281337970,"name":"Eric Legault","email":"eric@foo.com","photo":null,"workspaces":[{"id":1234250096894,"name":"foo"},{"id":123446170860,"name":"Personal Projects"},{"id":12345000597911,"name":"foo2"}]}}
// }
//}
using (var responseStream = ((HttpWebResponse)response).GetResponseStream())
{
if (responseStream != null)
{
try
{
AsanaObjects.Data2 jsonResponse = null;
var jsonSerializer = new DataContractJsonSerializer(typeof(AsanaObjects.Data2));
jsonResponse = jsonSerializer.ReadObject(responseStream) as AsanaObjects.Data2;
if (jsonResponse != null)
{
result = jsonResponse;
}
}
catch (Exception ex)
{
Log.Error(ex);
}
}
}
}
}
catch (Exception ex)
{
}
return result;
}
</code></pre>
<p>This is the class I'm trying to deserialize into (sorry for the initial unformatted part - not sure how to fix):</p>
<p>public partial class AsanaObjects
{
[DataContract]
public class Workspace
{
[DataMember]
public object id { get; set; }</p>
<pre><code> [DataMember]
public string name { get; set; }
}
}
public partial class AsanaObjects
{
[DataContract]
public class Data2
{
[DataMember]
public long id { get; set; }
[DataMember]
public string name { get; set; }
[DataMember]
public string email { get; set; }
[DataMember]
public object photo { get; set; }
[DataMember]
public Workspace[] workspaces { get; set; }
}
}
public partial class AsanaObjects
{
[DataMember]
public Data2[] data { get; set; }
}
</code></pre>
| <ol>
<li><code>data</code> is not an array. In your sample it is a single object. </li>
<li>You want to be deserializing at the root, <code>AsanaObjects</code> class, not one level down at the <code>data</code> class. </li>
<li>I also had to throw a <code>[DataContract]</code> on the root <code>AsanaObjects</code> class</li>
</ol>
<p>The following works and comes back with a full object:</p>
<pre><code>using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
const string Json = @"{""data"":{""id"":12343281337970,""name"":""Eric Legault"",""email"":""eric@foo.com"",""photo"":null,""workspaces"":[{""id"":1234250096894,""name"":""foo""},{""id"":123446170860,""name"":""Personal Projects""},{""id"":12345000597911,""name"":""foo2""}]}}";
static void Main(string[] args)
{
var theReturn = DeserializeJson(Json);
}
private static AsanaObjects DeserializeJson(string json) {
var jsonSerializer = new DataContractJsonSerializer(typeof(AsanaObjects));
var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
return jsonSerializer.ReadObject(stream) as AsanaObjects;
}
public partial class AsanaObjects
{
[DataContract]
public class Workspace
{
[DataMember]
public object id { get; set; }
[DataMember]
public string name { get; set; }
}
}
public partial class AsanaObjects
{
[DataContract]
public class Data2
{
[DataMember]
public long id { get; set; }
[DataMember]
public string name { get; set; }
[DataMember]
public string email { get; set; }
[DataMember]
public object photo { get; set; }
[DataMember]
public Workspace[] workspaces { get; set; }
}
}
[DataContract]
public partial class AsanaObjects
{
[DataMember]
public Data2 data { get; set; }
}
}
}
</code></pre>
|
syntax error in mysql php code <p>I am stuck in using MySQL insert statement. When i run this statement it does display output but somehow not inserting the data into table. Not able to establish where am I going wrong.</p>
<pre><code>if($app_siblingno=='0'){
$query2 = "INSERT INTO tbl_stu_siblings( fk_stu_id,sib_count,name,dt_dob,class,gender,scl_name) "
. " VALUES ('$stuid','0','', '','','','')";
mysql_query($query2) or die(mysql_error());
echo 'in loop';
</code></pre>
| <p>Try this query;</p>
<pre><code>$query2 = "INSERT INTO tbl_stu_siblings ( fk_stu_id,sib_count,name,dt_dob,class,gender,scl_name) VALUES ('".$stuid."','0','', '','','','')";
</code></pre>
<p>And check your table structure and field type and not null statements.</p>
<p>You should check and try your sql query. If it still dont work, open display error and paste sql error here.</p>
<p>Good luck</p>
|
D3.js: Force-layout - Nodes not rendering with images <p>Currently I am working one of <a href="https://www.freecodecamp.com/challenges/show-national-contiguity-with-a-force-directed-graph" rel="nofollow">FCC' Project</a> and
I am trying to have node render with images from these flag sprites (<a href="https://www.flag-sprites.com/" rel="nofollow">https://www.flag-sprites.com/</a>)</p>
<p>However, my nodes are not rendering, yet I see in my dev tool that are there.</p>
<p><a href="http://codepen.io/neotriz/pen/wzpEjj?editors=1010" rel="nofollow">Codepen - Not Working</a></p>
<pre><code>const width = w - (margin.left + margin.right);
const height = h - (margin.top + margin.bottom);
let svg = d3.select("#canvas")
.append("svg")
.attr("id","chart")
.attr("width", w)
.attr("height", h)
let flagNodes = svg.append("div")
.classed("flag-nodes",true)
// .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
let chart = svg.append("g")
.classed("display", true)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
let simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function(d,i) {
return i;
}))
.force("charge", d3.forceManyBody().strength(-4))
.force("center", d3.forceCenter(width/2, height/2))
let node = flagNodes.append("div")
.selectAll(".flag-nodes")
.data(data.nodes)
.enter()
.append("div")
.attr("class", function(d,i){
return `flag flag-${d.code}`
})
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended)
)
let link = chart.append("g")
.classed("links",true)
.selectAll("line")
.data(data.links)
.enter()
.append("line")
node.append("title")
.text(function(d) { return d.country; });
simulation
.nodes(data.nodes)
.on("tick", ticked);
simulation.force("link")
.links(data.links);
//functions provided by D3.js
//
function ticked() {
link
.attr("x1", function(d) {return d.source.x;})
.attr("y1", function(d) {return d.source.y;})
.attr("x2", function(d) {return d.target.x;})
.attr("y2", function(d) {return d.target.y;});
node
.style("left", function(d) {
// console.log(d)
return d.x + 'px'
})
.style("top", function(d) {
return d.y + 'px'
});
}
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
</code></pre>
| <p>The <code><div></code> elements are added to the HTML document and the links are added to <code><svg></code> element. They do not share the same coordinate system. Unfortunately you cannot add a <code><div></code> to an <code><svg></code>. It is probably easier to use another method for the flags instead of trying to coordinate both systems. You could use separate images for each flag and use <code><img></code> inside the <code><svg></code>.</p>
|
ASP.Net Core solution publishing wrong project <p>I created a new ASP.Net core project and set it up in source control which publishes to Azure when I do a check-in. I was able to get everything setup correctly and it was working fine. </p>
<p>However, I then added a class library project to the solution and now instead of publishing my website project the MSBuild task is attempting to publish my class library which of course fails. </p>
<p>The line in the deployment command is:</p>
<pre><code>"%MSBUILD_PATH%" "%DEPLOYMENT_SOURCE%\MySolution.sln" /nologo /verbosity:m /p:deployOnBuild=True;AutoParameterizationWebConfigConnectionStrings=false;Configuration=Release;UseSharedCompilation=false;publishUrl="%DEPLOYMENT_TEMP%"
</code></pre>
<p>And when that runs it first builds the models project which is fine:</p>
<pre><code> D:\Program Files (x86)\dotnet\dotnet.exe build "D:\home\site\repository\MySolution.Models" --configuration Release --no-dependencies
</code></pre>
<p>But then it attempts to publish that project as well:</p>
<pre><code>D:\Program Files (x86)\dotnet\dotnet.exe publish "D:\home\site\repository\MySolution.Models" --output "D:\local\Temp\PublishTemp\MySolution.Models71" --configuration Release --no-build
D:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\DotNet\Microsoft.DotNet.Publishing.targets(149,5): error : Can not find runtime target for framework '.NETStandard,Version=v1.6' compatible with one of the target runtimes: 'win8-x86, win7-x86'. Possible causes: [D:\home\site\repository\MySolution.Models\MySolution.Models.xproj]
</code></pre>
<p>Which is the wrong project (it should be the web project). I can't seem to find any files that contain the settings for this or the setting in the solution file itself. </p>
<p>What do I need to do for this to publish the correct project?</p>
| <p>I was able to solve this by doing it in two steps. </p>
<p>First remove the deployOnBuild=True and the publishUrl=[snip] from the msbuild command. This means this step will build the project but doesn't do any publishing. </p>
<p>Next add a new step that does the publish. </p>
<p>To do this I first created a new variable to hold the location of the dotnet.exe:</p>
<pre><code>IF DEFINED DOTNET_PATH goto DotNetPathDefined
SET DOTNET_PATH=%ProgramFiles(x86)%\dotnet\dotnet.exe
:DotNetPathDefined
</code></pre>
<p>Then add the following to do the publish of the web project:</p>
<pre><code>call :ExecuteCmd "%DOTNET_PATH%" publish "%DEPLOYMENT_SOURCE%\MySolution.Web" --framework netcoreapp1.0 --output "%DEPLOYMENT_TEMP%" --configuration Release --no-build
IF !ERRORLEVEL! NEQ 0 goto error
</code></pre>
<p>This then publishes all the files to the deployment temp folder which then get deployed using the KuduSync step.</p>
|
How to debug cython in and IDE <p>I am trying to debug a Cython code, that wraps a c++ class, and the error I am hunting is somewhere in the C++ code.</p>
<p>It would be awfully convenient if I could somehow debug as if it were written in one language, i.e. if there's an error in the C++ part, it show me the source code line there, if the error is in the python part it does the same.</p>
<p>Right now I always have to try and replicate the python code using the class in C++ and right now I have an error that only occurs when running through python ... I hope somebody can help me out :)</p>
| <p>It's been a while for me and I forgot how I exactly did it, but when I was writing my own C/C++ library and interfaced it with swig into python, I was able to debug the C code with <a href="https://www.gnu.org/software/ddd/" rel="nofollow">DDD</a>. It was important to compile with debug options. It wasn't great, but it worked for me. I think you had to run <code>ddd python</code> and within the python terminal run my faulty C code. You would have to make sure all linked libraries including yours is loaded with the source code so that you could set breakpoints. </p>
|
r scientific notation limit mantissa decimal points <p>In r, is it possible to limit the number after decimal points of mantissa/significand. E.g 1.43566334245e-9, I want to ignore/round to 1.44e-9.</p>
<p>I do not want to simply say keep N numbers after decimal. Cause if there is another number in the dataset is 5.2340972e-5, I want it to be 5.23e-5 but not 5.234097e-5. So only limiting on mantissa's decimal point, rather than the whole number. </p>
| <p>If I understood you correctly:</p>
<pre><code>signif(1.43566334245e-9,3)
[1] 1.44e-09
signif(5.2340972e-5,3)
[1] 5.23e-05
</code></pre>
|
How to run a 2-layer perceptron to solve XOR <p>XOR is not solvable by using a single perceptron with standard scalar product and unit step function.</p>
<p>This article suggests using 3 perceptron to make a network:
<a href="http://toritris.weebly.com/perceptron-5-xor-how--why-neurons-work-together.html" rel="nofollow">http://toritris.weebly.com/perceptron-5-xor-how--why-neurons-work-together.html</a></p>
<p>I'm trying to run the 3-perceptron network this way but it doesn't produce correct results for XOR:</p>
<pre><code>//pseudocode
class perceptron {
constructor(training_data) {
this.training_data = training_data
}
train() {
iterate multiple times over training data
to train weights
}
unit_step(value) {
if (value<0) return 0
else return 1
}
compute(input) {
weights = this.train()
sum = scalar_product(input,weights)
return unit_step(sum)
}
}
</code></pre>
<p>The above perceptron can solve NOT, AND, OR bit operations correctly. This is how I use 3 perceptrons to solve XOR:</p>
<pre><code>AND_perceptron = perceptron([
{Input:[0,0],Output:0},
{Input:[0,1],Output:0},
{Input:[1,0],Output:0},
{Input:[1,1],Output:1}
])
OR_perceptron = perceptron([
{Input:[0,0],Output:0},
{Input:[0,1],Output:1},
{Input:[1,0],Output:1},
{Input:[1,1],Output:1}
])
XOR_perceptron = perceptron([
{Input:[0,0],Output:0},
{Input:[0,1],Output:1},
{Input:[1,0],Output:1},
{Input:[1,1],Output:0}
])
test_x1 = 0
test_x2 = 1
//first layer of perceptrons
and_result = AND_perceptron.compute(test_x1,test_x2)
or_result = OR_perceptron.compute(test_x1,test_x2)
//second layer
final_result = XOR_perceptron.compute(and_result,or_result)
</code></pre>
<p>The final_result above is not consistent, sometimes 0, sometimes 1. It seems I run the 2 layers wrongly. How to run these 3 perceptrons in 2 layers the correct way?</p>
| <p>If you want to build a neural network with logical connectives (and, or, not), you have to consider the following equivalences regarding xor:</p>
<blockquote>
<p>A xor B ⡠(A ⨠B) ⧠¬(A ⧠B) ⡠(A ⨠B) ⧠(¬A ⨠¬B) ⡠(A ⧠¬B) ⨠(¬A ⧠B)</p>
</blockquote>
<p>So you would need at least three and- or or-perceptrons and one negation if you want to use your perceptrons if I understand them correctly. In the article they use three perceprons with special weights for the xor. These are not the same as and- and or-perceptrons.</p>
|
Shortcut keys for un/comment block of code doesn't work in xcode 8 (suddenly) <p>something weird just happen and can't solve it, the command "Command + /" which I used to un/comment block of codes doesn't work any more. when I hit the command the cursers just disappear for a second and than comeback but doesn't comment or uncomment block of code. I changed the shortcut keys to be something else and tried it but it does the same action which is not commenting or uncommenting the code, what should I do to fix it? </p>
| <p>ok, after install the latest ios update the problem just solved by itself.</p>
|
Getting access to the metaclass in Ruby <p>I'm trying to better understand the rules of Ruby and how to get access to the metaclass. I'm reading Yehuda Katz's article on metaprogramming and I came across this:</p>
<pre><code>matz = Object.new
def matz.speak
"Place your burden to machine's shoulders"
end
matz.class #=> Object
</code></pre>
<p>In fact, matz's "class" is its invisible metaclass. We can even get access to the metaclass:</p>
<pre><code>metaclass = class << matz; self; end
metaclass.instance_methods.grep(/speak/) #=> ["speak"]
</code></pre>
<p>What is going on on this line:</p>
<pre><code>metaclass = class << matz; self; end
</code></pre>
<p>Is that the same as:</p>
<pre><code>matz
self
end
</code></pre>
<p>?</p>
| <blockquote>
<p>What is going on on this line:</p>
<pre><code>metaclass = class << matz; self; end
</code></pre>
</blockquote>
<pre><code>class << foo
</code></pre>
<p>opens the singleton class of <code>foo</code>. Inside a class definition body, <code>self</code> is the class. The return value of a class definition body is the value of the last expression inside the class definition body.</p>
<p>So, we assign the value of the class definition body, which is the value of the last expression inside the class definition body, which is <code>self</code>, which is the class, i.e. the singleton class of <code>matz</code>.</p>
<p>In other words: we assign the singleton class of <code>matz</code> to the local variable <code>metaclass</code>.</p>
<p>Note that modern Ruby has the <a href="http://ruby-doc.org/core/Object.html#method-i-singleton_class" rel="nofollow"><code>Object#singleton_class</code></a> method for that purpose (added in Ruby 1.9.2, released in 2010).</p>
<blockquote>
<p>Is that the same as:</p>
<pre><code>matz
self
end
</code></pre>
</blockquote>
<p>Obviously not, since the former is legal syntax, and this isn't.</p>
|
RestTemplate's postForObject Terminating Immediately After Sending Request <p>I'm trying to send a POST request with the following method, and return the HTTP response code upon sending the request. </p>
<p>Code in question:</p>
<pre><code>private ClientHttpRequestFactory getClientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
clientHttpRequestFactory.setConnectTimeout(timeout);
return clientHttpRequestFactory;
}
public int sendRequest() {
RestTemplate request = new RestTemplate(getClientHttpRequestFactory());
String URL = buildURL();
HttpHeaders headers = buildHeaders();
validatePayload();
HttpEntity<String> postRequest = new HttpEntity<String>(requestPayload, headers);
return request.postForObject(URL, postRequest, ResponseEntity.class).getStatusCodeValue();
}
</code></pre>
<p>I am generating a ClientHttpRequestFactory so I'm able to set a timeout, and eventually sending a POST by using RestTemplate's postForObject. My issue here is that the program immediately terminates (it runs in the command line) upon sending the POST request, and I'm not able to do anything with the response code. I can't find any documentation online saying that this is expected behavior for postForObject, is there something here that I should be doing differently?</p>
<p>Thanks!</p>
| <p>The issue at hand was that postForObject() was returning null. I had an exception catcher later on that was hiding the issue.</p>
<p>I instead used postForEntity, which did not return null, and I was able to get a HTTP Status code using the following block:</p>
<pre><code>ResponseEntity<String> re = request.postForEntity(URL, postRequest, String.class);
HttpStatus status = re.getStatusCode();
statusCode = status.value();
</code></pre>
|
Grep search certain characters any order any capitalization <p>I need to grep search for the characters "james". The problem is they can be in any order and any of them can be capitalized. For example the following would need to be found..</p>
<ul>
<li><em>Aemjs</em></li>
<li><em>emaJS</em></li>
<li><em>SeMaJ</em></li>
</ul>
<p>That's just a few possibilities, obviously there are many more combinations.</p>
<p>If possible this needs to be done with one grep statement. The grep search is being done with the software Encase and not on a unix machine. The input only accepts one grep command. Is it possible to do this in one statement?</p>
| <p>Here's a fun regex for you:</p>
<pre><code>/ (?=.{0,4}j)(?=.{0,4}a)(?=.{0,4}m)(?=.{0,4}e)(?=.{0,4}s).{5} /i
</code></pre>
<p>What this'll do is look ahead to ensure that each character in the string "james" is matched within the next 5 characters, and the <code>i</code> modifier makes it case-insensitive.</p>
<p><a href="https://regex101.com/r/UxexNF/2" rel="nofollow">Demo on Regex101</a></p>
<p>Putting it into <code>grep</code>, you get something like this:</p>
<pre><code>grep -Pi " (?=.{0,4}j)(?=.{0,4}a)(?=.{0,4}m)(?=.{0,4}e)(?=.{0,4}s).{5} " $file
</code></pre>
<p>Where <code>$file</code> is the file you want to <code>grep</code> through. Note that the <code>-P</code> flag requires GNU <code>grep</code>, and indicates that the pattern is a Perl-style regex (native <code>grep</code> regexes, even with <code>-E</code>, don't support lookaheads). The <code>-i</code> flag makes it case-insensitive.</p>
|
Django : form validation in client side? <p>I have two questions.</p>
<ol>
<li>I made certain <code>view</code> accept <code>POST</code> request only through <code>ajax</code>(Not general <code>POST</code> request)</li>
</ol>
<p>I'm using <code>Form</code> and realized that If I used <code>ajax</code>, I could not use django built-in form validation. </p>
<p>In this case, do I have to make my own validation for all fields in <code>javascript</code>?. I think that it is kinda time-consuming and redundant thing. Any alternatives?</p>
<p><br>
2. Is it ok for <code>view</code> to accept only <code>ajax</code> POST request? I mean, I do something like this:<br></p>
<pre><code>def post(self, request, *args, **kwargs):
if request.is_ajax():
# return response
else:
# give HTTP404
</code></pre>
<p>Is it bad practice? Once the <code>view</code> accept <code>ajax</code> request, does it always accept general HTTP request, too?</p>
<p>Thanks.</p>
| <p>Generate the form HTML in a separate template. When you submit with ajax, if the form is invalid, i.e. form.is_invalid() then instantiate the form with request.POST and render the template again. Then, return this rendered HTML back to your Ajax function and replace the existing form. </p>
<p>This will prevent having to fiddle around with JS a lot.</p>
|
Unity Errors after Update <p>I updated Unity today and i get 2 errors from times to times. I am pretty sure there are not from my scripts. How can i fix them?</p>
<pre><code>SUCCEEDED(hr)
rc.right == m_GfxWindow->GetWidth() && rc.bottom == m_GfxWindow->GetHeight()
</code></pre>
| <p>This is a known bug from Unity. </p>
<p>Re-Import the Project from the Editor.</p>
<p><strong>Assets</strong> -> <strong>Reimport All</strong>.</p>
<p>Then from MonoDevelop go to <strong>Build</strong>-><strong>Clean All</strong> and then <strong>Build</strong> -> <strong>Rebuild All</strong>. </p>
<p>Close and restart Unity and MonoDevelop.</p>
|
Unexpected result while sorting using if loops - Bad Algorithm <p>The objective of my program is to read randomized data of runners and their speeds from a text file and organize it into First, Second and Third. It has their names, bib, age, gender and m:s. However, in this program I cannot use STL/Arrays etc and am limited to ints, doubles and strings. </p>
<p>The code compares the pace of the runners. Here is one of the algorithms I've used</p>
<pre><code>int pace_f = 100000;
int pace_s = 100000;
int pace_t = 100000;
if ((pace < pace_t) && (pace > pace_s))
{
name_t = name;
min_t = min;
sec_t = sec;
pace_t = pace;
}
if ((pace < pace_s) && (pace > pace_f))
{
name_s = name;
min_s = min;
sec_s = sec;
pace_s = pace;
}
if (pace < pace_f)
{
name_f = name;
pace_f = pace;
}
</code></pre>
<p>The error is in the output where it displays the First and Second positions correctly. However, it sometimes either fails to print out the third position or provides a wrong one. I understand it does this because it compares the value of the first time that is passed to the loop and since it is always under 10,000 it sets it as the 3rd best time. Now, when a better time comes along, it replaces the one in the third place because it meets all other conditions. The program runs correctly when the first three pace values passed are in ascending order. </p>
<p>So my question is this - How can I correct the error so that it works without needing your numbers to be in ascending order because otherwise this is just pointless.</p>
| <p>I'll point out the logical problem with this part of your existing code:</p>
<pre><code> if (pace < pace_f)
{
name_f = name;
pace_f = pace;
}
</code></pre>
<p>Your other <code>if</code> statements have the same problem, but it's easier to explain the problem here, and then you can apply the same fix to all the others.</p>
<p>Here you've decided that your next pace level is better than the current first place finish. Now, it is true that <code>pace</code>, the current record, is now the first place pace, and you need to update <code>name_f</code> and <code>pace_f</code>, the first place records accordingly.</p>
<p>But the detail that you missed is that your current first place pace is now your second best pace, and your current second place pace is now your third best pace.</p>
<p>You just found a record with a pace that's better than your top three paces, so this must mean that your existing best is now the second best, and your existing second best is now your third best.</p>
<p>So, before you can update your first best's pace and name, you need to move your existing second place name and pace to the third place name and pace; your existing first place name and pace to the second place name and pace; and only after that's done, you can update your first place name and pace.</p>
<p>Additionally, you can simply the comparisons by rearranging their relative order with each other.</p>
<p>If you can compare the first place pace first, then the <code>else</code> part can then be used to test the remaining possibilities. Once you've excluded the possibility that you have the best first pace, it's simpler to test the remain possibilities.</p>
<p>Your overall logic should be:</p>
<pre><code>if (pace < pace_f)
{
// Move the second place name+pace to third place
// Move the first place name+pace to the second place
// Set the new first place pace.
}
else if (pace < pace_s)
{
// Move the second place name+pace to third place
// Set the new second place pace.
}
else if (pace < pace_t)
{
// Set the new third place pace.
}
</code></pre>
<p>That's it.</p>
|
Finding asymptotic upper and lower bound? <p>If we assume T(n) is constant for small n, how can we find the solution of this function?</p>
<pre><code>T(n) = T(nâ2) + 2logn
</code></pre>
<p>So far, I am unable to find a way to represent the whole function. Can you please help me? I really want to understand. </p>
| <p>Assuming n is even, and that <code>T(1) = T(0) = 0</code>.</p>
<pre><code>T(n)/2 = log(n) + log(n-2) + ... + log(2)
= log((n/2)! * 2^n)
= n log(2) + log((n/2)!)
= n log(2) + n log(n) - n + O(log(n)) (Stirling's approximation)
</code></pre>
<p>So for <code>n</code> even, <code>T(n) = Theta(n log(n))</code>.</p>
<p>For <code>n</code> odd, you can note that <code>T(n-1) < T(n) < T(n+1)</code>, and get the same asymptotic bound.</p>
|
jQuery .find() using parent id <p>I am trying to find the value of an input statement that does not have an id.</p>
<p>The html is: </p>
<pre><code><td id="LastName">
<input type="text" value="Abner">
</td>
</code></pre>
<p>The jQuery code I am trying to use is:</p>
<pre><code>var name = $('#LastName').find('input').value
</code></pre>
<p>But it keeps coming up empty. I thought I had read about .find() properly, but apparently not.</p>
<p>Anyone see my error?</p>
| <p>As DelightedD0D commented, <code>.val()</code> is the correct way to retrieve a value from a text input.</p>
<p>Here's a working snippet: <a href="https://jsfiddle.net/tuywqucb/3/" rel="nofollow">https://jsfiddle.net/tuywqucb/3/</a></p>
<p>One other thing to look out for.. if the <code>td</code> isn't correctly wrapped in a <code>tr</code> and a <code>table</code> tag, many browsers will omit it from the DOM which will make your element and thus your id disappear and thus not be found by jQuery.</p>
|
PHP array detect if it contains unique value <p>I have some PHP arrays that looks like this...</p>
<pre><code>$cars1 = array("Volvo", "Volvo", "Volvo");
$cars2 = array("Volvo", "BMW", "Toyota");
$cars3 = array("Volvo");
$cars4 = array("Volvo", "BMW", "Volvo");
$cars5 = array("BMW", "Toyota");
</code></pre>
<p>I need to detect when an array contains all Volvo's or only one Volvo on it's own. So in the examples above only $cars1 and $cars3 would pass.</p>
<p>Anyone have a similar example I can see?</p>
| <p>you're proably looking for something like <a href="https://repl.it/DqW7" rel="nofollow">this</a></p>
<pre><code>function arrayEq($array,$val)
{
foreach($array as $item)
{
if($item != $val)
{
return false;
}
}
return true;
}
$cars1 = array("Volvo", "Volvo", "Volvo");
$cars2 = array("Volvo", "BMW", "Toyota");
$cars3 = array("Volvo");
$cars4 = array("Volvo", "BMW", "Volvo");
$cars5 = array("BMW", "Toyota");
var_dump(arrayEq($cars1,"Volvo"));
var_dump(arrayEq($cars2,"Volvo"));
var_dump(arrayEq($cars3,"Volvo"));
var_dump(arrayEq($cars4,"Volvo"));
var_dump(arrayEq($cars5,"Volvo"));
</code></pre>
<p>what the function does is loops though the passed array with a for each and with each item in the array it compares it to the comparing value we passed in.</p>
<p>if even one item in the array doesn't match the comapring value we return false. this breaks out of the loop as well. if the loop can goes all the way though then we know that all the values are the same and return true</p>
<p>note that this is case sensitive ss <code>"Volvo" != "volvo"</code> but you can fix this with something like <a href="http://php.net/manual/en/function.strtoupper.php" rel="nofollow"><code>strtoupper</code></a> or <a href="http://php.net/manual/en/function.strtolower.php" rel="nofollow"><code>strtolower</code></a></p>
|
Custom unwind segue animation display issue <p>I'm doing my first custom segue animations. What I want is to have a list view that when I select on a row, instead of sliding in from the side, it expands in place from the row selected. Something like:</p>
<p><a href="http://i.stack.imgur.com/gCcME.png" rel="nofollow"><img src="http://i.stack.imgur.com/gCcME.png" alt="enter image description here"></a></p>
<p>So the user selects the green row, which causes the new controller to start at the green row size and expand to fill the screen. This part has worked fine so far.</p>
<p>The problem I'm having is with the unwind segue which seeks to do the opposite, shrink the full screen back to the original row and then dismiss. What happens is that it shrinks fine, but the area exposed remains black, and then suddenly flashes into place when the animation is done. What is wanted is something like this:</p>
<p><a href="http://i.stack.imgur.com/iu8I2.png" rel="nofollow"><img src="http://i.stack.imgur.com/iu8I2.png" alt="enter image description here"></a></p>
<p>But what is happening is more like this:</p>
<p><a href="http://i.stack.imgur.com/lihg3.png" rel="nofollow"><img src="http://i.stack.imgur.com/lihg3.png" alt="enter image description here"></a></p>
<p>The code I'm using for the unwind's <code>perform</code> looks like:</p>
<pre><code>class FromScheduleFocusSegue: UIStoryboardSegue {
override func perform() {
let fromView = self.source.view!
let toView = self.destination.view!
let window = UIApplication.shared.keyWindow!
let schedulesList = self.destination as! SchedulesListController
let cell = schedulesList.tableView.cellForRow(at: schedulesList.tableView.indexPathForSelectedRow!)!
var stripe = cell.bounds
stripe.size.height = 60
let targetFrame = cell.convert(stripe, to: window).insetBy(dx: 0, dy: 0)
schedulesList.tableView.selectRow(at: nil, animated: false, scrollPosition: .none)
UIView.animateWithDuration(4000.milliseconds, delay: 0.seconds, options: .curveEaseInOut, animations: {
fromView.frame = targetFrame
}) { (finished) in
self.source.dismiss(animated: false, completion: nil)
}
}
}
</code></pre>
<p>So basically, how do I get the view that I'm unwinding to to show up as the animation is taking place?</p>
<p>For completeness sake, here's the forward segue code:</p>
<pre><code>class ToScheduleFocusSegue: UIStoryboardSegue {
override func perform() {
let fromView = self.source.view!
let toView = self.destination.view!
let window = UIApplication.shared.keyWindow!
let box = UIScreen.main.bounds
let schedulesList = self.source as! SchedulesListController
let cell = schedulesList.tableView.cellForRow(at: schedulesList.tableView.indexPathForSelectedRow!)!
toView.frame = cell.convert(cell.bounds, to: window).insetBy(dx: 0, dy: 0)
window.insertSubview(toView, aboveSubview: fromView)
UIView.animateWithDuration(4000.milliseconds, delay: 0.seconds, options: .curveEaseInOut, animations: {
toView.frame = box
}) { (finished) in
self.source.present(self.destination, animated: false, completion: nil)
}
}
}
</code></pre>
<p>(This is in XCode8, targeted at iOS10 using Swift3)</p>
| <p>Try having the view controller that does the presentation also do the dismiss.</p>
<p>So in your unwind segue:</p>
<pre><code>UIView.animateWithDuration(4000.milliseconds, delay: 0.seconds, options: .curveEaseInOut, animations: {
fromView.frame = targetFrame
}) { (finished) in
self.destination.dismiss(animated: false, completion: nil) // the destination is the one that presented the current view
}
</code></pre>
|
Spring Boot + Jetty + Jersey won't start up: `Creation of FactoryDescriptors must have Factory as a contract of the first argument` <p>Unable to start a Spring Boot app using the embedded Jetty servlet container and Jersey. I'm using Spring Boot version 1.4.1.</p>
<p>Here is the error message:</p>
<p><code>Creation of FactoryDescriptors must have Factory as a contract of the first argument</code></p>
<p>Here is the full stack trace:</p>
<pre><code> org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Jetty servlet container
at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.start(JettyEmbeddedServletContainer.java:143) ~[spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.startEmbeddedServletContainer(EmbeddedWebApplicationContext.java:297) ~[spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:145) ~[spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at com.example.MyApplication.main(MyApplication.java:14) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_40]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_40]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_40]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_40]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.4.1.RELEASE.jar:1.4.1.RELEASE]
Caused by: javax.servlet.ServletException: com.example.config.JerseyConfig@c2666de==org.glassfish.jersey.servlet.ServletContainer,-1,false
at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:661) ~[jetty-servlet-9.3.11.v20160721.jar:9.3.11.v20160721]
at org.eclipse.jetty.servlet.ServletHolder.initialize(ServletHolder.java:419) ~[jetty-servlet-9.3.11.v20160721.jar:9.3.11.v20160721]
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:875) ~[jetty-servlet-9.3.11.v20160721.jar:9.3.11.v20160721]
at org.springframework.boot.context.embedded.jetty.JettyEmbeddedWebAppContext$JettyEmbeddedServletHandler.deferredInitialize(JettyEmbeddedWebAppContext.java:46) ~[spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.context.embedded.jetty.JettyEmbeddedWebAppContext.deferredInitialize(JettyEmbeddedWebAppContext.java:36) ~[spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.handleDeferredInitialize(JettyEmbeddedServletContainer.java:186) ~[spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.start(JettyEmbeddedServletContainer.java:121) ~[spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
... 15 common frames omitted
Caused by: java.lang.IllegalArgumentException: Creation of FactoryDescriptors must have Factory as a contract of the first argument
at org.glassfish.hk2.utilities.FactoryDescriptorsImpl.<init>(FactoryDescriptorsImpl.java:78) ~[hk2-api-2.5.0-b05.jar:na]
at org.glassfish.hk2.utilities.binding.AbstractBindingBuilder$FactoryTypeBasedBindingBuilder.complete(AbstractBindingBuilder.java:454) ~[hk2-api-2.5.0-b05.jar:na]
at org.glassfish.hk2.utilities.binding.AbstractBinder.resetBuilder(AbstractBinder.java:180) ~[hk2-api-2.5.0-b05.jar:na]
at org.glassfish.hk2.utilities.binding.AbstractBinder.complete(AbstractBinder.java:190) ~[hk2-api-2.5.0-b05.jar:na]
at org.glassfish.hk2.utilities.binding.AbstractBinder.bind(AbstractBinder.java:174) ~[hk2-api-2.5.0-b05.jar:na]
at org.glassfish.jersey.model.internal.CommonConfig.configureBinders(CommonConfig.java:676) ~[jersey-common-2.23.2.jar:na]
at org.glassfish.jersey.model.internal.CommonConfig.configureMetaProviders(CommonConfig.java:654) ~[jersey-common-2.23.2.jar:na]
at org.glassfish.jersey.server.ResourceConfig.configureMetaProviders(ResourceConfig.java:829) ~[jersey-server-2.23.2.jar:na]
at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:453) ~[jersey-server-2.23.2.jar:na]
at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:184) ~[jersey-server-2.23.2.jar:na]
at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:350) ~[jersey-server-2.23.2.jar:na]
at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:347) ~[jersey-server-2.23.2.jar:na]
at org.glassfish.jersey.internal.Errors.process(Errors.java:315) ~[jersey-common-2.23.2.jar:na]
at org.glassfish.jersey.internal.Errors.process(Errors.java:297) ~[jersey-common-2.23.2.jar:na]
at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:255) ~[jersey-common-2.23.2.jar:na]
at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:347) ~[jersey-server-2.23.2.jar:na]
at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:392) ~[jersey-container-servlet-core-2.23.2.jar:na]
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:177) ~[jersey-container-servlet-core-2.23.2.jar:na]
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:369) ~[jersey-container-servlet-core-2.23.2.jar:na]
at javax.servlet.GenericServlet.init(GenericServlet.java:244) ~[javax.servlet-api-3.1.0.jar:3.1.0]
at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:640) ~[jetty-servlet-9.3.11.v20160721.jar:9.3.11.v20160721]
... 21 common frames omitted
</code></pre>
| <p>I solved this by upgrading HK2 to version <code>2.5.0-b22</code>.</p>
|
MVC5 return status 500 custom page, tried normal solutions <p>I want to be able to control a redirect to a different page or return a different view on certain handled errors. I can create custom pages with status 404, 403, 418, and it displays the page fine, but when I try to return 500 it overrides it with a default page. I've tried the normal solutions. Using TrySkipIisCustomErrors to get by IIS intercepting the 500 error. I have no filter.cs and register no filters in application_Start(). I've tried adding and removing [HandleError] from the method and that doesn't make a difference.</p>
<pre><code>[NonAction]
[HandleError]
private ActionResult error(Exception e)
{
Response.StatusCode = 500;
Response.StatusDescription = "Internal server error: " + e.Message;
Response.TrySkipIisCustomErrors = true;
ErrorModel errorModel = new ErrorModel();
errorModel.error = e.Message;
return View(viewName: "error", model: errorModel);
}
</code></pre>
<p>That's the method that the error is redirected to and returns the view to be displayed. I can change the first line to other StatusCodes and it works fine, but 500 doesn't.</p>
| <p>Turns out it was a weird fluke with Razor. The RenderBody() adds <code><body></code> tags if none are in the document, apparently unless you return 500 in your status header. Then it doesn't add the <code><body></code> tags, and the HTML returns malformed which was causing my problem.</p>
|
Excel VBA address of FIRST INSTANCE instead of address of each location of value <p>I have a few employee numbers listed in Sheet1 of a workbook. There are a few other sheets (lets call these sheets A, B, C, D, etc) in the workbook that contain the employee number with some info (maybe dates worked). If an employee number is found in, lets say, worksheet A, it will not be in any other worksheet, but it may appear multiple time within worksheet A.</p>
<p>I wrote some VBA that will look in all other worksheets for the employee number listed in Sheet1 and return the cell location of where that employee number is found. Employee numbers are listed in column A, starting at A2 and it listls the location of where the number is found to the right of the employee number.
<a href="http://i.stack.imgur.com/PqNPH.png" rel="nofollow">How Sheet1 looks</a>
<a href="http://i.stack.imgur.com/eETWQ.png" rel="nofollow">Sheet "A"</a></p>
<p>Right Now, when I run my VBA Macro, it will list all the cell location of where that employee number is found, but what i want it do it is give me the cell location of only the FIRST INSTANCE of that employee number. Then, move on to the next employee number listed in colmn A of Sheet1. This is the VBA I have so far.</p>
<pre><code>Sub makeMySearch()
Dim ws As Worksheet, lastrow As Long
For Each cell In Sheets("Sheet1").Range("A2:A" & Sheets("Sheet1").Range("A1").End(xlDown).Row)
recFound = 0
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Sheet1" Then
lastrow = Sheets(ws.Name).Range("A1").End(xlDown).Row
For Each cell2 In Sheets(ws.Name).Range("A1:A" & lastrow)
If InStr(cell2.Value, cell.Value) <> 0 Then
recFound = recFound + 1
cell.Offset(0, recFound) = Split(cell2.Address, "$")(1) & Split(cell2.Address, "$")(2)
End If
Next cell2
End If
Next ws
Next cell
MsgBox "Done Finding!"
End Sub
</code></pre>
| <p>This method will stop on the first find (via the <code>Exit For</code>)</p>
<p>It also shows a more efficient method rather than looping all the cells on each sheet</p>
<pre><code>Sub makeMySearch()
Dim cell As Range, cell2 As Range
Dim ws As Worksheet, lastrow As Long, recFound As Long
Dim rw As Variant
Dim dat As Variant, i As Long
With Worksheets("Sheet1")
dat = .Range(.Cells(2,1), .Cells(.Rows.Count,1).End(xlUp)).Value
For i = 1 To UBound(dat, 1)
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Sheet1" Then
rw = Application.Match( dat(i, 1) , ws.Columns(1), 0)
If Not IsError(rw) Then
.Cells(i+1, 2) = "A" & rw
' Option: show Sheet name and cell
'.Cells(i+1, 2) = ws.Name & "!A" & rw
Exit For
End If
End If
Next ws
Next
End With
MsgBox "Done Finding!"
End Sub
</code></pre>
|
New string list shuffles order of list elements on initialization in LINQ <p>After running into some frustrations with my ASP.NET 5 API project I decided to rebuild it as an older WebApi 2 project. I'm trying to generate a list of collections of 2 strings (originally a list of a 2 element string array, now a list of list of strings) from a LINQ query.</p>
<p>Here is the pseudocode that worked as I wanted it to in the ASP.NET 5 project:</p>
<pre><code>var testList = db.MyTable.Where(x => [WHERE Clauses]).Select(x => new string[] { x.Number.Trim(), x.Name.Trim() }).ToList();
</code></pre>
<p>The new project choked on the query citing it didn't like using string arrays for whatever reason (I'm assuming difference in EF 6 vs 7?). As a fix I instead had the query return a list of string lists but it mixes up the order of the "Number" and "Name" fields it returns, sometimes the Number is the first element and other times the Name is. Here is some new query code attempts I tried that all ended up with the jumbled element order:</p>
<pre><code>var testList = db.MyTable.Where(x => [WHERE Clauses]).Select(x => new List<string> { x.Number.Trim(), x.Name.Trim() }).ToList();
var testList = db.MyTable.Where(x => [WHERE Clauses]).Select(x => (new string[2] { x.Number.Trim(), x.Name.Trim() }).ToList()).ToList();
var testList = db.MyTable.Where(x => [WHERE Clauses]).Select(x => new List<string>(new string[] { x.Number.Trim(), x.Name.Trim() })).ToList();
</code></pre>
<p>I realize there are a ton of different ways to get the end result I'm looking for but I'm hoping someone can help me understand why these list elements would be placed in the list in differing orders (sometimes Name then Number other times Number then Name), even when I generate a list based on a newly created array which preserved the order perfectly previously.</p>
| <p>I'd be curious to see what SQL is generated for those queries and whether or not it changes when your result changes. Selecting a List to me seems like a pretty rare situation, so it's possible you have run into an edge-case (or at least into undefined behavior territory).</p>
<p>Since you're still essentially just selecting two columns, we can worry about how the data is structured after Entity Framework has finished it's work</p>
<pre><code>db.MyTable.Where(x => [WHERE Clauses])
.Select(x => new { Number = x.Number.Trim(), Name = x.Name.Trim() })
.AsEnumerable() //Force EF to materialize the result here
.Select(x => new List<string> { x.Number, x.Name }) //Manipulate the result in memory
.ToList();
</code></pre>
|
WPF DataGridComboBoxColumn Edit on Key press <p>I have a datagrid with a <code>DataGridComboBoxColumn</code> in it.</p>
<p>I want my users to be able to enter edit mode by just typing.<br>
This is the default behavior for <code>DataGridTextColumn</code> and I don't like that they have to press F2 in order to enable editing for just this column type.</p>
<p>How can I make the <code>DataGridComboBoxColumn</code> enter edit mode without them needing to press F2? Ideally on Key Press, but I would be fine if it entered edit mode on focus as well.</p>
<p><strong>Solution</strong>
Modifications to the accepted answer that bring back the basic functionality of the datagrid:</p>
<pre><code> void Cell_PreviewKeyDown(object sender, KeyEventArgs e)
{
if(e.Key == Key.Enter || e.Key == Key.Tab)
{
dgBins.CommitEdit();
dgBins.SelectedIndex += 1;
}else if(e.Key.ToString().Length == 1
|| (e.Key.ToString().StartsWith("D") && e.Key.ToString().Length == 2)
|| e.Key.ToString().StartsWith("NumPad")
|| e.Key == Key.Delete
|| e.Key == Key.Back )
{
if (e.OriginalSource is DataGridCell)
{
DataGridCell cell = (sender as DataGridCell);
Control elem = FindChild<Control>(cell, null);
elem.Focus();
}
}
}
</code></pre>
| <p>You can try to use <code>SelectedCellsChanged</code> event. It works on focus changing. </p>
<p>If you don't want that behaviour on other columns you can check <code>e.AddedCells[0].Column</code> property (if your <code>SelectionUnit="Cell"</code> of <code>DataGrid</code>).</p>
<pre><code>private void dgTest_SelectedCellsChanged( object sender, SelectedCellsChangedEventArgs e )
{
( sender as DataGrid ).BeginEdit();
}
</code></pre>
|
Pattern Is Matching Every Other Line Of Input <p>Here is the pattern I have:</p>
<pre><code>\s+\d+:\s+(?<local>\d+)[-][>]\s+?(?<remote>\d+)\s+(?<wwn>..:..:..:..:..:..:..:..)\s+\d+\s+(?<name>\w+)\s+[s][p]:\s+\w+.\w+\s+\w+[:]\s+\d.\w+\s+(?<trunk>TRUNK)?
</code></pre>
<p>Here is the input. The '*' is not part of the input, it's just designating what is matched. I'm testing this at RegExStorm.net. I don't think the every other line is significant by itself, different input didn't follow with matching every other line. I can't see what's different, if anything between the matched and non-match lines except for the line that says QOS but the match should still succeed there, it would just throw that away.</p>
<pre><code> * 1: 0-> 11 10:00:00:05:1e:89:ed:8c 14 SAN009B sp: 8.000G bw: 8.000G
2: 23-> 2 50:00:51:e8:b9:1b:ae:01 3 fcr_fd_3 sp: 8.000G bw: 8.000G
* 3: 24-> 22 10:00:00:05:1e:36:5b:ea 1 SAN001B sp: 4.000G bw: 4.000G TRUNK
4: 38-> 38 10:00:00:05:1e:e2:45:00 9 SAN004B sp: 8.000G bw: 24.000G TRUNK QOS
*5: 48-> 15 10:00:00:05:1e:89:ed:8c 14 SAN009B sp: 8.000G bw: 8.000G
6: 49-> 10 10:00:00:05:1e:87:5a:e4 13 SAN013B sp: 8.000G bw: 8.000G
*7: 56-> 3 10:00:00:05:1e:84:15:dc 11 SAN011B sp: 8.000G bw: 8.000G
8: 64-> 16 10:00:00:05:1e:89:ed:8c 14 SAN009B sp: 8.000G bw: 8.000G
* 9: 65-> 18 10:00:00:05:1e:87:5a:e4 13 SAN013B sp: 8.000G bw: 8.000G
10: 72-> 63 10:00:00:05:1e:84:15:dc 11 SAN011B sp: 8.000G bw: 8.000G
*11: 87-> 27 50:00:51:e8:b9:1b:ae:01 3 fcr_fd_3 sp: 8.000G bw: 8.000G
</code></pre>
| <p>That's because of this part: <code>\d.\w+</code></p>
<p>The corresponding part for the other number is <code>\w+.\w+</code></p>
<p><code>24</code> (from the <code>24.000G</code> substring) does not fit the <code>\d</code>, so you either should use <code>\d+</code> or <code>\w+</code>.</p>
<p>Another note, in this excerpt it you want to use the dot literal as-is, you need to escape it as <code>\.</code>, since otherwise it matches <code>any character</code>.</p>
<p>How I found your problem: I opened it on <a href="https://regex101.com/" rel="nofollow">https://regex101.com/</a> and removed the parts from the regular expression until it matched, then it was immediately obvious.</p>
|
Getting DHCP Scope Options using Powershell 2.0 <p>I need to get the DHCP scope option values using Powershell 2.0 on Windows Server 2003 R2 SP2.
I don't have access to the Get-DhcpServerv4OptionValue commandlet since that's only available on Windows Server 2012 R2.</p>
<p>How can I get the DHCP scope option values without using the Get-Dhcp commandlets?</p>
| <p>You may do this <a href="https://social.technet.microsoft.com/Forums/en-US/66210404-e80c-4077-987f-84f8fc92eac8/monitor-dhcp-server-statistics-via-wmi?forum=winserverpowershell" rel="nofollow">via WMI</a> or use <code>net.exe</code> and then parse the text in PowerShell where needed</p>
|
Condition inside a count -SQL <p>I am trying to write a condition inside a count statement where it should only count the entries which do not have an ENDDATE. i am looking for writing the condition inside the count as this is a very small part of a large SQl Query</p>
| <p>sample query,</p>
<p>select product, count(*) as quantity</p>
<p>from table</p>
<p>where end_date is null</p>
<p>group by age</p>
<p>This query lists quantity for each product which do not have an end date</p>
|
Where to place .erl & .hrl files in phoenix project? <p>I have phoenix project and am going to use soap request. for that purpose I've generated stubs from wsdl as described <a href="https://medium.com/@larryweya/soap-in-elixir-with-soap-64400c585f69#.9uqcwrb9f" rel="nofollow">here</a>.
The question is where to put auto-generated .erl and .hrl client modules within phoenix project?</p>
| <p><code>erl</code> files should go in any directory present in the <code>erlc_paths</code> config, and <code>hrl</code> in the one in specified by <code>erlc_include_path</code> config. <a href="https://github.com/elixir-lang/elixir/blob/c16f54c6adc147a4bc84922097852b2062eedd96/lib/mix/lib/mix/project.ex#L552-L553" rel="nofollow">The default value of <code>erlc_paths</code> is <code>["src"]</code> and of <code>erlc_include_path</code> is <code>"include"</code></a>, so you can simply place the <code>.erl</code> file(s) in <code>/src</code> and <code>.hrl</code> file(s) in <code>/include</code> and they will be compiled by <code>mix</code> and available in your Elixir code.</p>
|
Redefinition of class constructor error <p>I am trying to compile my code and I keep getting the error: </p>
<blockquote>
<p>redefinition of 'SimpleDate::SimpleDate(int, int, int)</p>
</blockquote>
<p>I think the error is usually because of not adding <code>#ifndef</code>, <code>#define</code>, and <code>#endif</code> but I did add those.</p>
<p>simple_date.h:</p>
<pre><code>#ifndef SIMPLE_DATE_H
#define SIMPLE_DATE_H
#include <string>
class SimpleDate
{
int _year, _month, _day;
public:
// create a new 'SimpleDate' object with the given year, month, and day
// throws an invalid_argument error if the date is invalid
SimpleDate(int year, int month, int day) {};
// returns the current year
int year() const { return 0; };
// returns the current month
int month() const { return 0; };
// returns the current day of the month
int day() const { return 0; };
// return string formatted as year-month-day with day an month 0 prefixed
// i.e. 2000-01-01 is Jan 01, 2000
std::string to_string() const { return ""; };
// comparison operators
bool operator==(const SimpleDate& lhs) const { return true; };
bool operator!=(const SimpleDate& lhs) const { return true; };
bool operator> (const SimpleDate& lhs) const { return true; };
bool operator< (const SimpleDate& lhs) const { return true; };
bool operator>=(const SimpleDate& lhs) const { return true; };
bool operator<=(const SimpleDate& lhs) const { return true; };
// returns 'true' if current year is a leap year
bool is_leap() const { return true; };
// returns the day of the week; 0 = Sunday
// HINT: To calculate the day of the week, you need to have a known day. Use
// 1970-01-01 which was a Thursday. Make sure to reference where you found
// the algorithm or how you came up with it.
int wday() const { return 0; };
// returns the day of the year; Jan 1st = 1
int yday() const { return 0; };
// add one day to current date
SimpleDate& incr_day() { SimpleDate dd {2016, 1, 1}; };
SimpleDate& operator++() { SimpleDate dd {2016, 1, 1}; };
// add n day(s) to current date
SimpleDate& operator+=(int n) { SimpleDate dd {2016, 1, 1}; };
// subtract one day from current date
SimpleDate& decr_day() { SimpleDate dd {2016, 1, 1}; };
SimpleDate& operator--() { SimpleDate dd {2016, 1, 1}; };
// subtract n day(s) from current date
SimpleDate& operator-=(int n) { SimpleDate dd {2016, 1, 1}; };
// add one month to current date
SimpleDate& incr_month() { SimpleDate dd {2016, 1, 1}; };
// subtract one month from current date
SimpleDate& decr_month() { SimpleDate dd {2016, 1, 1}; };
// add one year to current date
SimpleDate& incr_year() { SimpleDate dd {2016, 1, 1}; };
// subtract one year from current date
SimpleDate& decr_year() { SimpleDate dd {2016, 1, 1}; };
// returns 'true' if current date is a Monday
bool is_monday() const { return true; };
// returns 'true' if current date is a Tuesday
bool is_tuesday() const { return true; };
// returns 'true' if current date is a Wednesday
bool is_wednesday() const { return true; };
// returns 'true' if current date is a Thursday
bool is_thursday() const { return true; };
// returns 'true' if current date is a Friday
bool is_friday() const { return true; };
// returns 'true' if current date is a Saturday
bool is_saturday() const { return true; };
// returns 'true' if current date is a Sunday
bool is_sunday() const { return true; };
};
#endif
</code></pre>
<p>simple_date.cpp:</p>
<pre><code>#include "simple_date.h"
SimpleDate::SimpleDate(int year, int month, int day)
{
std::cout >> year;
if (year < 1970 || year > 2020)
{
throw invalid_argument("Don't care about years less than 1970 or greater than 2020");
}
else
{
_year = year;
}
if (month < 1 || month > 12)
{
throw invalid_argument("Not a real month");
}
else
{
_month = month;
}
if (day < 1 || day>31)
{
throw invalid_argument("Not a real day");
}
else if ((_month == 2 || _month == 4 || _month == 6 || _month == 9 || _month == 11) && day > 30)
{
throw invalid_argument("Not a real day for this month");
}
else if (_month == 2 && day == 29)
{
if (this.is_leap())
_day = day;
else
hrow invalid_argument("Not a real day for this month and year");
}
else
_day = day;
}
</code></pre>
| <p>You defined the constructor in the header file, here:</p>
<pre><code>SimpleDate(int year, int month, int day) {};
</code></pre>
<p>Those innocent-looking braces turned this declaration into a definition. And then compiler got very upset when it later encountered the real definition of this constructor. Just remove them:</p>
<pre><code>SimpleDate(int year, int month, int day);
</code></pre>
|
Putting result of foreach loop into a variable <p>i have a foreach loop that will convert each letter of a word to a number, then converting it into a binary.</p>
<p>for example:</p>
<ul>
<li>word= abc,</li>
<li>equivalent number: 0 1 3,</li>
<li>then convert it into binary: 00000 00001 00010</li>
</ul>
<p>im having a hardtime getting that result, but when i do, i only get the value of the last letter.</p>
<pre><code>static void Main(string[] args)
{
string result;
string a, aa=null;
Console.Write("INSERT TEXT:");
a = Console.ReadLine();
char[] array = a.ToCharArray();
foreach (char let in array)
{
int index = char.ToUpper(let) - 65;//index == 1
int num = index; //int to binary
result = Convert.ToString(num, 2).PadLeft(5, '0');
aa = result;
Console.Write(aa); //all the converstions display correctly
}
Console.ReadLine();
Console.Write(aa); //but when i put it outside, i only get the conversion of the last letter
Console.ReadLine();
}
</code></pre>
| <p>Use following modified program:</p>
<pre><code>public static void Main(string[] args)
{
Console.Write("INSERT TEXT:");
string a = Console.ReadLine();
char[] array = a.ToCharArray();
string[] aa = new string[array.Length];
int forIndex = 0;
foreach (char let in array)
{
int index = char.ToUpper(let) - 65;
string result = Convert.ToString(index, 2).PadLeft(5, '0');
aa[forIndex] = result;
Console.Write(aa[forIndex++]); //output 1
}
Console.ReadLine();
foreach(string x in aa)
Console.Write(x); // you will get same out here as output 1
Console.ReadLine();
}
</code></pre>
|
Pandas: How to do analysis on array-like field? <p>I'm doing analysis on movies, and each movie have a <code>genre</code> attribute, it might be several specific genre, like <code>drama</code>, <code>comedy</code>, the data looks like this:</p>
<pre><code>movie_list = [
{'name': 'Movie 1',
'genre' :'Action, Fantasy, Horror'},
{'name': 'Movie 2',
'genre' :'Action, Comedy, Family'},
{'name': 'Movie 3',
'genre' :'Biography, Drama'},
{'name': 'Movie 4',
'genre' :'Biography, Drama, Romance'},
{'name': 'Movie 5',
'genre' :'Drama'},
{'name': 'Movie 6',
'genre' :'Documentary'},
]
</code></pre>
<p>The problem is that, how do I do analysis on this? For example, how do I know how many action moviews are here, and how do I query for the category action? Specifically:</p>
<ol>
<li><p>How do I get all the categories in this list? So I know each contains how many moviews</p></li>
<li><p>How do I query for a certain kind of movies, like action?</p></li>
<li><p>Do I need to turn the <code>genre</code> into <code>array</code>?</p></li>
</ol>
<p>Currently I can get away the 2nd question with <code>df[df['genre'].str.contains("Action")].describe()</code>, but is there better syntax?</p>
| <p>If your data isn't too huge, I would do some pre-processing and get 1 record per genre. That is, I would structure your data frame like this:</p>
<pre><code> Name Genre
Movie 1 Action
Movie 1 Fantasy
Movie 1 Horor
...
</code></pre>
<p>Note the names should be repeated. While this may make your data set much bigger, if your system can handle it it can make data analysis very easy.
Use the following code to do the transformation:</p>
<pre><code>import pandas as pd
def reformat_movie_list(movies):
name = []
genre = []
result = pd.DataFrame()
for movie in movies:
movie_name = movie["name"]
movie_genres = movie["genre"].split(",")
for movie_genre in movie_genres:
name.append(movie_name.strip())
genre.append(movie_genre.strip())
result["name"] = name
result["genre"] = genre
return result
</code></pre>
<p>In this format, your 3 questions become</p>
<ol>
<li><p>How do I get all the categories in this list? So I know each contains how many movies?</p>
<p>movie_df.groupby("genre").agg("count")</p></li>
</ol>
<p>see <a href="http://stackoverflow.com/questions/19384532/how-to-count-number-of-rows-in-a-group-in-pandas-group-by-object">How to count number of rows in a group in pandas group by object?</a></p>
<ol start="2">
<li><p>How do I query for a certain kind of movies, like action?</p>
<p>horror_movies = movie_df[movie_df["genre"] == "horror"]</p></li>
</ol>
<p>see <a href="http://stackoverflow.com/questions/11869910/pandas-filter-rows-of-dataframe-with-operator-chaining">pandas: filter rows of DataFrame with operator chaining</a></p>
<ol start="3">
<li>Do I need to turn the genre into array?</li>
</ol>
<p>Your de-normalization of the data should take care of it.</p>
|
Minimum Spanning Tree with Boost <p>I have the following code that generates an undirected graph:</p>
<pre><code>// --- Header File ---
class Node { ... };
struct Edge { float weight; };
typedef adjacency_list<vecS, vecS, undirectedS, Node, Edge> Grafo;
class MST
{
public:
MST(std::vector<Node> nodes);
Grafo g;
vector<edge_t> build();
};
// --- cpp File ---
MST::MST(std::vector<Node> nodes) { // build the graph by setting vertices and edges... }
vector<edge_t> MST::build()
{
vector<edge_t> mst;
kruskal_minimum_spanning_tree(g, std::back_inserter(mst));
return mst;
}
</code></pre>
<p>The problem is in the line that I call Kruskal: <code>kruskal_minimum_spanning_tree()</code>. If I comment this line it will compile fine, and I can export the graph with graphviz (you can see the graph at <a href="http://www.webgraphviz.com" rel="nofollow">webgraphviz.com</a>):</p>
<pre><code>graph G {
0[label="a"];
1[label="b"];
2[label="c"];
3[label="d"];
4[label="e"];
0--1 [label=80.4487381];
0--2 [label=406.060333];
0--3 [label=405.738831];
0--4 [label=434.203857];
1--2 [label=25.9422436];
1--3 [label=210.344955];
1--4 [label=246.965591];
2--3 [label=35.805027];
2--4 [label=35.1283379];
3--4 [label=167.5858];
}
</code></pre>
<p>But if I try to compile with that line I get A LOT of errors from Boost (I'm using g++ 4.9.2). The first error is: <code>error: forming reference to void typedef value_type& reference;</code>, this error repeats several times. Other error that appears:</p>
<pre><code>error: no matching function for call to 'get(boost::edge_weight_t, const boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, Symbol, Edge>&)'
get(edge_weight, g));
</code></pre>
<p>So I've tried to add <code>get(edge_weight, g);</code> before call the Kruskal method, but I got notes saying:</p>
<pre><code>note: types 'boost::subgraph<Graph>' and 'const boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, Symbol, Edge>' have incompatible cv-qualifiers
get(edge_weight, g));
</code></pre>
<p>and </p>
<pre><code>note: mismatched types 'const boost::two_bit_color_map<IndexMap>' and 'boost::edge_weight_t'
get(edge_weight, g));
</code></pre>
<p>I don't know what to do. This is the first time I'm using Boost Graph Library. It is very powerful but not easy to understand.</p>
| <p><strong>TLDR</strong>: use </p>
<pre><code>kruskal_minimum_spanning_tree(g, std::back_inserter(mst),
weight_map( get(&Edge::weight, g) );
</code></pre>
<p><strong>Original answer</strong>:</p>
<p>The problem you are facing is that the algorithm needs to access a graph's weight map and yours doesn't have one by default. If you look at the signature of the algorithm in <a href="http://www.boost.org/libs/graph/doc/kruskal_min_spanning_tree.html" rel="nofollow">the documentation</a> you can see that it is:</p>
<pre><code>template <class Graph, class OutputIterator, class P, class T, class R>
OutputIterator kruskal_minimum_spanning_tree(Graph& g, OutputIterator tree_edges,
const bgl_named_params<P, T, R>& params = all defaults);
</code></pre>
<p>It has two "normal" parameters (the ones you used) and then a strange looking <code>bgl_named_params<P, T, R>& params</code>. This last parameter allows you to use the four parameters listed later in that page: <code>weight_map</code>, <code>rank_map</code>, <code>predecessor_map</code> and <code>vertex_index_map</code>. If you don't use any of these parameters its default value is used and in the case of <code>weight_map</code> this default is <code>get(edge_weight,g)</code>. That only works if you have an interior edge_weight property in your graph, meaning your graph is defined like this:</p>
<pre><code>typedef adjacency_list<vecS, vecS, undirectedS,
property<vertex_name_t,char>,//Could also be `Node` unless you use another algorithm with requirements on the vertices
property<edge_weight_t,float>
> InternalPropGraph;
</code></pre>
<p>But if that definition was required to use <code>kruskal_minimum_spanning_tree</code> (or any other algorithm) then <a href="http://www.boost.org/libs/graph/doc/bundles.html" rel="nofollow">bundled properties</a> wouldn't be useful at all. You just need to override the default <code>weight_map</code> using the named parameters:</p>
<pre><code>//typedef adjacency_list<vecS, vecS, undirectedS, Node, Edge> Grafo;
...
kruskal_minimum_spanning_tree(g, std::back_inserter(mst),
weight_map( get(&Edge::weight, g) );
</code></pre>
<p>In order to access a property map that relates a vertex/edge descriptor with a member of your structs you can simply use <code>get(&Struct::member, g)</code>.</p>
<p>A final note about Named Parameters, if in your invocation of the algorithm you need to use more than one of these parameters, you need to concatenate them with <code>.</code> instead of the usual <code>,</code> since in the signature <code>params</code> despite its name is a single parameter.</p>
<pre><code>//the order of the named params is irrelevant
kruskal_minimum_spanning_tree(g, std::back_inserter(mst),
weight_map(my_weights)
.vertex_index_map(my_indices)
.predecessor_map(my_predecessors));
</code></pre>
<p><a href="http://melpon.org/wandbox/permlink/DGEBVM9SHBl6ovZ9" rel="nofollow">Here</a> is an example that shows something similar to what you want using both internal properties and bundled properties. It deliberately uses different ways to set/access properties to show what you can do.</p>
|
subprocess.Popen execution of a script stuck <p>I am trying to execute a command as follows but it is STUCK in <code>try</code> block as below until the timeout kicks in,the python script executes fine by itself independently,can anyone suggest why is it so and how to debug this?</p>
<pre><code>cmd = "python complete.py"
proc = subprocess.Popen(cmd.split(' '),stdout=subprocess.PIPE )
print "Executing %s"%cmd
try:
print "In try" **//Stuck here**
proc.wait(timeout=time_out)
except TimeoutExpired as e:
print e
proc.kill()
with proc.stdout as stdout:
for line in stdout:
print line,
</code></pre>
| <p><code>proc.stdout</code> isn't available to be read <em>after the process exits</em>. Instead, you need to read it <em>while the process is running</em>. <code>communicate()</code> will do that for you, but since you're not using it, you get to do it yourself.</p>
<p>Right now, your process is almost certainly hanging trying to write to its stdout -- which it can't do, because the other end of the pipe isn't being read from.</p>
<p>See also <a href="http://stackoverflow.com/questions/1191374/using-module-subprocess-with-timeout">Using module 'subprocess' with timeout</a>.</p>
|
Supporting Angular 2's PathLocationHandler with Jetty (using a 404 error page) <p>I'm trying to work out how to support Angular 2's PathLocationHandler with an embedded Jetty server. To do that, as I understand it, I need to redirect any 404 request to the top-level index.html file (<a href="http://stackoverflow.com/a/34104534/797">http://stackoverflow.com/a/34104534/797</a>)</p>
<p>I figured the way to do that was to give the ContextHandler and ErrorHandler which redirected all 404 requests back to /index.html with something like the code below (I'm actually doing it in a context xml file, but the code might be easier to conceptualize/debug).</p>
<p>What I see is that my error handler is completely ignored, and I'm not sure how to fix that or, alternately, how I ought be configuring things instead.</p>
<hr>
<pre><code>import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
public class JettyTest {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setResourceBase("/tmp/directory-with-just-an-index.html-file");
ContextHandler contextHandler = new ContextHandler("/context-path");
ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
errorHandler.addErrorPage(404, "/index.html");
contextHandler.setHandler(resourceHandler);
contextHandler.setErrorHandler(errorHandler);
server.setHandler(contextHandler);
server.start();
System.out.println("Started!");
server.join();
}
}
</code></pre>
<p>Stepping through the Jetty code for a request like <a href="http://localhost:8080/context-path/some-file-which-is-not-present.html" rel="nofollow">http://localhost:8080/context-path/some-file-which-is-not-present.html</a>, what I see is that the ResourceHandler finds no matching files in it's resourceBase, and then calls...</p>
<pre><code> //no resource - try other handlers
super.handle(target, baseRequest, request, response);
return;
</code></pre>
<p>...then we bubble up out of the ContextHandler and eventually HttpChannelOverHttp sends out a 404 because the request isn't considered to have been handled.</p>
<pre><code> if (!_response.isCommitted() && !_request.isHandled())
_response.sendError(404);
</code></pre>
<p>Perhaps Jetty is expecting ResourceHandler to signal the 404 error in some different way? Or more likely, I'm failing to account for something in the way I'm configuring things.</p>
<p>The misconfiguration hint may be that <a href="https://www.eclipse.org/jetty/documentation/9.3.x/resource-handler.html" rel="nofollow">https://www.eclipse.org/jetty/documentation/9.3.x/resource-handler.html</a> mentions for ResourceHandler "Requests for resources that do not exist are let pass (Eg no 404âs).", but that leaves me unclear on where to go next other than 'write your own handler' which I'd prefer to avoid.</p>
<p>Any pointers much appreciated!</p>
| <p>Some amount of banging my head against things brought me to the following, which does do what I want, though I'd still certainly accept an answer which explained why ResourceHandler isn't appropriate for what I want...</p>
<pre><code>import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class JettyTest {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
ServletContextHandler servletContextHandler = new ServletContextHandler();
servletContextHandler.setContextPath("/context-path");
servletContextHandler.setResourceBase("/tmp/directory-with-just-an-index.html-file");
servletContextHandler.addServlet(new ServletHolder(new DefaultServlet()), "/*");
ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
errorHandler.addErrorPage(404, "/index.html");
servletContextHandler.setErrorHandler(errorHandler);
server.setHandler(servletContextHandler);
server.start();
System.out.println("Started!");
server.join();
}
}
</code></pre>
<p>...Now to try to turn that back into an xml context file :)</p>
<hr>
<p>...which I eventually did with the following in case anyone needs it later.</p>
<pre><code><?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
<Configure class="org.eclipse.jetty.servlet.ServletContextHandler" id="myContext">
<Set name="contextPath">/context-path</Set>
<Set name="resourceBase">/tmp/directory-with-just-an-index.html-file</Set>
<!-- Direct all 404s to index.html (required by Angular's PathLocationStrategy) -->
<Set name="errorHandler">
<New class="org.eclipse.jetty.servlet.ErrorPageErrorHandler">
<Call name="addErrorPage">
<Arg type="int">404</Arg>
<Arg type="String">/index.html</Arg>
</Call>
</New>
</Set>
<Call name="addServlet">
<Arg><New class="org.eclipse.jetty.servlet.ServletHolder">
<Arg>
<New class="org.eclipse.jetty.servlet.DefaultServlet"></New>
</Arg>
</New></Arg>
<Arg>/*</Arg>
</Call>
</Configure>
</code></pre>
|
Python Scripting in TIBCO Spotfire to show custom Messages <p>I am loading a data table on demand and have linked it to markings in a previous tab. The Data table look like:</p>
<pre><code> ID Values
1 365
2 65
3 32
3 125
4 74
5 98
6 107
</code></pre>
<p>I want to limit the data that is brought into this new visualization based on distinct count of ID. </p>
<p>I am currently doing it using
"Limit Data by Expression" section in the properties.
Where my expression is</p>
<pre><code>UniqueCount(ID) <= 1000
</code></pre>
<p>This works perfectly, however, I'd also like it to display a message like
"Too many IDs selected. Max Limit is 1000"</p>
<p>I was thinking of doing this using a property control where the property control triggers an iron python script. Any suggestions on how to write that script ?</p>
| <p>One work-around would be use of a small Text Area on the page (perhaps as a header). You can <code>Insert Dynamic Item</code> -> Calculated Value or Icon and have it perform a count or unique count based on marking (selection). For example, once the Count(ID) is > 1000, the text can change to red, or the icon can change color. This is a processing-light alternative which won't necessarily create a pop-up, but can still provide instant notification to a user that too many rows have been selected.</p>
<p>Edit below:</p>
<pre><code><!-- Invisible span to contain a copy of your value -->
<span style="display:none;" id="stores-my-count"><span id="seek-ender"></span></span>
\\Javascript below to grab dynamic item element's value and put it into a span
\\To be executed every time the dynamic value changes
$("#DynamicItemSpotfireID").onchange = function() {
var myCount = $("#DynamicItemSpotfireID").text();
$("#stores-my-count").append(myCount);
}
#IronPython script to locate the value placed into the span by the JS above
#and put only that portion of the page's HTML (only the value) into a document property
parentSpan = '<span id="stores-my-count">'
endingSpan = '<span id="seek-ender">'
startingHTML = myTextArea.As[VisualContent]().HtmlContent
startVal = startingHTML.find(parentSpan, startingIndex, endingIndex) + len(parentSpan)
endVal = startingHTML.find(endingSpan, startingIndex, endingIndex)
Document.Properties["myMarkingCount"] = startingHTML[startVal:endVal]
</code></pre>
<p>I haven't tested most of this code and I provide it as a place to start thinking about the problem, rather than a turnkey solution. Hopefully it works with only minor tweaking necessary.</p>
|
Int template in an array/vector/whatever <p>I need to know how to create an array/vector containing a class defined somewhat like:</p>
<pre><code>template<unsigned int rows, unsigned int columns>
class Matrix
{
......
};
</code></pre>
<p>Where <code>rows</code> and <code>columns</code> may vary from item to item in the vector.
Since the templates change, the vector regards them as different types and so it doesn't work.</p>
<p>Btw, I chose this format since many operations with matrices require the number of rows and columns to be the same and the templates make checking for it much easier.</p>
| <p>you might can try something like this</p>
<pre><code>class MatrixBase
{
public:
virtual ~MatrixBase() {}
virtual int getrow() = 0;
virtual int getcol() = 0;
};
template<unsigned int row, unsigned int column>
class Matrix : public MatrixBase
{
public:
virtual int getrow()
{
return row;
}
virtual int getcol()
{
return column;
}
};
Matrix<4, 4> m1;
Matrix<3, 3> m2;
Matrix<2, 2> m3;
vector<MatrixBase*> v;
v.push_back(&m1);
v.push_back(&m2);
v.push_back(&m3);
</code></pre>
<p>is thats not an option than you might wanna think of a design change.</p>
|
expect regular expression matches everything or nothing <p>From the following output</p>
<pre><code>user@machine ~]$ myScript
Warning: Permanently added '2.2.2.2' (RSA) to the list of known hosts.
Cookie: 65251-403 EventID: 8900000000
Answer:
</code></pre>
<p>How may I capture only the line "Cookie: 65251-403 EventID: 8900000000" into a variable?</p>
<p>The following code currently captures everything from "Warning" up to "Answer:"</p>
<pre><code>set [lindex $argv 0]
set [lindex $argv 0]
set timeout 20
spawn -noecho ssh -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -l $user $ip
set chalStr "(Cookie)"
expect {
$chalStr {
set challengeString $expect_out(buffer)
puts "RegEx matched: $challengeString"
}
}
interact {
"ver" { send "sversion|more" }
}
</code></pre>
<p>If I enclose the expression as ^Cookie$ then nothing is matched.</p>
| <p>Capture this <code>Cookie: 65251-403 EventID: 8900000000</code> with <code>^Cookie.*?$</code></p>
<p><strong>[EDIT] after your comment</strong></p>
<p>You need to add the multiline flag - see it working here: <a href="https://regex101.com/r/7XBeOF/1" rel="nofollow">https://regex101.com/r/7XBeOF/1</a></p>
<p>If you want to match same thing without the <code>m</code> flag you can also do so: <code>Cookie.*?\n</code>.</p>
<p>See it working here:
<a href="https://regex101.com/r/7XBeOF/2" rel="nofollow">https://regex101.com/r/7XBeOF/2</a></p>
|
External User for JFrog Artifactory Pro sees "Build Browser" <p>I want to share few of our libraries with our customers using JFrog Artifactory Pro. I have added a User for the customer and set permission to only show those packages which we want to share. However, when I login into JFrog Artifactory using the newly created (restricted) user I can see </p>
<ol>
<li>Artifacts - Which only shows what I want to expose</li>
<li>Builds - Which shows all the projects which are built?</li>
</ol>
<p>Is there any way to disable Build Browser for certain users?</p>
<p>If my expectations here are wrong or I am way off mark, please take a moment to explain what is the industry standard. </p>
<p>My basic aim is to use jfrog artifactory to expose certain artifacts in a controlled manner.</p>
| <p>In Artifactory you can block the access to the builds tab only for users that are not signed in. In case that a user is logged in and has read permissions on a repository then he will be able to see the builds tab. There is an open feature request for adding permissions to the builds tab. You can vote and watch this feature <a href="https://www.jfrog.com/jira/browse/RTFACT-4398" rel="nofollow">here</a>.</p>
|
How can I use Linq to XML to parse an XML string and locate all nodes with a value that starts with a specified letter? <p>Given a string of XML text like</p>
<pre><code> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<directory dirname=\"c\">" +
"<directory dirname=\"documents\">" +
"<directory dirname=\"daves projects 2015\" />" +
"<directory dirname=\"vics projects 2015\" />" +
"<directory dirname=\"daves projects 2014\" />" +
"</directory>" +
"<directory dirname=\"daves projects archive\" />" +
"</directory>";
</code></pre>
<p>What is the current preferred way to parse this string using Linq to XML so that it returns a list of directory names that start with "dave". Or is there a better way than using Linq to XML</p>
<p>I need an result that is a list of strings like the following;</p>
<p>daves projects 2015</p>
<p>daves projects 2014</p>
<p>daves projects archive</p>
<p>I tried using the following;</p>
<pre><code>public static void Main(string[] args)
{
string xml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<directory dirname=\"c\">" +
"<directory dirname=\"documents\">" +
"<directory dirname=\"daves projects 2015\" />" +
"<directory dirname=\"vics projects 2015\" />" +
"<directory dirname=\"daves projects 2014\" />" +
"</directory>" +
"<directory dirname=\"daves projects archive\" />" +
"</directory>";
var Folders = ParseXmlString(xml, "dave");
foreach (XElement name in Folders)
Console.WriteLine(name.Value);
}
private static List<XElement> ParseXmlString(string xmlStr, string searchValue)
{
List<XElement> result = new List<XElement>();
try
{
var str = XElement.Parse(xmlStr);
result = str.Elements("directory").Where(x => x.Element("dirname").Value.StartsWith(searchValue)).ToList();
}
catch (Exception ex)
{
throw ex;
}
return result;
}
</code></pre>
<p>But result is always empty.</p>
<p>Any suggestions?</p>
| <p>Change the function as below...</p>
<ol>
<li><p>In the calling method, change the type as </p>
<pre><code>foreach (XAttribute name in Folders)
</code></pre></li>
<li><p>Change the ParseXmlString as below. </p>
<pre><code>private static List<XAttribute> ParseXmlString(string xmlStr, string searchValue)
{
List<XAttribute> result = new List<XAttribute>();
try
{
XDocument doc = XDocument.Parse(xmlStr);
result = doc.Descendants("directory")
.Attributes("dirname")
.Where(x => x.Value.StartsWith("d"))
.ToList();
}
catch (Exception ex)
{
throw ex;
}
return result;
}
</code></pre></li>
</ol>
<p>Let me know if this helps.. </p>
|
Output list of files from slideshow <p>I have adapted a python script to display a slideshow of images. The original script can be found at <a href="https://github.com/cgoldberg/py-slideshow" rel="nofollow">https://github.com/cgoldberg/py-slideshow</a></p>
<p>I want to be able to record the filename of each of the images that is displayed so that I may more easily debug any errors (i.e., remove incompatible images).</p>
<p>I have attempted to include a command to write the filename to a text file in the <code>def get_image_paths</code> function. However, that has not worked. My code appears below - any help is appreciated.</p>
<pre><code>import pyglet
import os
import random
import argparse
window = pyglet.window.Window(fullscreen=True)
def get_scale(window, image):
if image.width > image.height:
scale = float(window.width) / image.width
else:
scale = float(window.height) / image.height
return scale
def update_image(dt):
img = pyglet.image.load(random.choice(image_paths))
sprite.image = img
sprite.scale = get_scale(window, img)
if img.height >= img.width:
sprite.x = ((window.width / 2) - (sprite.width / 2))
sprite.y = 0
elif img.width >= img.height:
sprite.y = ((window.height / 2) - (sprite.height / 2))
sprite.x = 0
else:
sprite.x = 0
sprite.y = 0
window.clear()
thefile=open('test.txt','w')
def get_image_paths(input_dir='.'):
paths = []
for root, dirs, files in os.walk(input_dir, topdown=True):
for file in sorted(files):
if file.endswith(('jpg', 'png', 'gif')):
path = os.path.abspath(os.path.join(root, file))
paths.append(path)
thefile.write(file)
return paths
@window.event()
def on_draw():
sprite.draw()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('dir', help='directory of images',
nargs='?', default=os.getcwd())
args = parser.parse_args()
image_paths = get_image_paths(args.dir)
img = pyglet.image.load(random.choice(image_paths))
sprite = pyglet.sprite.Sprite(img)
pyglet.clock.schedule_interval(update_image, 3)
pyglet.app.run()
</code></pre>
| <p>System don't have to write to file at once but it can keep text in buffer and saves when you close file. So probably you have to close file.</p>
<p>Or you can use <code>thefile.flush()</code> after every <code>thefile.write()</code> to send new text from buffer to file at once.</p>
|
Extract the year and the month from a line in a file and use a map to print every time its found to add 1 to the value <pre><code>def Stats():
file = open('mbox.txt')
d = dict()
for line in file:
if line.startswith('From'):
words = line.split()
for words in file:
key = words[3] + " " + words[6]
if key:
d[key] +=1
return d
</code></pre>
<p>The line reads</p>
<pre><code>From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
</code></pre>
<p>I want to pull "Jan 2008" as the key </p>
<p>My error message: </p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Robert\Documents\PYTHON WORKSPACE\Program 1.py", line 78, in <module>
File "C:\Users\Robert\Documents\PYTHON WORKSPACE\Program 1.py", line 76, in <module>
File "C:\Users\Robert\Documents\PYTHON WORKSPACE\Program 1.py", line 63, in <module>
builtins.KeyError: 'u -'
</code></pre>
| <p>Not the direct answer to the question, but a possible alternative solution - use the <a href="https://labix.org/python-dateutil" rel="nofollow"><code>dateutil</code></a> datetime parser in a "fuzzy" mode and simply format the extracted <code>datetime</code> object via <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.strftime" rel="nofollow"><code>.strftime()</code></a>:</p>
<pre><code>In [1]: from dateutil.parser import parse
In [2]: s = "From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008"
In [3]: parse(s, fuzzy=True).strftime("%b %Y")
Out[3]: 'Jan 2008'
</code></pre>
|
How to show array from show table schema query in php <p>i have a query</p>
<pre><code>$qdrop=mysqli_query($connect,"select TABLE_NAME,create_time
FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema = 'purbalingga'
AND CREATE_TIME <='2016-10-07' and TABLE_NAME LIKE '2016%'");
</code></pre>
<p>and a while for show the array</p>
<pre><code>while ($datadrop=mysqli_fetch_array($qdrop)) {
echo $qdrop['TABLE_NAME'];echo"<br/>";
}
</code></pre>
<p>But i got an error:</p>
<pre><code>Fatal error: Cannot use object of type mysqli_result as array in E:\xampp\htdocs
</code></pre>
| <p>Replace:</p>
<pre><code>while ($datadrop=mysqli_fetch_array($qdrop)) {
echo $qdrop['TABLE_NAME'];
echo"<br/>";
}
</code></pre>
<p>With:</p>
<pre><code>while ($datadrop=mysqli_fetch_array($qdrop)) {
echo $datadrop['TABLE_NAME'];
echo"<br/>";
}
</code></pre>
<p><code>$qdrop</code> only holds the query but <code>$datadrop</code> is the one holding the <code>result in array</code>.</p>
|
Angular 2 two-way binding propagation through components <p>I'm trying to make two-way binding in a component and propagate it through other components that contain the child component:</p>
<p>I have a child component, with two-way binding and it's working. The binding is pointing to a variable called <code>child_value</code></p>
<p>Then this child component is present in the template of a parent component. I want a two-way binding here too, so I use <code>[(child_value)]=parent_value</code></p>
<p>Finally this parent component is used in my application, so in this component I also want a two-way binding like <code>[(parent_value)]=application_value</code></p>
<p>But only the first binding is working in two way. To exemplify it I created this plunker</p>
<p><a href="http://plnkr.co/edit/IWVzmRbqL3ARFaYxjs3F?p=preview" rel="nofollow">http://plnkr.co/edit/IWVzmRbqL3ARFaYxjs3F?p=preview</a></p>
<p>When you drag the slider you can see that the Child value updates, but the others don't. If I change the <code>application_value</code> in code, through the button, then it is propagated through all components. </p>
| <p><strong>1. The easiest way to fix your code:</strong></p>
<p>If you check the console log that you've written into, you can see that <code>AppComponent</code> and <code>ParentComponent</code> are notified by the <code>valueChanged</code> event, all you need to do is to update the value of the variables accordingly:</p>
<p>In <code>AppComponent</code>:</p>
<pre><code> onchange(event)
{
this.application_value = event.value; // <-- add this line
console.log('root::onchange() => value:' + event.value);
}
</code></pre>
<p>In <code>ParentComponent</code>:</p>
<pre><code> onchange(event)
{
this.parent_value = event.value; // <-- add this line
console.log('parent::onchange() => value:' + event.value);
this.valueChanged.emit({value: event.value});
}
</code></pre>
<p>Here's the plunker for your reference: <a href="http://plnkr.co/edit/TW2F6mdx1SJbdjKqonmO?p=preview" rel="nofollow">http://plnkr.co/edit/TW2F6mdx1SJbdjKqonmO?p=preview</a></p>
<p><strong>2. Understand two-way binding and make it works:</strong> </p>
<p>Here is the reason why the two-way binding doesn't work on your case: </p>
<blockquote>
<p>The banana in the box syntax (<code>[(child_value)]="someValue"</code>) is just a
syntactic sugar for having both <code>[child_value]="someValue"</code> and
<code>(child_valueChange)="someValue=$event"</code>.</p>
</blockquote>
<p>And because you never define the <code>@Output() child_valueChange</code> in your component, the return way is blocked. To solve it:</p>
<ul>
<li>Change your <code>@Output() valueChanged</code> to <code>@Output() child_valueChange</code>
in your <code>ChildComponent</code> and </li>
<li>Change your <code>@Output() valueChanged</code> to
<code>@Output() parent_valueChange</code> in your <code>ParentComponent</code></li>
</ul>
<p>The second plunker that has working two-way binding: <a href="http://plnkr.co/edit/M5CPqrgWJ53vBkqhVz4f?p=preview" rel="nofollow">http://plnkr.co/edit/M5CPqrgWJ53vBkqhVz4f?p=preview</a></p>
|
How can I simulate a basic drop shadow using border-image and linear-gradient? <p>I'd like to simulate a drop shadow effect using border-image and linear-gradient (for scroll performance reasons, I am not using the native box-shadow effect).</p>
<p>As can be seen in the example below and in the <a href="https://jsfiddle.net/tjsghk9t/" rel="nofollow">fiddle</a>, my attempted approach involves using border-image for the gradient, border-image-outset to move the shadow outside the content box, and border-width to show only the bottom edge.</p>
<p>Admittedly, I don't understand border-image so well, particularly when it comes to using it with linear-gradients. Through trial and error, I achieved what seemed to be a satisfactory result. But as it turns out, when the width of the div is short enough, the "shadow" disappears entirely.</p>
<p>What can I do to achieve a drop shadow like in the top box, but one that works regardless of the box size? Your help with this is really appreciated!</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box
{
/* the "shadow" */
border-image: linear-gradient(to bottom, rgba(0,0,0,0.5) 0%, rgba(0,0,0,0.5) 10%, rgba(0,0,0,0) 100%) 100 repeat;
border-image-outset: 0px 0px 6px 0px;
border-width: 0px 0px 6px 0px;
border-style: solid;
/* other stuff */
font-family: sans-serif;
font-size: 20px;
color: #FEFEFE;
background: #007277;
margin: 10px 0px;
float: left;
clear: left;
padding: 50px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
Here's longer text, where the "shadow" appears how I want it to.
</div>
<div class="box">
Short
</div></code></pre>
</div>
</div>
</p>
| <p>For the short border to work you need to change the </p>
<pre><code>100 repeat;
</code></pre>
<p>to</p>
<pre><code>0 0 100 0 repeat;
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box
{
/* the "shadow" */
border-image: linear-gradient(to bottom, rgba(0,0,0,0.5) 0%, rgba(0,0,0,0.5) 10%, rgba(0,0,0,0) 100%) 0 0 100 0 repeat;
border-image-outset: 0px 0px 6px 0px;
border-width: 0px 0px 6px 0px;
border-style: solid;
/* other stuff */
font-family: sans-serif;
font-size: 20px;
color: #FEFEFE;
background: #007277;
margin: 10px 0px;
float: left;
clear: left;
padding: 50px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
Here's longer text, where the "shadow" appears how I want it to.
</div>
<div class="box">
Short
</div></code></pre>
</div>
</div>
</p>
<p>This link may help you a little on your border imaging <a href="https://css-tricks.com/understanding-border-image/" rel="nofollow">https://css-tricks.com/understanding-border-image/</a></p>
|
How to select a match and split a string in ruby? <p>I need to select and prune an array of strings in Ruby and I have it partially working.</p>
<p>I have array of strings that looks like this:</p>
<pre><code>321 com.apple.storeaccountd.daemon
- com.apple.cmio.AVCAssistant
- com.apple.diskmanagementd
150 com.apple.CodeSigningHelper
- com.apple.tailspind
197 com.apple.sysmond
- com.apple.storeassetd.daemon
160 com.apple.sandboxd
</code></pre>
<p>What I need to do is select only those entries that have an integer which the line below does:</p>
<pre><code>launchctl_list.select! { |f| /^(?!- )/.match(f) }
</code></pre>
<p>This results in an array that looks like this:</p>
<pre><code>321 com.apple.storeaccountd.daemon
150 com.apple.CodeSigningHelper
197 com.apple.sysmond
160 com.apple.sandboxd
</code></pre>
<p>I now just want to retain the 'last' part of each string in the array and I thought the following line would do the trick but doesn't.</p>
<pre><code>launchctl_list.select! { |f| f.split(' ').last }
</code></pre>
<p>The strings in the array do not have their numbers dropped, what am I missing?</p>
| <p>The Array#select method will not modify each entry in the list, its used only to select which one to keep based on what the block returns.</p>
<p>What you want to use is Array#map! like this:</p>
<pre><code>launchctl_list.map!{|f| f.split(' ').last }
</code></pre>
|
How can I disable a button until image is taken in swift 3? <p>So, I want the button to be disable if no photo is taken, if the photo is taken and shows on the imageview then I want the button to be enabled? </p>
| <p><strong>step-1</strong></p>
<blockquote>
<p>check the image is nil or not in view is loaded</p>
</blockquote>
<pre><code>@IBOutlet weak var photoImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// call the method
setHiddenImage()
}
</code></pre>
<blockquote>
<p>create the common method for check the Image is empty or not</p>
</blockquote>
<pre><code> func setHiddenImage ()
{
proceedBtn. hidden = true
if (self.photoImageView.image != nil){
//image set
proceedBtn. hidden = false
}
}
</code></pre>
<p><strong>Step-2</strong></p>
<blockquote>
<p>UIImagePickerController delegate method , check whether image is fetched or not</p>
</blockquote>
<pre><code> // MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// Dismiss the picker if the user canceled. and call the method
setHiddenImage()
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// The info dictionary contains multiple representations of the image, and this uses the original.
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
// Set photoImageView to display the selected image.
photoImageView.image = selectedImage
setHiddenImage()
// Dismiss the picker.
dismiss(animated: true, completion: nil)
}
</code></pre>
|
How to tie different data in sql with same post_id <p>Below is How this Table data look a like</p>
<pre><code>Post_id | P_key | P_value
10 | F_name | Amar
10 | l_name | Arya
10 | country | India
11 | F_name | Karan
11 | l_name | Roy
11 | country | Nepal
</code></pre>
<p>And I want to display same post_id detail in one row like this</p>
<pre><code>f_name | L_name | Country
Amar | Arya | India
Karan | Roy | Nepal
</code></pre>
<p>So can you please suggest me SQL query for it.</p>
| <p>Here's one option using <code>conditional aggregation</code>:</p>
<pre><code>select max(case when p_key = 'f_name' then p_value end) as f_name,
max(case when p_key = 'l_name' then p_value end) as l_name,
max(case when p_key = 'country' then p_value end) as country,
post_id
from yourtable
group by post_id
</code></pre>
<p>This will return a single row for each <code>post_id</code>. </p>
|
What is the iOS URL schema for Facebook profiles? <pre><code>class func openFacebook(id: String){ //id is a username in this case
let name = id.replace(" ", withString: "")
let hook = "fb://profile/" + name
let hookURL = NSURL(string: hook)
if UIApplication.sharedApplication().canOpenURL(hookURL!){
UIApplication.sharedApplication().openURL(hookURL!)
} else {
UIApplication.sharedApplication().openURL(NSURL(string: "http://facebook.com/" + name)!)
}
}
</code></pre>
<p>I try to do this, but it never opens the app. It always opens the browser.
I'm not using the facebook sdk. I just want to open facebook from my app, to the user's profile.</p>
| <p>If you have an error: 'LSApplicationQueriesSchemes'
so you have to register url scheme in LSApplicationQueriesSchemes under plist.</p>
<p>please check below link for process of adding url scheme to LSApplicationQueriesSchemes.</p>
<p><a href="http://stackoverflow.com/questions/21893447/facebook-sdk-app-not-registered-as-a-url-scheme">Facebook SDK: app not registered as a URL Scheme</a></p>
|
Mock standard input - multi line in python 3 <p>I am new to python and have been using python 3 for my learning. I am using python's unit test framework to test my code.</p>
<p>Problem :-</p>
<p>The function that I need to unit test takes inputs in the following manner:-</p>
<pre><code>def compare():
a, b, c = input().strip().split(' ')
d, e, f = input().strip().split(' ')
# other code here
</code></pre>
<p>I am using the following test case to mock the input :-</p>
<pre><code>class TestCompare(unittest.TestCase):
@patch("builtins.input", lambda: "1 2 3")
@patch("builtins.input", lambda: "4 5 6")
def test_compare(self):
self.assertEqual(compare(), "1 1")
</code></pre>
<p>The problem I am facing is that when the test case is run the variable triplets a,b,c and d,e,f have the same values - 1,2,3</p>
<p>I have been trying to find a way to inject the second set of inputs to run my test but in vain.</p>
<p>Any help regarding the above is greatly appreciated.</p>
<p>Solution environment :- Python 3</p>
| <p>You can't patch it twice like that. You'll have to patch it once, with an object that returns different values on subsequent calls. Here's an example:</p>
<pre><code>fake_input = iter(['1 2 3', '4 5 6']).__next__
@patch("builtins.input", fake_input)
def test_compare(self):
...
</code></pre>
|
accessing specific columns from another table in the has_many/belongs_to relationship <p>I have an <code>Rsvp</code> table which forms a join between a <code>User</code> and an <code>Event</code>. <code>Rsvp</code> table has information for an rsvp <code>status</code>. I need for <code>Event</code> to be able to access this info in the users/show view, perhaps make a call like <code>event.rsvp_status</code> as I showed below. User has freedom to change the rsvp status at anytime. How can this be achieved?
What my models look like: </p>
<pre><code>class Rsvp < ApplicationRecord
enum status: { not_interested: 0, interested: 1, attending: 2 }
belongs_to :event
belongs_to :user
end
class Event < ApplicationRecord
has_many :rsvps
has_many :users, through: :rsvps
def title
"#{self.name} with #{self.artists.map(&:name).join(", ")} at #{self.venue.name}"
end
end
class User < ApplicaitonRecord
has_many :rsvps
has_many :events, through: :rsvps
end
</code></pre>
<p>I am using these methods in views for other models, such as <code>Venue</code>, <code>Event</code> and <code>Artist</code></p>
<pre><code>class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def past_events
self.events.select { |event| event.date < DateTime.now }
end
def future_events
self.events.select { |event| event.date > DateTime.now }
end
end
</code></pre>
<p>in the view, it would look something like this.</p>
<pre><code><%= "Upcoming events: " %>
<% @user.future_events.each do |event| %>
<% unless event.rsvp_status = "not_interested" %>
<%= link_to event.title, event_path(event) %>
<%= event.rsvp_status %>
<% end %>
<% end %>
</code></pre>
| <blockquote>
<p>here error I get: <code>undefined method 'status=' for #<Rsvp::ActiveRecord_AssociationRelation:0x007fabb403b8f0></code>. it works if you do it directly like <code>Rsvp.find(:id).status</code></p>
</blockquote>
<p>Odd. <code>status=</code> means you're trying to set a value on the status... but that shouldn't be the case if you're just trying to look at the status... </p>
<p>also AHA! <code>Rsvp::ActiveRecord_AssociationRelation</code> means that you've got a set of RSVPs, instead of a single one. What you probably want to do is add a <code>.first</code> on the end of your <code>where</code> - to make sure you've just got a single, actual rsvp, rather than a whole set of them (with just one in the set).</p>
<p>So that would mean the code would look a bit like this:</p>
<pre><code>class User
def rsvp_for_event(event)
rsvps.where(:event_id => event.id).first
end
end
</code></pre>
<p>and in your template:</p>
<pre><code><% @user.future_events.each do |event| %>
<% rsvp_status = @user.rsvp_for_event(event).status %>
<% unless rsvp_status = "not_interested" %>
<%= link_to event.title, event_path(event) %>
<%= rsvp_status %>
<% end %>
<% end %>
</code></pre>
<p>or something different, but giving the same end result :)</p>
<p>Thinking about it, an rsvp-scope might be prettier</p>
<pre><code>class Event
scope :for_event, ->(event) { where(:event_id => event.id) }
end
</code></pre>
<p>and in your template:</p>
<pre><code><% @user.future_events.each do |event| %>
<% rsvp_status = @user.rsvp_for_event(event).status %>
<% unless rsvp_status = "not_interested" %>
<%= link_to event.title, event_path(event) %>
<%= rsvp_status %>
<% end %>
<% end %>
</code></pre>
|
Convert JAVA code KeyStore.getInstance to c# <p>I'm trying to convert this following <code>JAVA</code> code to <code>C#</code> for getting <code>ECPrivateKey</code>.</p>
<pre><code>private static ECPrivateKey loadPrivateKey(String pkcs12Filename) throws KeyStoreException, NoSuchProviderException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
keystore.load(new FileInputStream(pkcs12Filename), "".toCharArray());
assert keystore.size() == 1 : "wrong number of entries in keychain";
Enumeration<String> aliases = keystore.aliases();
String alias = null;
while (aliases.hasMoreElements()) {
alias = aliases.nextElement();
}
return (ECPrivateKey) keystore.getKey(alias, null);
}
</code></pre>
| <p>Here is the code, I got the output with this.</p>
<pre><code>private void GetPrivateKeyFromP12(string path, string passWord)
{
//this.mKeyStoreEntities = PKCSUtils.extractEntities(privateKeyFilePath, privateKeyPassword);
/**
* Java has a minimum requirement for keystore password lengths. Utilities like KeyChain will
* allow you to specify less but then you will receive an obscure java error when trying to
* load the keystore. Check for it here and throw a meaningful error
*/
//X509Certificate certificate;
//ECPrivateKey privateKey;
using (StreamReader reader = new StreamReader(path))
{
var fs = reader.BaseStream;
GetMerchantIdentifierField(fs);
fs.Position = 0;
GetPrivateKey(fs, passWord);
}
}
private void GetPrivateKey(Stream fs, string passWord)
{
Pkcs12Store store = new Pkcs12Store(fs, passWord.ToCharArray());
foreach (string n in store.Aliases)
{
if (store.IsKeyEntry(n))
{
AsymmetricKeyEntry asymmetricKey = store.GetKey(n);
if (asymmetricKey.Key.IsPrivate)
{
this.merchantPrivateKey = asymmetricKey.Key as ECPrivateKeyParameters;
}
}
}
}
</code></pre>
|
What is the most secure way to Create a Process with Admin Rights? <p>I have a server that uses the CreateProcess function to launch a client program which requires administrative rights. I am hesitant to do this because all a hacker would have to is replace their program <code>hacker.exe</code> in the same location as my client program and give it the name <code>totallysafeclient.exe</code> which my server will launch with administrative rights. </p>
<p>I was thinking of using <a href="https://support.microsoft.com/en-us/kb/307020#bookmark-3" rel="nofollow">System.Security.Cryptography</a> to calculate the hash of <code>totallysafeclient.exe</code> to determine if it is indeed what it says it is. Thoughts?</p>
| <p>After some additional research, using <a href="https://support.microsoft.com/en-us/kb/307020#bookmark-3" rel="nofollow">System.Security.Cryptography</a> is a very poor choice because Windows already has a builtin mechanism involving RSA encryption called <a href="https://msdn.microsoft.com/en-us/library/ms537361(v=vs.85).aspx" rel="nofollow">Code Signing</a>. Signing your code allows users to know where code comes from and if it has been <strong>tampered with</strong>. </p>
<p><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx" rel="nofollow">ShellExecute</a> is a much better choice than CreateProcessAsUser because it can handle <code>ERROR_ELEVATION_REQUIRED</code> exceptions by using UAC. Most users <em>and developers</em> hated (and probably still do) when Vista came out with this but I highly encourage you to watch <a href="https://channel9.msdn.com/Shows/Going+Deep/UAC-What-How-Why" rel="nofollow">UAC - What. How. Why.</a> where both the Project Lead and System Architect of UAC explain why it was needed and how it has increased security. </p>
|
Identify the latest file through specific patterns in a directory <pre><code>var directory = new DirectoryInfo("C:\example");
string pattern = "LOG" + "_" + "NA" + "_" + "3465";
var validFiles = directory.GetFiles("*.xml");
List<string> list = new List<string>();
foreach (var item in validFiles)
{
string a = item.ToString();
if (a.Contains(pattern))
{
list.Add(a);
}
}
</code></pre>
<p>I wanted to get the latest file with the above pattern from the directory specified. I had tried the as above to get the file that as the common pattern, but, I am stuck in getting the latest file among the files in <code><list></code>. Your help is very much appreciated.</p>
| <p>Use the pattern when you call <code>GetFiles</code>, then order by creation date or whatever field you're interested in. The <code>OrderByDescending</code> ensures the oldest file is on top.</p>
<pre><code>list = directory.GetFiles("*LOG_NA_3465*.xml")
.OrderByDescending(fi => fi.CreationTime)
.First();
</code></pre>
<p>In your code, by the time you store the results in the <code>List<string></code>, you're not dealing with a <code>FileInfo</code> object anymore and you've lost access to any details about the files.</p>
|
How do I properly pass data from a component to another in angular 2 <p>I have these codes:</p>
<p>moduleOne.component.ts:</p>
<pre><code>@Component({
selector: 'one',
templateUrl: './moduleOne.component.html'
})
export class ModuleOneComponent {
private ag: AgGridModel;
private columnDefs = [
{headerName: "Sport", field: "sport", width: 110, suppressMenu: true},
{headerName: "Gold", field: "gold", width: 100, suppressMenu: true},
{headerName: "Silver", field: "silver", width: 100, suppressMenu: true},
{headerName: "Bronze", field: "bronze", width: 100, suppressMenu: true},
{headerName: "Total", field: "total", width: 100, suppressMenu: true}
];
constructor(){
this.ag.id = "one";
this.ag.tableName = "module one";
this.ag.colDefs = this.columnDefs;
// Define delegate button
var delegateBtn = new buttonModel(
'delegateId',
'Delegate',
'glyphicon icon-arrow_right',
this.delegateJob
) ;
// Define print button
var printBtn = new buttonModel(
'printId',
'Print',
'glyphicon print',
this.printJob
);
this.ag.gridButtons.push(printBtn);
this.ag.gridButtons.push(delegateBtn);
}
private delegateJob() {
// TODO: call delegateModal
return;
}
private printJob() {
// TODO: call delegateModal
return;
}
}
</code></pre>
<p>moduleOne.component.html:</p>
<pre><code><div class="container-fluid single-col-full-width-container">
<ag-grid-common [ag]="ag" ></ag-grid-common>
</div>
</code></pre>
<p>ag-grid-common.component.ts:</p>
<pre><code>@Component({
selector: 'ag-grid-common',
templateUrl: './ag-grid-common.component.html'
})
export class AgGridCommonComponent implements OnInit {
@Input() public ag: AgGridModel;
private gridOptions:GridOptions;
private rowCount;
ngOnInit(){
this.gridOptions = this.ag.gridOptions;
// Dynamically create ag-grid in the selected element
var idSelector = '#' + this.ag.id;
var gridDiv = <HTMLInputElement>document.querySelector(idSelector);
new Grid(gridDiv, this.gridOptions);
this.createNewDatasource();
}
constructor() {
}
}
</code></pre>
<p>ag-grid-common.component.html:</p>
<pre><code><div style="width: 100%">
<div class="row">
<div class="col-sm-12">
<div class="col-sm-1" *ngFor="let btn of ag.gridButtons">
<cui-button [id]="btn.id" [iconClass]="btn.icon" (click)="btn.callbackFunc">{{btn.name}}</cui-button>
</div>
</div>
</div>
<div style="height: 320px; padding-top: 10px;" [id]="ag.id" class="ag-fresh"></div>
</code></pre>
<p>The ag variable of ag-grid-common is an input variable from moduleOne
and some attributes of the ag variable are used in ag-grid-common.component.html</p>
<p>I got this error: ag-Grid: no div element provided to the grid</p>
<p>When I check the page source, all directives with ag are not loaded.</p>
<p>here is the page source:</p>
<pre><code><ag-grid-common ng-reflect-ag="[object Object]">
<br>
<div style="width: 100%">
<div class="row">
<div class="col-sm-12">
<!--template bindings={}-->
**<div class="col-sm-1">**
</div>
</div>
</div>
<div style="padding: 4px; width: 100%; ">
<div style="height: 6%;">
Page Size:
<select>
<option selected="" value="10">10</option>
<option value="100">100</option>
<option value="500">500</option>
<option value="1000">1000</option>
</select>
</div>
<div class="ag-fresh" style="height: 320px; padding-top: 10px;"></div>
<br></div>
</div>
</ag-grid-common>
</code></pre>
| <p>In <code>AgGridCommonComponent.ngOnInit()</code> you query the DOM but the DOM is probably not available yet. This code should be moved to <code>ngAfterViewInit()</code></p>
|
r - look up values in a table based on other variables representing row and column number <p>In R I have a table of people's responses to a multiple choice questionnaire e.g. table1:</p>
<pre><code>subject question1 question2 question3
person1 1 2 1
person2 2 1 3
person3 4 3 1
person4 2 4 2
</code></pre>
<p>and I have tables I want to use to combine their answers to the questions to produce a new variable e.g. table2:</p>
<pre><code> Q2=1 Q2=2 Q2=3 Q2=4
Q1=1 1 1 2 2
Q1=2 2 2 2 3
Q1=3 3 3 4 4
Q1=4 4 4 4 5
</code></pre>
<p>Where the row# is their answer to Question 1 and the column# is their answer to Question 2. For example, if they answered "3" to Question 1 and "2" to Question 2, I need the corresponding value in row 3/column 2 of the second table i.e. "3".</p>
<p>When I use the code:</p>
<pre><code>table1$combinedq1q2 = (table2[table1$question1, table1$question2])
</code></pre>
<p>I'm hoping to end up with:</p>
<pre><code>subject question1 question2 question3 combinedq1q2
person1 1 2 1 1
person2 2 1 3 2
person3 4 3 1 4
person4 2 4 2 3
</code></pre>
<p>but instead, R is generating a bajillion columns named combinedq1q2.1, combinedq1q2.2, combinedq1q2.3, etc... I don't understand why this is happening or how to fix it. ): I'd appreciate any help!</p>
<p>I did look at <a href="http://stackoverflow.com/questions/31366548/vlookup-match-like-function-in-r?rq=1">this thread</a> and if I can't find any other solution I'll just copy the code from there without really understanding it. But since what I'm looking up values by is the same as the row and column numbers, I was hoping there would be a simpler solution.</p>
<p>Thanks!</p>
<p>EDIT: Thank you for the responses! I added row and column names to my Table 2 to clarify. I'm trying to use the answers to Question 1 and Question 2 to look up/access the value of a third variable in Table 2 (and I already have Table 2; I do not need to generate it). Also, combinedq1q2 just happened to always match question1 in my previous example, so I added another person/row to show that this won't always be the case. </p>
<p>I'll try what was suggested so far, although I'm confused about people saying I'll get combinedq1q2=5 for person3.</p>
| <p>I <em>think</em> your question is "How do I look up the (question1, question2)th (row, col) of <code>table2</code> and save the result for each person", where <code>table2</code> is given. (As opposed to "how do I generate <code>table2</code>").</p>
<p>if so, you can use matrix indexing into your table. Ie make a 2-column matrix where each row is the (row, column) coordinates, and use that to index <code>table2</code>.</p>
<pre><code>df$question1question2 = table2[cbind(df$question1, df$question2)]
</code></pre>
<p>However this output doesn't match yours. For example, person3 has (question1, question2) = (4,3) and that element of <code>table2</code> is 5, but in your desired output you have 4 (in fact, it looks like you just want <code>question1question2</code> to be the same as <code>question1</code>.</p>
<p>You will have to clarify your desired output.</p>
<p>If your questions is around how to <em>generate</em> a <code>table2</code>, you'll have to answer my comment about how exactly this table is constructed.</p>
|
My Word VBA UserForm is not populating my template as expected, but does not produce an error message. Why? <p>The expected behavior when I click the OK button is populating the form with the information entered by the user. Instead, nothing happens. The document remains unchanged, but I don't receive an error message. Why is this happening?</p>
<p>It also doesn't interact very well with the Code Sample button, either. I'm not sure why, so apologies for the ugliness below. There's a Pastebin link <a href="http://pastebin.com/GmbVXAxk" rel="nofollow">http://pastebin.com/GmbVXAxk</a> that looks a little prettier. </p>
<pre><code>Public Function ValidateData() As Boolean
ValidateData = True
If txtName.Value = "" Then
MsgBox "Please enter the candidate's name", , "Missing Information"
ValidateData = False
Exit Function
End If
If cboProvince.Value = "" Then
MsgBox "Please select a province", , "Missing Information"
ValidateData = False
Exit Function
End If
If txtCity.Value = "" Then
MsgBox "Please enter a city", , "Missing Information"
ValidateData = False
Exit Function
End If
If txtStreetAddress.Value = "" Then
MsgBox "Please enter a street address", , "Missing Information"
ValidateData = False
Exit Function
End If
If txtPostalCode.Value = "" Then
MsgBox "Please enter the candidate's postal code", , "Missing Information"
ValidateData = False
Exit Function
End If
If txtPosition.Value = "" Then
MsgBox "Please enter the candidate's position", , "Missing Information"
ValidateData = False
Exit Function
End If
If txtStartDate.Value = "" Or Not IsDate(txtStartDate.Value) Then
MsgBox "Please enter the candidate's start date", , "Missing Information"
ValidateData = False
Exit Function
End If
If txtAnnualSalary = "" Or Not IsNumeric(txtAnnualSalary.Value) Then
MsgBox "Please enter a total salary using numbers only", , "Missing Information"
ValidateData = False
Exit Function
End If
If cboPaymentFrequency = "" Then
MsgBox "Please select a payment frequency", , "Missing Information"
ValidateData = False
Exit Function
End If
If txtTotalVacation = "" Or Not IsNumeric(txtTotalVacation.Value) Then
MsgBox "Please enter the total number of vacation days", , "Missing Information"
ValidateData = False
Exit Function
End If
If cboDepartment.Value = "" Then
MsgBox "Please select the candidate's department", , "Missing Information"
ValidateData = False
Exit Function
End If
If optRegards.Value = False And optSincerely.Value = False And optYoursTruly.Value = False And optBestWishes.Value = False Then
MsgBox "Please selection a sign off", , "Missing Information"
ValidateData = False
Exit Function
End If
If txtSignersName.Value = "" Then
MsgBox "Please Enter the signer's name", , "Missing Information"
ValidateData = False
Exit Function
End If
If txtSignersTitle.Value = "" Then
MsgBox "Please Enter the signer's title", , "Missing Information"
ValidateData = False
Exit Function
End If
End Function
Private Sub cmdCancel_Click()
frmEmploymentOffer.Hide
Unload frmEmploymentOffer
End Sub
Private Sub cmdClear_Click()
txtName.Value = ""
cboProvince.Value = ""
txtCity.Value = ""
txtStreetAddress.Value = ""
txtPostalCode.Value = ""
txtPosition.Value = ""
txtStartDate.Value = ""
txtAnnualSalary.Value = ""
cboPaymentFrequency.Value = ""
txtTotalVacation.Value = ""
cboDepartment.Value = ""
optRegards.Value = False
optSincerely.Value = False
optBestWishes.Value = False
optYoursTruly.Value = False
txtSignersName.Value = ""
txtSignersTitle.Value = ""
End Sub
Private Sub PopulateTemplate()
'Takes input and transfers it to the form in the appropriate fields
ActiveDocument.Bookmarks("Name").Range.Text = txtName.Value
ActiveDocument.Bookmarks("Province").Range.Text = cboProvince.Value
ActiveDocument.Bookmarks("City").Range.Text = txtCity.Value
ActiveDocument.Bookmarks("StreetAddress").Range.Text = txtStreetAddress.Value
ActiveDocument.Bookmarks("PostalCode").Range.Text = txtPostalCode.Value
ActiveDocument.Bookmarks("Position").Range.Text = txtPosition.Value
ActiveDocument.Bookmarks("StartDate").Range.Text = txtStartDate.Value
ActiveDocument.Bookmarks("AnnualSalary").Range.Text = txtAnnualSalary.Value
ActiveDocument.Bookmarks("PaymentFrequency").Range.Text = cboProvince.Value
ActiveDocument.Bookmarks("TotalVacation").Range.Text = txtTotalVacation.Value
ActiveDocument.Bookmarks("Department").Range.Text = cboDepartment.Value
ActiveDocument.Bookmarks("SignersName").Range.Text = txtSignersName.Value
ActiveDocument.Bookmarks("SignersTitle").Range.Text = txtSignersTitle.Value
'Adds the correct sign off to the document
If optBestWishes.Value = True Then
ActiveDocument.Bookmarks("ClosingGreeting").Range.Text = "Best Wishes"
ElseIf optYoursTruly.Value = True Then
ActiveDocument.Bookmarks("ClosingGreeting").Range.Text = "Yours truly"
ElseIf optSincerely.Value = True Then
ActiveDocument.Bookmarks("ClosingGreeting").Range.Text = "Sincerely"
Else
ActiveDocument.Bookmarks("ClosingGreeting").Range.Text = "Regards"
End If
'Calculates monthly vacation by dividing TotalVacation input by 12
ActiveDocument.Bookmarks("MonthlyVacation").Range.Text = txtTotalVacation.Value / 12
'Calculates salary amount per pay period by dividing annual salary input by user by
'the number of weeks in that pay period
If cboPaymentFrequency.Value = "Weekly" Then
ActiveDocument.Bookmarks("EarningsPerPayPeriod").Range.Text = txtAnnualSalary.Value / 52
ElseIf cboPaymentFrequency.Value = "Bi-Weekly" Then
ActiveDocument.Bookmarks("EarningsPerPayPeriod").Range.Text = txtAnnualSalary.Value / 26
ElseIf cboPaymentFrequency.Value = "Monthly" Then
ActiveDocument.Bookmarks("EarningsPerPayPeriod").Range.Text = txtAnnualSalary.Value / 12
ElseIf cboPaymentFrequency.Value = "Quarterly" Then
ActiveDocument.Bookmarks("EarningsPerPayPeriod").Range.Text = txtAnnualSalary.Value / 4
Else
ActiveDocument.Bookmarks("EarningsPerPayPeriod").Range.Text = txtAnnualSalary
End If
End Sub
Private Sub cmdOK_Click()
If ValidateData = False Then
Exit Sub
End If
'Closes the form after information is entered
frmEmploymentOffer.Hide
Unload frmEmploymentOffer
End Sub
Private Sub UserForm_Initialize()
'Province
frmEmploymentOffer.cboProvince.AddItem "Alberta", 0
frmEmploymentOffer.cboProvince.AddItem "British Columbia", 1
frmEmploymentOffer.cboProvince.AddItem "Manitoba", 2
frmEmploymentOffer.cboProvince.AddItem "New Brunswick", 3
frmEmploymentOffer.cboProvince.AddItem "Newfoundland and Labrador", 4
frmEmploymentOffer.cboProvince.AddItem "Northwest Territories", 5
frmEmploymentOffer.cboProvince.AddItem "Nova Scotia", 6
frmEmploymentOffer.cboProvince.AddItem "Nunavut", 7
frmEmploymentOffer.cboProvince.AddItem "Ontario", 8
frmEmploymentOffer.cboProvince.AddItem "Prince Edward Island", 9
frmEmploymentOffer.cboProvince.AddItem "Quebec", 10
frmEmploymentOffer.cboProvince.AddItem "Saskatchewan", 11
frmEmploymentOffer.cboProvince.AddItem "Yukon Territory", 12
'Payment Frequency
frmEmploymentOffer.cboPaymentFrequency.AddItem "Weekly", 0
frmEmploymentOffer.cboPaymentFrequency.AddItem "Bi-Weekly", 1
frmEmploymentOffer.cboPaymentFrequency.AddItem "Monthly", 2
frmEmploymentOffer.cboPaymentFrequency.AddItem "Quarterly", 3
'Department
frmEmploymentOffer.cboDepartment.AddItem "Administration", 0
frmEmploymentOffer.cboDepartment.AddItem "Business Resource", 1
frmEmploymentOffer.cboDepartment.AddItem "Finance", 2
frmEmploymentOffer.cboDepartment.AddItem "Human Resources", 3
frmEmploymentOffer.cboDepartment.AddItem "IT", 4
frmEmploymentOffer.cboDepartment.AddItem "Legal", 5
frmEmploymentOffer.cboDepartment.AddItem "Operations", 6
frmEmploymentOffer.cboDepartment.AddItem "Sales", 7
frmEmploymentOffer.cboDepartment.AddItem "Technology", 8
End Sub
</code></pre>
| <p>You must add PopulateTemplate before hiding the userform</p>
<pre><code>Private Sub cmdOK_Click()
If ValidateData = False Then
Exit Sub
End If
PopulateTemplate
'Closes the form after information is entered
frmEmploymentOffer.Hide
End Sub
</code></pre>
|
SQL SELECT query between 2 unknown dates <p>I was trying to find symptoms between 2 dates. The date is obtained from a table and is not current date. The range is date +1 day to date+ 5 days. I wrote this code but it does not seem to work. </p>
<p>Where am I going wrong?</p>
<pre><code>SELECT answer
FROM column
WHERE BETWEEN date(date,'+1 day') AND date(date, '+5 days')
</code></pre>
| <p>--maybe like this :)
--dateadd to +5 days</p>
<p>SELECT x
FROM date a
WHERE a.yourDate BETWEEN a.yourDate and DateAdd(day, 5, a.yourDate)</p>
<p>--using GateDate();</p>
<p>SELECT x
FROM date a
WHERE a.yourDate BETWEEN getdate() and DateAdd(day, 5, getdate())</p>
|
Are two doubles of equal value guaranteed to have the same bit pattern? <p>In C, is there a guarantee that two doubles whose values are equal (<code>double1 == double2</code>) will have identical bit patterns?</p>
| <p>There is no such guarantee.</p>
<p>For example, in <a href="https://en.wikipedia.org/wiki/IEEE_floating_point" rel="nofollow">IEEE floating point format</a>, there exists the concept of negative 0. It compares equal to positive 0 but has a different representation.</p>
<p>Here's an example of that:</p>
<pre><code>#include <stdio.h>
int main()
{
unsigned long long *px, *py;
double x = 0.0, y = -0.0;
px = (unsigned long long *)&x;
py = (unsigned long long *)&y;
printf("sizeof(double)=%zu\n",sizeof(double));
printf("sizeof(unsigned long long)=%zu\n",sizeof(unsigned long long));
printf("x=%f,y=%f,equal=%d\n",x,y,(x==y));
printf("x=%016llx,y=%016llx\n",*px,*py);
return 0;
}
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>sizeof(double)=8
sizeof(unsigned long long)=8
x=0.000000,y=-0.000000,equal=1
x=0000000000000000,y=8000000000000000
</code></pre>
<p>EDIT:</p>
<p>Here's a revised example that doesn't rely on type punning:</p>
<pre><code>#include <stdio.h>
void print_bytes(char *name, void *p, size_t size)
{
size_t i;
unsigned char *pdata = p;
printf("%s =", name);
for (i=0; i<size; i++) {
printf(" %02x", pdata[i]);
}
printf("\n");
}
int main()
{
double x = 0.0, y = -0.0;
printf("x=%f,y=%f,equal=%d\n",x,y,(x==y));
print_bytes("x", &x, sizeof(x));
print_bytes("y", &y, sizeof(y));
return 0;
}
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>x=0.000000,y=-0.000000,equal=1
x = 00 00 00 00 00 00 00 00
y = 00 00 00 00 00 00 00 80
</code></pre>
<p>You can see here the difference in representation between the two. One has the sign bit set while the other doesn't.</p>
|
CSS: Fixed-first-column Table? (CSS only!) <p>I've been trying to figure out a way to take a standard table and create a fixed-column table where the first column is fixed while the rest scrolls. There's a couple ways that I think make sense, so I'll start with that.</p>
<p>The first way that makes sense to me is to simply break the table code format by creating a separate table as the column that we want to be by itself, something like this:</p>
<pre><code><div class="table-container">
<div class="table-column">
<table>
<thead><tr><th>&nbsp;</th></tr></thead>
<tbody>
<tr><td>Side Header 1</td></tr>
<tr><td>Side Header 2</td></tr>
<tr><td>Side Header 3</td></tr>
<tr><td>Side Header 4</td></tr>
<tr><td>Side Header 5</td></tr>
<tr><td>Side Header 6</td></tr>
</tbody>
</table>
</div>
<div class="table-column" style="overflow-x: auto;">
<table>
<thead>
<tr><th>Top Header 1</th><th>Top Header 2</th></tr>
</thead>
<tbody>
<tr><td>Row 1, Cell 1</td><td>Row 1, Cell 2</td></tr>
<tr><td>Row 2, Cell 1</td><td>Row 2, Cell 2</td></tr>
<tr><td>Row 3, Cell 1</td><td>Row 3, Cell 2</td></tr>
<tr><td>Row 4, Cell 1</td><td>Row 4, Cell 2</td></tr>
<tr><td>Row 5, Cell 1</td><td>Row 5, Cell 2</td></tr>
<tr><td>Row 6, Cell 1</td><td>Row 6, Cell 2</td></tr>
</tbody>
</table>
</div>
</div>
</code></pre>
<p>We make the first column have a <code><th></code> of just blank space so that the styling for the whole table still fits.</p>
<p>What I really want to do though is make this more of a dynamic process... Obviously in that case (especially using the word 'dynamic') I could just use some JS, but there must be a way to do this in CSS... but there doesn't seem to be anything solid online... so I thought I'd give it a go.</p>
<p>The closest I've been able to come is through using <code>data-attribute:;</code> and <code>td::before</code>, like this:</p>
<pre><code><div class="box-table">
<table class="text-center hover stripes">
<thead>
<tr>
<th data-label="Cat 1">Cat 1</th>
<th>Cat 2</th>
<th>Cat 3</th>
<th>Cat 4</th>
<th>Cat 5</th>
<th>Cat 6</th>
</tr>
</thead>
<tbody>
<tr>
<td data-label="Col 1">Col 1</td>
<td>Col 2</td>
<td>Col 3</td>
<td>Col 4</td>
<td>Col 5</td>
<td>Col 6</td>
</tr>
<tr>
<td data-label="Col 1">Col 1</td>
<td>Col 2</td>
<td>Col 3</td>
<td>Col 4</td>
<td>Col 5</td>
<td>Col 6</td>
</tr>
</tbody>
</table>
</div>
<style>
tr > th:first-child,
tr > td:first-child {
padding: 0;
}
tr > th:first-child::before,
tr > td:first-child::before {
content: attr(data-label);
display: inline-block;
position: fixed;
background: #fff;
border-right: 1px solid rgba(0,0,0,0.2);
letter-spacing: 1px;
padding: 0 0.75rem;
}
<style>
</code></pre>
<p>Here's a fiddle with what I've gotten so far: <a href="https://jsfiddle.net/wn5nonu3/" rel="nofollow">https://jsfiddle.net/wn5nonu3/</a></p>
<p>There's 2 issues I've run into:</p>
<ol>
<li>The first is that because I've set the item to fixed, if the overflow of the table allows vertical scrolling then the fixed will obviously stay where they are fixed and appear out of line with the row.</li>
<li>The second issue is that I can't seem to style <code>td::before</code> (it seems to be showing 'inline' behavior regardless of what I change the <code>display:;</code> value to?).</li>
</ol>
<p>Potential solution to the second problem is to remove the padding causing the row's to be larger, set the first column to a fixed width and add that width to <code>td::before</code>. I still can't fix the first problem though. </p>
<p>I thought I'd share in case anyone has any ideas about how this could possibly work, or whether or not the route I'm taking is even really doable?</p>
<hr>
<p>jsFiddle: <a href="https://jsfiddle.net/wn5nonu3/" rel="nofollow">https://jsfiddle.net/wn5nonu3/</a> (same as one posted above, just for easy finding)</p>
<p>For the record: I know there's a number of great JS options, I just like to limit the amount of scripts I throw on my pages, and this just seems like something that would be useful.</p>
| <p>One way you could make it is by using two tables with the same style, but it's a little hard to maintain. You have to make sure both tables are on the same line and that there's no space between them. When you just wrap the table with the actual content in a div that scrolls. Honestly, I wouldn't go there unless you really don't want to use JS, but it's your call.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.table-wrapper {
width: 100%;
white-space: nowrap;
}
.table-firstcolon {
display: inline-block;
vertical-align: top;
}
.table-firstcolon td,
.table-firstcolon th {
width: 60px;
}
.table-content-wrapper {
display: inline-block;
overflow-x: scroll;
vertical-align: top;
max-width: calc(100% - 60px);
}
.table-content-wrapper>table {
display: inline-block;
vertical-align: top;
}
/* Page Setup */
*,
*::after,
*::before {
box-sizing: inherit;
}
html {
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
height: 100%;
line-height: 1.5;
width: 50%;
}
body {
min-height: 100%;
padding: 5px 10px;
/* this style is only for the fiddle, would be '0' */
width: 100%;
}
/* General Table Styling */
table {
background: #fdfdfd;
border-collapse: collapse;
border-spacing: 0;
}
th {
font-weight: bold;
}
thead,
tbody,
tfoot {
border: 1px solid #f1f1f1;
}
th, td {
padding: 6px;
text-align: left;
}
thead tr:first-child {
font-weight: bold;
border-bottom: 2px solid #eee;
}
tr:nth-child(even) {
background-color: rgba(0, 0, 0, 0.025);
}
tr:hover td {
background-color: rgba(0, 0, 0, 0.04);
color: #000;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="table-wrapper">
<table class="table-firstcolon text-center hover stripes">
<thead>
<tr>
<th>&nbsp;</th>
</tr>
</thead>
<tbody>
<tr>
<th>Row 1</th>
</tr>
<tr>
<th>Row 2</th>
</tr>
<tr>
<th>Row 3</th>
</tr>
<tr>
<th>Row 4</th>
</tr>
<tr>
<th>Row 5</th>
</tr>
<tr>
<th>Row 6</th>
</tr>
</tbody>
</table><!--
--><div class="table-content-wrapper">
<table>
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
<th>Column C</th>
<th>Column D</th>
<th>Column E</th>
</tr>
</thead>
<tbody>
<tr>
<td>A1</td>
<td>B1</td>
<td>C1</td>
<td>D1</td>
<td>E1</td>
</tr>
<tr>
<td>A2</td>
<td>B2</td>
<td>C2</td>
<td>D2</td>
<td>E2</td>
</tr>
<tr>
<td>A3</td>
<td>B3</td>
<td>C3</td>
<td>D3</td>
<td>E3</td>
</tr>
<tr>
<td>A4</td>
<td>B4</td>
<td>C4</td>
<td>D4</td>
<td>E4</td>
</tr>
<tr>
<td>A5</td>
<td>B5</td>
<td>C5</td>
<td>D5</td>
<td>E5</td>
</tr>
<tr>
<td>A6</td>
<td>B6</td>
<td>C6</td>
<td>D6</td>
<td>E6</td>
</tr>
</tbody>
</table>
</div>
</div></code></pre>
</div>
</div>
</p>
|
How to fix âSystems.Collections.Generic.IEnumerables<>â An explicate conversion exists. Are you missing a cast? <p>Iâm creating a web API in MVC. The database is (thus far) simple, only three tables. I am unable to join them, though. Iâve tried three different methods for joining tables in the controller, and all return the same error, which is: </p>
<blockquote>
<p>Cannot covert type (something*) to
âSystems.Collections.Generic.IEnumerables< SalesDbApi.Sample>â An
explicate conversion exists. Are you missing a cast?</p>
</blockquote>
<p>(* The "something" portion is different depending on how the join occurs but the rest of the message remains the same, so I am assuming it is the relevant part.)</p>
<p>Iâm guessing there is something wrong with how I have setup my Entity Relationships in Linq, because if I donât do a join and just do a select all from Sample I get the following JSON back:</p>
<pre><code>{"SampleId":10,"Barcode":"863760","CreatedAt":"2016-01-25T00:00:00","CreatedBy":10,"StatusID":3,"User":null,"Status":null}
</code></pre>
<p>User and Status arenât fields in the Sample table. They are the names of the tables I am trying to link with, so I wouldn't expect them to appear. </p>
<p>Any idea on what I've done wrong?</p>
<p>Here are my three models:</p>
<p>Users.cs</p>
<pre><code>namespace SalesDbApi
{
using System;
using System.Collections.Generic;
public partial class User
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public User()
{
this.Samples = new HashSet<Sample>();
}
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Sample> Samples { get; set; }
}
}
</code></pre>
<p>Statuses.cs</p>
<pre><code>namespace SalesDbApi
{
using System;
using System.Collections.Generic;
public partial class Status
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Status()
{
this.Samples = new HashSet<Sample>();
}
public int StatusId { get; set; }
public string Status1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Sample> Samples { get; set; }
}
}
</code></pre>
<p>Samples.cs</p>
<pre><code>namespace SalesDbApi
{
using System;
using System.Collections.Generic;
public partial class Sample
{
public int SampleId { get; set; }
public string Barcode { get; set; }
public Nullable<System.DateTime> CreatedAt { get; set; }
public int CreatedBy { get; set; }
public int StatusID { get; set; }
public virtual User User { get; set; }
public virtual Status Status { get; set; }
}
}
</code></pre>
<p>Hereâs the code from the controller</p>
<p>SalesUsersController.cs</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using SalesDbApi;
namespace SalesProject.Controllers
{
public class SalesUsersController : ApiController
{
webapitestdbEntities1 db = new webapitestdbEntities1();
public IEnumerable<Sample> Get()
{
{
db.Configuration.ProxyCreationEnabled = false;
var query = from x in db.Samples
join q in db.Users
on x.CreatedBy equals q.UserId
select q.FirstName;
return query.ToList();
}
}
</code></pre>
| <p>i think table Samples or table users not a data in database. besause linq can't accommodate table with no data.</p>
|
OAuth2 auth on postman when token at hand <p>How to configure postman when you already have a token/bearer key at hand?</p>
<p>Was hoping it would be somewhat similar with seting up an OAuth2.0 authentication with SoapUI that you can just input the bearer/token key.</p>
| <p>If you have an access token, you can configure POSTman by setting up a custom Authorization header. Setup:</p>
<pre><code>Authorization: Bearer <accessToken>
</code></pre>
<p>And if the API you are accessing supports bearer tokens, and you are providing a valid access token, then it should work.</p>
|
JavaScript element does not display on mouseover <p>I have two elements. One is "menu1" and is designed to unhide "atlas_menu1" on mouseover, and hide it on mouseout. My issue is that I also want "atlas_menu1" to stay unhidden when the mouse is over itself as well, but it isn't working. Here is the code I have:</p>
<pre><code><script type="text/javascript">
window.a = document.getElementById("menu1");
window.e = document.getElementById("atlas_menu1");
a.onmouseover=function(){ e.style.display = "block"; };
a.onmouseout=function(){ e.style.display = "none"; };
e.onmouseover=function(){ e.style.display = "block"; };
e.onmouseout=function(){ e.style.display = "none"; };
</script>
</code></pre>
<p>Any thoughts as to how this could be done correctly? Here is the website to see, if you hover over the menu option "Who We Are" you will see the menu come down, but on hover over the menu it disappears. <a href="http://linden.flywheelsites.com" rel="nofollow">http://linden.flywheelsites.com</a></p>
| <pre><code>#hiddenpanel{
width: 150px;
height:150px;
background: green;
display: inline-block;
display: none;
}
</code></pre>
<p>here is a working sample: <a href="https://jsfiddle.net/huspg48w/2/" rel="nofollow">https://jsfiddle.net/huspg48w/2/</a></p>
|
How can I include response data in Rails logs? <p>I noticed that Rails logs show the request-response duration, which means Rails first waits for the response before logging the request parameters, and other request info.</p>
<p>This means the response has already been generated upon the point of logging. Is there a way to add response data to the logs?</p>
<p>For example: If I have an <code>InquiriesController#create</code>. I hope to include the attributes of the newly created inquiry in the log item pertaining to that request.</p>
<p>I've learned that you can add more stuff to the logs using data from the <code>ActiveSupport::Notifications::Event</code>, but upon inspection these don't seem include the response data as well.</p>
<p>Hope you can help, thanks!</p>
| <p>You can write to the rails log with anything you like at any time you like within your own code. Details here:
<a href="http://guides.rubyonrails.org/debugging_rails_applications.html#the-logger" rel="nofollow">http://guides.rubyonrails.org/debugging_rails_applications.html#the-logger</a></p>
<p>eg you could put in the current set of data you've pulled out using the params, if that's what you want to log.</p>
<p>However, you can't print the response to the log until you have one... and AFAIK you only get one at the end of the process of rendering the response... no idea how you'd get access to some kind of partial response to print.</p>
<p>But perhaps your intent is based around an error somewhere... and you actually want to figure out where you are getting the error? If so... you can do that by logging along the way (including putting log statements into your views) and seeing where you get up to before the error occurs.</p>
|
Notification alerts not working <p>I need to setup notification alerts for my website. I'm using this simple <a href="https://github.com/msroot/Notify.js/" rel="nofollow">notification script</a>. I have test it on my website like this. </p>
<pre><code><div id="notifications">
<div class="alert alert-danger" role="alert">
<a class="button close" style="padding-left: 10px;" href="#">Ã</a>
<i class="fa fa-info-circle "></i>
Thanks
</div>
</div>
</code></pre>
<p><strong>Styles</strong></p>
<pre><code>#notifications {
cursor: pointer;
position: fixed;
right: 0;
z-index: 9999;
bottom: 0;
margin-bottom: 22px;
margin-right: 15px;
max-width: 300px;
}
</code></pre>
<p><strong>Script</strong></p>
<pre><code> $( document ).ready(function() {
Notify = function(text, callback, close_callback, style) {
var time = '10000';
var $container = $('#notifications');
var icon = '<i class="fa fa-info-circle "></i>';
if (typeof style == 'undefined' ) style = 'warning'
var html = $('<div class="alert alert-' + style + ' hide">' + icon + " " + text + '</div>');
$('<a>',{
text: 'Ã',
class: 'button close',
style: 'padding-left: 10px;',
href: '#',
click: function(e){
e.preventDefault()
close_callback && close_callback()
remove_notice()
}
}).prependTo(html)
$container.prepend(html)
html.removeClass('hide').hide().fadeIn('slow')
function remove_notice() {
html.stop().fadeOut('slow').remove()
}
var timer = setInterval(remove_notice, time);
$(html).hover(function(){
clearInterval(timer);
}, function(){
timer = setInterval(remove_notice, time);
});
html.on('click', function () {
clearInterval(timer)
callback && callback()
remove_notice()
});
}
});
</code></pre>
<p>The notification is appearing correctly because of css styling. But the script is not working. If I click close icon on notification, it's not closing. When I reload the page, it stays on the(auto closing is also not working) What ami I missing in my script?</p>
| <p>Your requirements are a bit difficult to understand. You refer to the "notification" appearing correctly, but the only thing I see appearing is <code>x Thanks</code> in the bottom-right corner. However, that's not a notification, it's coming from your markup. It has no event associated with it, so nothing will happen when it is clicked.</p>
<p>Your main issue seems to be that you are defining something called <code>Notify</code>, but then not doing anything with it. To help you resolve this, please see the snippet below. It's probably not exactly what you want, but I think it's a lot closer.</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() {
Notify = function(text, callback, close_callback, style) {
var time = '10000';
var $container = $('#notifications');
var icon = '<i class="fa fa-info-circle "></i>';
if (typeof style == 'undefined' ) style = 'warning';
var html = $('<div class="alert alert-' + style + ' hide">' + icon + " " + text + '</div>');
$('<a>', {
text: 'Ã',
class: 'button close',
style: 'padding-left: 10px;',
href: '#',
click: function(e) {
e.preventDefault();
e.stopPropagation();
close_callback();
remove_notice();
}
}).prependTo(html);
$container.prepend(html);
html.removeClass('hide').hide().fadeIn('slow');
function remove_notice() {
// html.stop().fadeOut('slow').remove()
html.fadeOut('slow', function() {
$(this).remove();
});
}
var timer = setInterval(remove_notice, time);
$(html).hover(function() {
setMessage('You hovered over me.');
clearInterval(timer);
}, function(){
if (parseInt(html.css('opacity')) === 1 ) {
// element is not currently being faded out
setMessage('You stopped hovering over me.');
timer = setInterval(remove_notice, time);
}
});
html.on('click', function() {
clearInterval(timer);
callback && callback();
remove_notice();
});
}
var notification = new Notify('This is a notification.', function() {
setMessage('You clicked my text.');
}, function() {
setMessage('You clicked my "x".');
});
});
function setMessage(messageText) {
$('#testMessage').text(messageText);
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#notifications {
cursor: pointer;
position: fixed;
right: 0;
z-index: 9999;
bottom: 0;
margin-bottom: 22px;
margin-right: 15px;
max-width: 300px;
}
#testMessage {
position: fixed;
right: 0;
z-index: 9999;
top: 0;
margin-top: 22px;
margin-right: 15px;
max-width: 300px;
}</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 src="https://cdnjs.cloudflare.com/ajax/libs/notify/0.4.2/notify.min.js"></script>
<div id="testMessage"></div>
<div id="notifications">
<!-- <div class="alert alert-danger" role="alert">
<a class="button close" style="padding-left: 10px;" href="#">Ã</a>
<i class="fa fa-info-circle "></i>
Thanks
</div> -->
</div></code></pre>
</div>
</div>
</p>
|
Get img src within html file in Laravel <p>How can i get the image if I was given a URL with lots of img <code>src</code>? I am using Laravel 5.2.</p>
<p>This takes too long to load given that I have 6,000 links. Thanks in advance.</p>
<pre><code>$url="$products->product_url";
$html = file_get_contents($url);
$doc = new DOMDocument();
@$doc->loadHTML($html);
$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag) {
echo $tag->getAttribute('src');
}
</code></pre>
| <p>Firstable you need to find some kind of <code>class</code> of <code>id</code> of parent element that contain image that you need for example:</p>
<pre><code><body>
// bla-bla-bla
<div class="content">
<img src="img.png" />
</div>
</body>
</code></pre>
<p>You can do follow with ZendDomQuery:</p>
<pre><code>$finder = new Zend_Dom_Query($html);
$node = $finder->query("div[class~='content'] img");
</code></pre>
|
Count even numbers from function output in R <p>I am working through the <a href="https://projecteuler.net/" rel="nofollow">Euler Problems</a>, and the problem is to sum the even terms in a Fibonacci sequence up to the length where the last term is < 4e6. I got it eventually but the following method of counting the even numbers did not work, and I am curious as to why.</p>
<p>First, this method of counting even numbers from a sequence works:</p>
<pre><code>numbers <- 1:32
N <- length(numbers)
total <- rep(0,N)
for (i in numbers){
if(i %% 2 == 0) total[i] <-i
}
sum(total) #272
</code></pre>
<p>Then, this Fibb sequence works:</p>
<pre><code>Fibb<-function(x){
y <- 1:x
y[1] = 1
y[2] = 2
for (i in 3:x){
y[i] <- y[i-2] + y[i-1]
}
return(y)
}
</code></pre>
<p>but the same sum function I used on the first sequence doesn't work:</p>
<pre><code>numbers <- as.integer(Fibb(32)) # 1, 2, 3, 5, 8, 13, 21...
N <- length(numbers)
total <- rep(0,N)
for (i in numbers){
if(i %% 2 == 0) total[i] <-i
}
sum(total) #NA
</code></pre>
<p>The <code>total</code> of the third chunk is a large numeric, mostly composed of NAs.</p>
<p>EDIT: What I'd like to know is why the loop in the first block of code runs correctly and not that in the third; I copied and pasted likes 6-7, from the first chunk to the third, the only difference is the "numbers" sequence.</p>
<p>Has anyone encountered a problem like this?
Thanks!</p>
| <p>It is because you are using elements of <code>numbers</code> as your index into <code>total</code>.</p>
<p>See how you have <code>for (i in numbers)</code>. So (for example) when considering the Fibbonaci number 2584 in <code>numbers</code>, you are setting <code>total[2584] <- 1</code>.</p>
<p>Your eventual <code>total</code> vector is 3524578 elements long (!!) when it only needs to be 32 long. All the other elements that you don't store a result in are set to <code>NA</code>, and the <code>sum</code> of <code>NA</code> is <code>NA</code>.</p>
<p>Separate out your Fibonacci number (which can be arbitrarily large) from your index into <code>total</code> (which only goes up to 32). To make the index, you can use <code>seq_along(numbers)</code> which is essentially <code>1:length(numbers)</code>. Then use <code>numbers[i]</code> to get that Fibonacci number.</p>
<pre><code>for (i in seq_along(numbers)) {
if(numbers[i] %% 2 == 0) total[i] <- 1
}
</code></pre>
|
MaterializeCSS NavBar and SideNav <p>I'm creating a sb admin 2 like page where it has 2 navigations that looks like this:</p>
<p><a href="http://i.stack.imgur.com/pY9CK.png" rel="nofollow"><img src="http://i.stack.imgur.com/pY9CK.png" alt="enter image description here"></a></p>
<p>And what I've done so far is this:</p>
<p><a href="http://i.stack.imgur.com/pP2ST.png" rel="nofollow"><img src="http://i.stack.imgur.com/pP2ST.png" alt="enter image description here"></a></p>
<p>As you can see, the side navigation extends at the top bar. My code so far is this:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<!--Import Google Icon Font-->
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div class="navbar-fixed">
<!-- Dropdown Structure -->
<ul id="dropdown1" class="dropdown-content">
<li><a href="#!">User Profile</a></li>
<li><a href="#!">Settings</a></li>
<li class="divider"></li>
<li><a href="#!">Logout</a></li>
</ul>
<nav class="light-blue lighten-1" role="navigation">
<div class="nav-wrapper container">
<a href="#!" class="brand-logo">Point of Sale</a>
<ul class="right hide-on-med-and-down">
<!-- Dropdown Trigger -->
<li><a class="dropdown-button" href="#!" data-activates="dropdown1">Profile<i class="material-icons right">arrow_drop_down</i></a></li>
</ul>
</div>
</nav>
</div>
<ul id="slide-out" class="side-nav fixed">
<li><a href="#!">First Sidebar Link</a></li>
<li><a href="#!">Second Sidebar Link</a></li>
</ul>
<!--Import jQuery before materialize.js-->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
<script>
(function($){
$(function(){
$('.button-collapse').sideNav();
}); // end of document ready
})(jQuery); // end of jQuery name space
</script>
</body>
</html>
</code></pre>
<p>What I am trying to achieve is this:</p>
<p><a href="http://i.stack.imgur.com/U940T.png" rel="nofollow"><img src="http://i.stack.imgur.com/U940T.png" alt="enter image description here"></a></p>
<p>Is this possible?</p>
| <p><a href="http://materializecss.com/side-nav.html" rel="nofollow">As the Side Nav documentations says:</a></p>
<p>You have to offset your content by the width of the side menu.
so do like this</p>
<pre><code><style type="text/css">
.wrapper {
padding-left: 300px;
}
</style>
</code></pre>
<p>and wrap your code in wrapper div</p>
<pre><code><div class="wrapper">
<div class="">
<!-- Dropdown Structure -->
<ul id="dropdown1" class="dropdown-content">
<li><a href="#!">User Profile</a></li>
<li><a href="#!">Settings</a></li>
<li class="divider"></li>
<li><a href="#!">Logout</a></li>
</ul>
<nav class="light-blue lighten-1" role="navigation">
<div class="nav-wrapper container">
<a href="#!" class="brand-logo">Point of Sale</a>
<ul class="right hide-on-med-and-down">
<!-- Dropdown Trigger -->
<li><a class="dropdown-button" href="#!" data-activates="dropdown1">Profile<i class="material-icons right">arrow_drop_down</i></a></li>
</ul>
</div>
</nav>
</div>
</div>
<ul id="slide-out" class="side-nav fixed">
<li><a href="#!">First Sidebar Link</a></li>
<li><a href="#!">Second Sidebar Link</a></li>
</ul>
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.