title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
XSLT output JSON instead of XML | <p>I have a XSLT that works the way I want when it outputs XML, however I would like to change the XSLT it to output JSON instead. The problem appears to me with the inner most for-each loop, but I'm not sure. If there is way to make this more efficient I'm also interested in your suggestions. </p>
<p>Sample input XML</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<root xmlns:xs="http://www.w3.org/2001/XMLSchema">
<Metric measType="1526727075"
measResult="0"
endTime="2016-08-25T04:30:00-07:00"
measObjLdn="LTHBC0126858/GTPU:Board Type=MPT, Cabinet No.=0, Subrack No.=1, Slot No.=7"
Element_Type="ENODEB"
Key1="LTHBC0126858"
TableName="HH_ENODEB"
ColumnName="H1526727075"
H1526727075="0"/>
<Metric measType="1526727076"
measResult="0"
endTime="2016-08-25T04:30:00-07:00"
measObjLdn="LTHBC0126858/GTPU:Board Type=MPT, Cabinet No.=0, Subrack No.=1, Slot No.=7"
Element_Type="ENODEB"
Key1="LTHBC0126858"
TableName="HH_ENODEB"
ColumnName="H1526727076"
H1526727076="0"/>
<Metric measType="1526727077"
measResult="0"
endTime="2016-08-25T04:30:00-07:00"
measObjLdn="LTHBC0126858/GTPU:Board Type=MPT, Cabinet No.=0, Subrack No.=1, Slot No.=7"
Element_Type="ENODEB"
Key1="LTHBC0126858"
TableName="HH_ENODEB"
ColumnName="H1526727077"
H1526727077="0"/>
</root>
</code></pre>
<p>This is the XSLT that outputs XML and works the way I expect</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.0">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="root">
<root>
<xsl:for-each-group select="Metric" group-by="@measObjLdn">
<xsl:sort select="current-grouping-key()"/>
<xsl:variable name="curr_key" select="current-grouping-key()"/>
<xsl:for-each-group select="current-group()" group-by="@TableName">
<xsl:sort select="current-grouping-key()"/>
<xsl:if test="current-grouping-key() != ''">
<Table TableName="{current-grouping-key()}">
<xsl:for-each select="current-group()">
<xsl:attribute name="Stamp">
<xsl:value-of select="@endTime"/>
</xsl:attribute>
<xsl:attribute name="measObjLdn">
<xsl:value-of select="$curr_key"/>
</xsl:attribute>
<xsl:attribute name="Element_Type">
<xsl:value-of select="@Element_Type"/>
</xsl:attribute>
<xsl:attribute name="Key1">
<xsl:value-of select="@Key1"/>
</xsl:attribute>
<xsl:for-each select="@*">
<xsl:if test="starts-with(name(), 'H')">
<xsl:attribute name="{name()}">
<xsl:value-of select="number(.)"/>
</xsl:attribute>
</xsl:if>
</xsl:for-each>
</xsl:for-each>
</Table>
</xsl:if>
</xsl:for-each-group>
</xsl:for-each-group>
</root>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>This is my JSON output code, but not working as expected.</p>
<pre><code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.0">
<xsl:output method="text" encoding="utf-8"/>
<xsl:strip-space elements="*"/>
<xsl:template match="root">
<xsl:text>{"root":{</xsl:text>
<xsl:for-each-group select="Metric" group-by="@TableName">
<xsl:sort select="current-grouping-key()"/>
<xsl:if test="current-grouping-key() != ''">
<xsl:text>"Table":[</xsl:text>
<xsl:text>{"TableName":"</xsl:text>
<xsl:value-of select="current-grouping-key()"/>
<!--<Table TableName="{current-grouping-key()}">-->
<xsl:text>",</xsl:text>
<xsl:for-each-group select="current-group()" group-by="@measObjLdn">
<xsl:sort select="current-grouping-key()"/>
<xsl:for-each select="current-group()">
<xsl:text>"Stamp":"</xsl:text>
<xsl:value-of select="@endTime"/>
<xsl:text>",</xsl:text>
<xsl:text>"measObjLdn":"</xsl:text>
<xsl:value-of select="current-grouping-key()"/>
<xsl:text>",</xsl:text>
<xsl:text>"Element_Type":"</xsl:text>
<xsl:value-of select="@Element_Type"/>
<xsl:text>",</xsl:text>
<xsl:text>"Key1":"</xsl:text>
<xsl:value-of select="@Key1"/>
<xsl:text>",</xsl:text>
<xsl:for-each select="@attribute()">
<xsl:if test="starts-with(name(), 'H')">
<xsl:text>"</xsl:text>
<xsl:value-of select="name()"/>
<xsl:text>":"</xsl:text>
<xsl:value-of select="number(.)"/>
<xsl:text>"</xsl:text>
<xsl:if test="position() != last()">
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:if>
</xsl:for-each>
</xsl:for-each>
</xsl:for-each-group>
<!--</Table>-->
<xsl:text>}</xsl:text>
<xsl:if test="position() != last()">
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:if>
</xsl:for-each-group>
<xsl:text>}</xsl:text>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>Good point, so the XML version groups all the attributes for the same table together; Given the sample above the XML output is as follows</p>
<pre><code><root xmlns:xs="http://www.w3.org/2001/XMLSchema">
<Table TableName="HH_ENODEB" Stamp="2016-08-25T04:30:00-07:00" measObjLdn="LTHBC0126858/GTPU:Board Type=MPT, Cabinet No.=0, Subrack No.=1, Slot No.=7" Element_Type="ENODEB" Key1="LTHBC0126858" H1526727075="0" H1526727076="0" H1526727077="0"/>
</code></pre>
<p></p>
<p>JSON example output is not a JSON version of the XML version which I expected.</p>
<pre><code>{"root":{"Table":[{"TableName":"HH_ENODEB","Stamp":"2016-08-25T04:30:00-07:00","measObjLdn":"LTHBC0126858/GTPU:Board Type=MPT, Cabinet No.=0, Subrack No.=1, Slot No.=7","Element_Type":"ENODEB","Key1":"LTHBC0126858","H1526727075":"0""Stamp":"2016-08-25T04:30:00-07:00","measObjLdn":"LTHBC0126858/GTPU:Board Type=MPT, Cabinet No.=0, Subrack No.=1, Slot No.=7","Element_Type":"ENODEB","Key1":"LTHBC0126858","H1526727076":"0""Stamp":"2016-08-25T04:30:00-07:00","measObjLdn":"LTHBC0126858/GTPU:Board Type=MPT, Cabinet No.=0, Subrack No.=1, Slot No.=7","Element_Type":"ENODEB","Key1":"LTHBC0126858","H1526727077":"0"}}
</code></pre> | 0 |
Error in is.data.frame(x) : object '' not found , how could I fix this? | <p>I'm trying to run correlations on R.</p>
<p>This is my code so far:</p>
<pre><code>library("foreign")
mydata<-read.csv(" ",header=FALSE)
options(max.print=1000000)
attach(mydata)
cor(as.numeric(agree_election),as.numeric(agree_party))
</code></pre>
<p>Then it gives me the error that object "agree_election" is not an object.</p>
<p>However, agree_election is just one of the headers of my columns for my excel spreadsheet.How do I fix this?</p> | 0 |
How do I exclude a specific URL in a filter in Spring? | <p>I have a basic application filter config that looks like this:</p>
<pre><code>@Configuration
public class ApplicationFilterConfig {
/**
* Check if user is logged in
*/
@Bean
public FilterRegistrationBean applicationFilterRegistration() {
// created a collections that need logins to be validated.
ArrayList<String> urlPatterns = new ArrayList<String>();
urlPatterns.add("/home");
urlPatterns.add("/about");
urlPatterns.add("/contact");
// ...
LoginFilter loginFilter = new LoginFilter();
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(loginFilter);
registration.setUrlPatterns(urlPatterns);
registration.setOrder(1);
return registration;
}
}
</code></pre>
<p>However, the list <code>urlPatterns</code> grows to be very long, even when using the star annotation (e.g. <code>/employees/*</code>). The main reason why I don't just use <code>/*</code> is because I don't want to require login validation for my login page. If I did, it'd create an infinite loop of redirects. </p>
<p>Does the <code>FilterRegistrationBean</code> class allow you to apply a filter to all URL patterns <em>except</em> certain patterns? </p>
<p>I could put everything except the login page in a directory and set my URL pattern to be <code>/subdirectory/*</code> but that adds an unnecessary level of depth to every file in my webapp. </p> | 0 |
Android Play Vimeo Video | <p>I want to play my Vimeo videos and I've followed the steps in <a href="https://github.com/vimeo/vimeo-networking-java" rel="nofollow">https://github.com/vimeo/vimeo-networking-java</a>.</p>
<p>I used this method to get the Video object and then load it into a WebView.</p>
<pre><code>VimeoClient.getInstance().fetchNetworkContent(String uri, ModelCallback callback)
</code></pre>
<p>However, when I logged the result, it seems to indicate that it fails.</p>
<p>Here are my 2 Java files.</p>
<p><strong>MyVimeoApplication.java</strong></p>
<pre><code>import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
import com.vimeo.networking.Configuration;
import com.vimeo.networking.Vimeo;
import com.vimeo.networking.VimeoClient;
public class MyVimeoApplication extends Application
{
private static final String SCOPE = "private public interact";
private static final boolean IS_DEBUG_BUILD = false;
// Switch to true to see how access token auth works.
private static final boolean ACCESS_TOKEN_PROVIDED = false;
private static Context mContext;
@Override
public void onCreate()
{
super.onCreate();
mContext = this;
Configuration.Builder configBuilder;
// This check is just as for the example. In practice, you'd use one technique or the other.
if (ACCESS_TOKEN_PROVIDED)
{
configBuilder = getAccessTokenBuilder();
Log.d("ACCESS_TOKEN", "PROVIDED");
}
else
{
configBuilder = getClientIdAndClientSecretBuilder();
Log.d("ACCESS_TOKEN", "NOT PROVIDED");
}
if (IS_DEBUG_BUILD) {
// Disable cert pinning if debugging (so we can intercept packets)
configBuilder.enableCertPinning(false);
configBuilder.setLogLevel(Vimeo.LogLevel.VERBOSE);
}
VimeoClient.initialize(configBuilder.build());
}
public Configuration.Builder getAccessTokenBuilder() {
// The values file is left out of git, so you'll have to provide your own access token
String accessToken = getString(R.string.access_token);
return new Configuration.Builder(accessToken);
}
public Configuration.Builder getClientIdAndClientSecretBuilder() {
// The values file is left out of git, so you'll have to provide your own id and secret
String clientId = getString(R.string.client_id);
String clientSecret = getString(R.string.client_secret);
String codeGrantRedirectUri = getString(R.string.deeplink_redirect_scheme) + "://" +
getString(R.string.deeplink_redirect_host);
Configuration.Builder configBuilder =
new Configuration.Builder(clientId, clientSecret, SCOPE, null,
null);
// configBuilder.setCacheDirectory(this.getCacheDir())
// .setUserAgentString(getUserAgentString(this)).setDebugLogger(new NetworkingLogger())
// // Used for oauth flow
// .setCodeGrantRedirectUri(codeGrantRedirectUri);
return configBuilder;
}
public static Context getAppContext() {
return mContext;
}
public static String getUserAgentString(Context context) {
String packageName = context.getPackageName();
String version = "unknown";
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(packageName, 0);
version = pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
System.out.println("Unable to get packageInfo: " + e.getMessage());
}
String deviceManufacturer = Build.MANUFACTURER;
String deviceModel = Build.MODEL;
String deviceBrand = Build.BRAND;
String versionString = Build.VERSION.RELEASE;
String versionSDKString = String.valueOf(Build.VERSION.SDK_INT);
return packageName + " (" + deviceManufacturer + ", " + deviceModel + ", " + deviceBrand +
", " + "Android " + versionString + "/" + versionSDKString + " Version " + version +
")";
}
}
</code></pre>
<p><strong>MainActivity.java</strong></p>
<pre><code>import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.widget.Toast;
import com.vimeo.networking.VimeoClient;
import com.vimeo.networking.callbacks.AuthCallback;
import com.vimeo.networking.callbacks.ModelCallback;
import com.vimeo.networking.model.Video;
import com.vimeo.networking.model.error.VimeoError;
public class MainActivity extends AppCompatActivity
{
private VimeoClient mApiClient = VimeoClient.getInstance();
private ProgressDialog mProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("All of your API are belong to us...");
// ---- Client Credentials Auth ----
if (mApiClient.getVimeoAccount().getAccessToken() == null) {
// If there is no access token, fetch one on first app open
authenticateWithClientCredentials();
}
}
// You can't make any requests to the api without an access token. This will get you a basic
// "Client Credentials" gran which will allow you to make requests
private void authenticateWithClientCredentials() {
mProgressDialog.show();
mApiClient.authorizeWithClientCredentialsGrant(new AuthCallback() {
@Override
public void success()
{
Toast.makeText(MainActivity.this, "Client Credentials Authorization Success", Toast.LENGTH_SHORT).show();
mProgressDialog.hide();
mApiClient.fetchNetworkContent("https://vimeo.com/179708540", new ModelCallback<Video>(Video.class)
{
@Override
public void success(Video video)
{
// use the video
Log.d("VIDEO", "SUCCESS");
String html = video.embed != null ? video.embed.html : null;
if(html != null)
{
// html is in the form "<iframe .... ></iframe>"
// load the html, for instance, if using a WebView on Android, you can perform the following:
WebView webview = (WebView) findViewById(R.id.webView); // obtain a handle to your webview
webview.loadData(html, "text/html", "utf-8");
}
}
@Override
public void failure(VimeoError error)
{
Log.d("VIDEO", "FAIL");
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
// voice the error
}
});
}
@Override
public void failure(VimeoError error) {
Toast.makeText(MainActivity.this, "Client Credentials Authorization Failure", Toast.LENGTH_SHORT).show();
mProgressDialog.hide();
}
});
}
}
</code></pre> | 0 |
Angular 2 REST request HTTP status code 401 changes to 0 | <p>I'm developing an Angular2 application. It seems when my access-token expires the 401 HTTP Status code gets changed to a value of 0 in the Response object. I'm receiving 401 Unauthorized yet the ERROR Response object has a status of 0. This is preventing me from trapping a 401 error and attempting to refresh the token. What's causing the 401 HTTP status code to be changed into HTTP status code of 0?</p>
<p>Here's screenshot from Firefox's console:</p>
<p><a href="https://i.stack.imgur.com/cgGQv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cgGQv.png" alt="enter image description here"></a></p>
<p>Here's my code:</p>
<pre><code>get(url: string, options?: RequestOptionsArgs): Observable<any>
{
//console.log('GET REQUEST...', url);
return super.get(url, options)
.catch((err: Response): any =>
{
console.log('************* ERROR Response', err);
if (err.status === 400 || err.status === 422)
{
return Observable.throw(err);
}
//NOT AUTHENTICATED
else if (err.status === 401)
{
this.authConfig.DeleteToken();
return Observable.throw(err);
}
else
{
// this.errorService.notifyError(err);
// return Observable.empty();
return Observable.throw(err);
}
})
// .retryWhen(error => error.delay(500))
// .timeout(2000, new Error('delay exceeded'))
.finally(() =>
{
//console.log('After the request...');
});
}
</code></pre>
<p>This code resides in a custom http service that extends Angular2's HTTP so I can intercept errors in a single location.</p>
<p>In Google Chrome, I get this error message:</p>
<p>XMLHttpRequest cannot load <a href="https://api.cloudcms.com/repositories/XXXXXXXXXXXXXXXX/branches/XXXXXXXXXXXXXXXX/nodesXXXXXXXXXXXXXXXX" rel="noreferrer">https://api.cloudcms.com/repositories/XXXXXXXXXXXXXXXX/branches/XXXXXXXXXXXXXXXX/nodesXXXXXXXXXXXXXXXX</a>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '<a href="http://screwtopmedia.local.solutiaconsulting.com" rel="noreferrer">http://screwtopmedia.local.solutiaconsulting.com</a>' is therefore not allowed access. The response had HTTP status code 401.</p>
<p>This is confusing because I am including 'Access-Control-Allow-Origin' header in request.</p>
<p>Here's a picture of results received in Google Chrome:</p>
<p><a href="https://i.stack.imgur.com/B4sb7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/B4sb7.png" alt="enter image description here"></a></p>
<p>I've tried accessing 'WWW-Authenticate' Response Header as a means to trap for 401. However, the following code returns a NULL:</p>
<pre><code>err.headers.get("WWW-Authenticate")
</code></pre>
<p>It's puzzling that I'm getting a CORS issue because I'm not getting any CORS errors when a valid access token is provided.</p>
<p>How do I trap for 401 HTTP status code? Why is 401 HTTP status code being changed to 0?</p>
<p>Thanks for your help.</p> | 0 |
Python speech recognition error converting mp3 file | <p>My first try on audio to text. </p>
<pre><code>import speech_recognition as sr
r = sr.Recognizer()
with sr.AudioFile("/path/to/.mp3") as source:
audio = r.record(source)
</code></pre>
<p>When I execute the above code, the following error occurs,</p>
<pre><code><ipython-input-10-72e982ecb706> in <module>()
----> 1 with sr.AudioFile("/home/yogaraj/Documents/Python workouts/Python audio to text/show_me_the_meaning.mp3") as source:
2 audio = sr.record(source)
3
/usr/lib/python2.7/site-packages/speech_recognition/__init__.pyc in __enter__(self)
197 aiff_file = io.BytesIO(aiff_data)
198 try:
--> 199 self.audio_reader = aifc.open(aiff_file, "rb")
200 except aifc.Error:
201 assert False, "Audio file could not be read as WAV, AIFF, or FLAC; check if file is corrupted"
/usr/lib64/python2.7/aifc.pyc in open(f, mode)
950 mode = 'rb'
951 if mode in ('r', 'rb'):
--> 952 return Aifc_read(f)
953 elif mode in ('w', 'wb'):
954 return Aifc_write(f)
/usr/lib64/python2.7/aifc.pyc in __init__(self, f)
345 f = __builtin__.open(f, 'rb')
346 # else, assume it is an open file object already
--> 347 self.initfp(f)
348
349 #
/usr/lib64/python2.7/aifc.pyc in initfp(self, file)
296 self._soundpos = 0
297 self._file = file
--> 298 chunk = Chunk(file)
299 if chunk.getname() != 'FORM':
300 raise Error, 'file does not start with FORM id'
/usr/lib64/python2.7/chunk.py in __init__(self, file, align, bigendian, inclheader)
61 self.chunkname = file.read(4)
62 if len(self.chunkname) < 4:
---> 63 raise EOFError
64 try:
65 self.chunksize = struct.unpack(strflag+'L', file.read(4))[0]
</code></pre>
<p>I don't know what I'm going wrong. Can someone say me what I'm wrong in the above code?</p> | 0 |
Huge space between title and plot matplotlib | <p>I've a issue with matplotlib that generates a plot(graph) very far from the title. My code is:</p>
<pre><code>df = pandas.read_csv(csvpath, delimiter=',',
index_col=0,
parse_dates=[0], dayfirst=True,
names=['Date','test1'])
df.plot(subplots=True, marker='.',markersize=8, title ="test", fontsize = 10, color=['b','g','g'], figsize=(8, 22))
imagepath = 'capture.png'
plt.savefig(imagepath)
</code></pre>
<p>An example of the graph generated is:</p>
<p><a href="https://i.stack.imgur.com/ZBKEP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZBKEP.png" alt="enter image description here"></a></p>
<p>Any idea why this is happening? Thanks a lot.</p> | 0 |
R Tidytext and unnest_tokens error | <p>Very new to R and have started to use the tidytext package.</p>
<p>I'm trying to use arguments to feed into the <code>unnest_tokens</code> function so I can do multiple column analysis. So instead of this</p>
<pre><code>library(janeaustenr)
library(tidytext)
library(dplyr)
library(stringr)
original_books <- austen_books() %>%
group_by(book) %>%
mutate(linenumber = row_number(),
chapter = cumsum(str_detect(text, regex("^chapter [\\divxlc]",
ignore_case = TRUE)))) %>%
ungroup()
original_books
tidy_books <- original_books %>%
unnest_tokens(word, text)
</code></pre>
<p>The last line of code would be:</p>
<pre><code>output<- 'word'
input<- 'text'
tidy_books <- original_books %>%
unnest_tokens(output, input)
</code></pre>
<p>But I'm getting this:</p>
<blockquote>
<p>Error in check_input(x) :
Input must be a character vector of any length or a list of character
vectors, each of which has a length of 1.</p>
</blockquote>
<p>I've tried using <code>as.character()</code> without much luck. </p>
<p>Any ideas on how this would work?</p> | 0 |
How to get device's IMEI/ESN number with code programming But in android > 6 | <blockquote>
<p>My Android version is <strong>Marshmallow 6.0</strong></p>
</blockquote>
<p>How to Find / Get imei number in android > 6 programmatically.</p>
<p>Note : I added READ_PHONE_STATE permission inside AndroidManifest.xml file.</p>
<pre><code><uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
</code></pre>
<p>And inside MainActivity</p>
<pre><code>TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String deviceid = manager.getDeviceId();
//Device Id is IMEI number
Log.d("msg", "Device id " + deviceid);
</code></pre> | 0 |
Visual Studio Code snippet as keyboard shortcut key | <p>I know how to modify and create code snippets and I know how to modify shortcut keys, but how does one bring those 2 together? </p> | 0 |
Can you use @ViewChild() or similar with a router-outlet? How if so? | <p>I repeatedly run into a situation where I'd like to access a child component existing on the other side of a router outlet rather than a selector:</p>
<pre><code>Like:
<router-outlet></router-outlet>
NOT:
<selector-name></selector-name>
</code></pre>
<p>This conflicts with the ViewChild functionality as I know it, yet it seems like my component should be able to see and interact with what's inside that router-outlet just as easily as with what's inside a selector-tag.</p>
<p>For instance I tried this:</p>
<pre><code>export class RequestItemCatsComp {
@ViewChild('child') child: RequestItemsComp;
***etc...***
ngAfterViewInit() {
if (this.child) // Always child is undefined
this.groupId = this.child.groupId;
}
}
</code></pre>
<p>But naturally, <strong>child is undefined</strong> because this is the wrong way. Is there a right way?</p>
<p>I'm trying to use a service to share the data but then run into another problem "expression has changed after it was checked" which I'm hoping to remedy without a hack or enabling prod mode.</p> | 0 |
possible to whitelist ip for inbound communication to an ec2 instance behind an aws load balancer? | <p>I have a single ec2 instance running a website behind an elastic load balancer in aws. Mainly because I want to use Amazon's new and free ssl for https.</p>
<p>my challenge is, I need to whitelist my IP address in the security groups so that I am the only person that can see this website (and I can selectively add people as needed). </p>
<p>I've successfully whitelisted my IP address without a load balancer. my challenge is white listing my IP address with the load balancer proxy between my IP address and my ec2 instance.</p>
<p>it appears as if my ec2 instance will not register with the load balancer because the security group for my ec2 does not allow incoming traffic from any IP address except for my own.</p>
<p>I am looking for a way for my load balancer to be able to health check my ec2, yet only allow specific whitelisted ips actually see the website.</p> | 0 |
What does pip install . (dot) mean? | <p>I have a shell script whose last line is:</p>
<pre><code>pip install .
</code></pre>
<p>What does it do?</p>
<ul>
<li><code>pip install <package-name></code> installs the specified package</li>
<li><code>pip install -r requirements.txt</code> installs all packages specified in <code>requirements.txt</code></li>
</ul>
<p>But I am not sure what the above command does.</p> | 0 |
Importing spark.implicits._ in scala | <p>I am trying to import spark.implicits._
Apparently, this is an object inside a class in scala.
when i import it in a method like so:</p>
<pre><code>def f() = {
val spark = SparkSession()....
import spark.implicits._
}
</code></pre>
<p>It works fine, however i am writing a test class and i want to make this import available for all tests
I have tried:</p>
<pre><code>class SomeSpec extends FlatSpec with BeforeAndAfter {
var spark:SparkSession = _
//This won't compile
import spark.implicits._
before {
spark = SparkSession()....
//This won't either
import spark.implicits._
}
"a test" should "run" in {
//Even this won't compile (although it already looks bad here)
import spark.implicits._
//This was the only way i could make it work
val spark = this.spark
import spark.implicits._
}
}
</code></pre>
<p>Not only does this look bad, i don't want to do it for every test
What is the "correct" way of doing it?</p> | 0 |
Merging many arrays from Promise.all | <p>When <code>Promise.all</code> completes it returns an array of arrays that contain data. In my case the arrays are just numbers:</p>
<pre><code>[
[ 1, 4, 9, 9 ],
[ 4, 4, 9, 1 ],
[ 6, 6, 9, 1 ]
]
</code></pre>
<p>The array can be any size.</p>
<p>Currently I'm doing this:</p>
<pre><code>let nums = []
data.map(function(_nums) {
_nums.map(function(num) {
nums.push(num)
})
})
</code></pre>
<p>Is there an alternative way of doing this? Does <code>lodash</code> have any functions that are able to do this?</p> | 0 |
How to hide bar button item | <p>My screen flow is as follow</p>
<p>Login -> Registration -> CarDetails </p>
<p>All 3 above screens are in navigation-controller, but users are not allowed to go back from Car-Details to Registration. To achieve it, I've</p>
<pre><code>override func viewWillAppear(animated: Bool)
{
self.navigationItem.setHidesBackButton(true, animated:true);
}
</code></pre>
<p>in CarDetails view controller. So it hides the back button which automatically gets created if controller is in navigation-controller.</p>
<p>So far it is good.</p>
<p>After providing all detail user lands on Home Screen where I've slide out menu. From menu user can goto to CarDetail Screen as well (to update). That time instead of backButton I need slide-out menu button as left bar button. So I've created it using storyboard. </p>
<p>The problem is that it is getting displayed after Registration view as well. I need conditional show/hide functionality for it in Car-Details View.</p>
<p>I've hook for it as well, as following</p>
<pre><code>override func viewDidLoad()
{
super.viewDidLoad()
if menuButtonVisibility
{
if self.revealViewController() != nil
{
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
}
else
{
}
menuButtonVisibility=true
}
</code></pre>
<p>I only need the line to put in else block.</p>
<p><a href="https://i.stack.imgur.com/ArJKz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ArJKz.png" alt="enter image description here"></a></p> | 0 |
How to create a PDF/A file in Swift? | <p>I'd like to create a PDF/A file in my iOS app but don't really know where to start. </p>
<p>My actual code (which generates a simple PDF) is:</p>
<pre><code>_ = UIGraphicsBeginPDFContextToFile(temporaryPdfFilePath, paperSize, nil)
UIGraphicsBeginPDFPageWithInfo(paperSize, nil)
let currentContext: CGContextRef = UIGraphicsGetCurrentContext()!
</code></pre>
<p>...drawing...</p>
<pre><code>UIGraphicsEndPDFContext()
</code></pre>
<p>Is there any API or something else to follow?</p> | 0 |
Mongodb $project: $filter sub-array | <p>There is an items (mongoose) schema that looks like this (simplified to what it matters to the question):</p>
<pre><code>{
brand: {
name: String,
},
title: String,
description: [{ lang: String, text: String }],
shortDescription: [{ lang: String, text: String }],
variants: {
cnt: Number,
attrs: [
{
displayType: String,
displayContent: String,
displayName: [{ lang: String, text: String }],
name: String,
},
],
}
}
</code></pre>
<p>I'm trying to filter the items by language, so I've constructed the following query:</p>
<pre><code>db.items.aggregate([
{ $match: { 'description.lang': 'ca', 'shortDescription.lang': 'ca' } },
{ $project: {
'brand.name': 1,
title: 1,
description: {
'$filter': {
input: '$description',
as: 'description',
cond: { $eq: ['$$description.lang', 'ca'] }
}
},
shortDescription: {
'$filter': {
input: '$shortDescription',
as: 'shortDescription',
cond: { $eq: ['$$shortDescription.lang', 'ca'] }
}
},
'variants.cnt': 1,
'variants.attrs': 1
} }
])
</code></pre>
<p>And it works as expected: it filters <code>description</code> and <code>shortDescription</code> by language. Right now I'm wondering if it could be possible to filter every <code>variants.attrs.$.displayName</code> as well. Is there any way to do it?</p>
<p>I've been trying to <code>$unwind</code> <code>variant.attrs</code> but I get completly lost when trying to <code>$group</code> again and I'm not really sure if this is the best way...</p> | 0 |
Highlight in Elasticsearch | <p>This is my elasticsearch query:</p>
<pre><code>GET indexname/_search
{
"fields": ["_id", "url","T"],
"query" : {
"bool": {"should": [
{"simple_query_string": {
"query": "white",
"fields": ["T", "content"]
}}
]}
},
"highlight" : {
"pre_tags": ["<b>"],
"post_tags": ["</b>"],
"fields" : {
"content" : {"fragment_size" : 150, "number_of_fragments" : 1}
}
}
}
</code></pre>
<p>My elasticsearch query is searching for white in the fields "T" and "content", and I am highlighting the field "content" and inserting a pre and post tag b(bold).
This is the result of my query</p>
<pre><code>"hits": {
"total": 922,
"max_score": 2.369757,
"hits": [
{
"_index": "indexname",
"_type": "Searchtype",
"_id": "http://www.example.com/de/unternehmenssuche-white-paper",
"_score": 2.369757,
"fields": {
"T": [
"White Paper Unternehmenssuche"
],
"url": [
"http://www.example.com/de/unternehmenssuche-white-paper"
]
},
"highlight": {
"content": [
"/Anwendungsbeispiele Ressourcen Blog <b>White</b> Papers in Deutsche Downloads Wiki Unternehmen Vorstellung der Search Executive"
]
}
}
....
...
</code></pre>
<p>I want my highlight result to look like this</p>
<pre><code>"highlight": {
"content": [
"<b>...</b> /Anwendungsbeispiele Ressourcen Blog <b>White</b> Papers in Deutsche Downloads Wiki Unternehmen Vorstellung der Search Executive <b>...</b>"
]
}
</code></pre>
<p>I want to add <code><b>...</b></code> before and after the highlight content. What should I add in my elasticsearch query to make results look like this? Any help would be appreciated</p> | 0 |
How to use espresso to press a AlertDialog button | <p>I want to press below button using Espresso, but I'm not sure how. Should I get the resource-id? Or how to set an ID to the AlertDialog??</p>
<p><a href="https://i.stack.imgur.com/a7FYe.png" rel="noreferrer"><img src="https://i.stack.imgur.com/a7FYe.png" alt="enter image description here"></a></p>
<pre><code>@RunWith(AndroidJUnit4.class)
public class ApplicationTest {
@Rule
public ActivityTestRule<LoadingActivity> mActivityRule =
new ActivityTestRule<>(LoadingActivity.class);
@Test
public void loginClickMarker() {
//Doesn't work:
onView(withText("GA NAAR INSTELLINGEN")).perform(click());
}
}
public class PopupDialog {
public static void showGPSIsDisabled(Context context, String msg, final PopupDialogCallback popupDialogCallback) {
new AlertDialog.Builder(context)
.setTitle(context.getString(R.string.location_turned_off))
.setMessage(msg)
.setPositiveButton(context.getString(R.string.go_to_settings), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
popupDialogCallback.hasClicked();
}
}).show();
}
}
</code></pre>
<p><strong>android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with text: is "GA NAAR INSTELLINGEN"</strong></p> | 0 |
How to download excel (.xls) file from API in postman? | <p>I am having an API endpoint and Authorization token for that API.</p>
<p>The said API is for <code>.xls</code> report download, how can I view the downloaded <code>.xls</code> file using (if possible) <em>Postman</em>?</p>
<p>If it is not possible using <em>Postman</em> what are the other programmatic ways I should be looking for?</p> | 0 |
How to append a querystring to the url created by Url.Action base on a hidden fields values | <p>Here is my controller Action method</p>
<pre><code>public ActionResult ChangeStateId(int userId,int stateId)
{
return RedirectToAction("Index")
}
</code></pre>
<p>and in my anchor tag of View, i want to redirect to above action method with parameter values like this</p>
<pre><code><a href="'@Url.Action("ChangeStateId","User")?userId='+$('#hidID').val()+ '&stateId=' +$('#hidStateId'.val()")></a>;
</code></pre>
<p>but it is not working for me.</p> | 0 |
How to sort items in a list using foreach C# | <p>I need to sort the items I have in a list by age using foreach in ascending order, and so I have no idea how to. This is my code so far:</p>
<pre><code>namespace ListProject
{
public struct FamilyMem
{
public string name;
public int age;
public FamilyMem(string name,int age)
{
this.name = name;
this.age = age;
}
}
class Program
{
static void Main(string[] args)
{
FamilyMem Jack = new FamilyMem("Jack", 15);
FamilyMem Tom = new FamilyMem("Tommy", 24);
FamilyMem Felix = new FamilyMem("Felix", 26);
FamilyMem Lukas = new FamilyMem("Lukas", 26);
FamilyMem Austin = new FamilyMem("Austin", 54);
FamilyMem Ben = new FamilyMem("Ben", 55);
List<FamilyMem> gambleList = new List<FamilyMem>();
gambleList.Add(Jack);
gambleList.Add(Tom);
gambleList.Add(Felix);
gambleList.Add(Lukas);
gambleList.Add(Austin);
gambleList.Add(Ben);
Console.WriteLine(gambleList.Count.ToString());
}
}
}
</code></pre>
<p>I also need a separate piece of code that will allow me to sort the names alphabetically. Thanks. </p> | 0 |
Create Cookie ASP.NET & MVC | <p>I have a quite simple problem. I want to create a cookie at a Client, that is created by the server.
I've found a lot of <a href="http://www.codeproject.com/Articles/244904/Cookies-in-ASP-NET" rel="nofollow noreferrer">pages</a> that describe, how to use it - but I always stuck at the same point.</p>
<p>I have a <code>DBController</code> that gets invoked when there is a request to the DB.</p>
<p>The <code>DBController</code>'s constructor is like this:</p>
<pre><code>public class DBController : Controller
{
public DBController()
{
HttpCookie StudentCookies = new HttpCookie("StudentCookies");
StudentCookies.Value = "hallo";
StudentCookies.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(StudentCookies);
Response.Flush();
}
[... more code ...]
}
</code></pre>
<p>I get the Error "<em>Object reference not set to an instance of an object</em>" at:</p>
<pre><code>StudentCookies.Expire = DateTime.Now.AddHours(1);
</code></pre>
<p>This is a kind of a basic error message. So what kind of basic thing I've forgot?</p> | 0 |
Unity how to check for color match | <p>I am using Unity 5 and wanted to check on collision if two game object material have the same matching color and to take action if the colours don't match. I am using the c# code below:</p>
<pre><code>void OnCollisionEnter2D(Collision2D col)
{
if(col.gameObject.GetComponent<Renderer> ().material.color != this.gameObject.GetComponent<Renderer> ().material.color)
{
Destroy(col.gameObject);
}
}
</code></pre>
<p>This doesn't appear to work properly as the sometimes the gameobject gets destroyed even when the color matches. Just wondering if there is another way to check for color matches?</p> | 0 |
How to get the REST response in Groovy? | <p>I have to write a small script within a web app. This web app has it's limitations but is similar to this online console: <a href="https://groovyconsole.appspot.com/" rel="noreferrer">https://groovyconsole.appspot.com/</a> so if it works here, it should work for my problem as well.</p>
<p>I need to parse a JSON response. For simplicity I developed in C# my own web API and when I enter on the browser the link (<a href="http://localhost:3000/Test" rel="noreferrer">http://localhost:3000/Test</a>) it gives this string :</p>
<pre><code>{"Code":1,"Message":"This is just a test"}
</code></pre>
<p>I want to get this string, and parse it afterwards, I guess with JsonSplunker. After hours of research, the most compelling sample would be this:</p>
<pre><code>import groovyx.net.http.RESTClient
def client = new RESTClient( 'http://www.acme.com/' )
def resp = client.get( path : 'products/3322' ) // ACME boomerang
assert resp.status == 200 // HTTP response code; 404 means not found, etc.
println resp.getData()
</code></pre>
<p>(taken from here: <a href="http://rest.elkstein.org/2008/02/using-rest-in-groovy.html" rel="noreferrer">http://rest.elkstein.org/2008/02/using-rest-in-groovy.html</a>)</p>
<p>However it does not recognize <code>import groovyx.net.http.RESTClient</code>. You can try testing it in the groovy web sonsole provided and you will get the error.</p>
<p>I tried <code>import groovyx.net.http.RESTClient.*</code> but still no success.</p> | 0 |
pandas group by ALL functionality? | <p>I'm using the <code>pandas groupby+agg</code> functionality to generate nice reports</p>
<pre><code>aggs_dict = {'a':['mean', 'std'], 'b': 'size'}
df.groupby('year').agg(aggs_dict)
</code></pre>
<p>I would like to use the same <code>aggs_dict</code> on the entire dataframe as a single group, with no division to years, something like:</p>
<pre><code>df.groupall().agg(aggs_dict)
</code></pre>
<p>or:</p>
<pre><code>df.agg(aggs_dict)
</code></pre>
<p>But couldn't find any elegant way to do it.. Note that in my real code <code>aggs_dict</code> is quite complex so it's rather cumbersome to do:</p>
<pre><code>df.a.mean()
df.a.std()
df.b.size()
....
</code></pre>
<p>am I missing something simple and nice?</p> | 0 |
Calculate the size in bytes of a Swift String | <p>I'm trying to calculate the byte size of a <code>String</code> in Swift but I don't know the size of a single character; what is the byte size of a character?</p>
<p>Let's say I have a string:
<code>let str = "hello, world"</code></p>
<p>I want to send that to some web service endpoint, but that endpoint only accepts strings whose size is under 32 bytes. How would I control the byte size of my string?</p> | 0 |
How to confirm email address using express/node? | <p>I'm trying to build verification of email address for users, to verify their email is real. What package should I use to confirm the email address of the user? So far Im using mongoose and express</p>
<p>Code Example</p>
<pre><code>var UserSchema = new mongoose.Schema({
email: { type: String, unique: true, lowercase: true }
password: String
});
var User = mongoose.model('User', UserSchema);
app.post('/signup', function(req, res, next) {
// Create a new User
var user = new User();
user.email = req.body.email;
user.password = req.body.password;
user.save();
});
</code></pre>
<p>In the app.post codes, how do i confirm the email address of the user?</p> | 0 |
Django ORM join without foreign keys and without raw queries | <h1>A</h1>
<pre><code>class AKeywords(models.Model):
id = models.AutoField(primary_key=True, db_column="kw_id")
word = models.CharField(max_length=200)
...
class Meta:
managed = False
db_table = '"A"."Keywords"'
</code></pre>
<h1>B</h1>
<pre><code>class BKeywords(models.Model):
id = models.AutoField(primary_key=True, db_column="kw_id")
word = models.CharField(max_length=200)
...
class Meta:
managed = False
db_table = '"B"."Keywords"'
</code></pre>
<p>I have another model where i would like to perform my join.</p>
<pre><code>class XKeywords(models.Model):
...
k_id = models.IntegerField(blank=True, null=True)
...
class Meta:
managed = False
db_table = '"public"."XKeywords"'
</code></pre>
<p>I have two models that are very similar, one comes from a database schema and another from another database schema.
A third model that will be to join with table A or B has i want.</p>
<p>How can i join model A or B without using foreignkeys and raw queries?</p> | 0 |
Laravel: How can I change the default Auth Password field name? | <p>I am currently working on my first laravel project and I am facing a problem.</p>
<p>If you have experience with laravel you probably know that by calling <code>php artisan make:auth</code> you will get a predefined mechanism that handles login and registration.</p>
<p>This mechanism is set to understand a couple of commonly used words in order to automate the whole procedure.</p>
<p>The problem that occurs in my case is that I am using oracle db and it won't let me have a table column with the name of <code>password</code> because its a system keyword and it throws errors when trying to insert a user.</p>
<p>So far, I have tried to change my <code>password</code> column to <code>passwd</code> and it worked in my registration form as expected. The User row was successfully inserted and my page was redirected to /home.</p>
<p><a href="https://i.stack.imgur.com/LdZQK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LdZQK.png" alt="Register" /></a></p>
<p><a href="https://i.stack.imgur.com/89aTR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/89aTR.png" alt="Success" /></a></p>
<p>But when I try to logout and then relogin, I get this error telling me that my credentials are not correct:</p>
<p><a href="https://i.stack.imgur.com/GEFR8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GEFR8.png" alt="enter image description here" /></a></p>
<p>As for my code, I have changed my <code>RegisterController.php</code> so that it takes username instead of email</p>
<pre><code>protected function validator(array $data)
{
return Validator::make($data, [
'username' => 'required|max:50|unique:ECON_USERS',
'passwd' => 'required|min:6|confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'username' => $data['username'],
'passwd' => bcrypt($data['passwd'])
]);
}
</code></pre>
<p>The User $fillable</p>
<pre><code>protected $fillable = [
'username', 'passwd'
];
</code></pre>
<p>I am guessing that Auth is trying to authenticate with <code>email</code> and not <code>username</code> or that Auth is searching for <code>password</code> and not <code>passwd</code>.</p> | 0 |
Converting GET request parameter to int ... if it is numeric | <p>lets say i'm showing some data to user , i want user to be able to perform some sort of filtering on a numeric field in the database using a <code>GET</code> form so i have something like this </p>
<pre><code>code = request.GET.get('code')
condition = {}
if( code is not None and int(code) > 0 ):
condition['code'] = int(code)
Somemodel.objects.filter(**condition)
</code></pre>
<p>but this works only if i code contains a number otherwise i get this error </p>
<pre><code>invalid literal for int() with base 10: ''
</code></pre>
<p>so what is the pythonic way to handle this problem ? should i use <code>try/except</code> block? i perfer to handle this in the same <code>if</code> statement considering i might add other filters </p> | 0 |
Convert HH:MM:SS AM/PM string to time | <p>I need to parse times in a character format like "1:36:22 PM".</p>
<p>I've tried various permutations of <code>as.POSIXct</code> and <code>strptime</code> but just can't get there. For example, this fails to pick up the importance of PM:</p>
<pre><code>t <- "1:36:22 PM"
as.POSIXct(t, format = "%H:%M:%S")
# [1] "2016-09-08 01:36:22 BST"
</code></pre>
<p>and this fails:</p>
<pre><code>strptime(t, "%H:%M:%S")
# [1] NA
</code></pre>
<p>Curiously, for reasons I can't understand, dropping the seconds from the input <em>may</em> work:</p>
<pre><code>t <- "1:30:00 PM"
strptime(t, "%I:%M %p")
# [1] NA
t <- "1:30 PM"
strptime(t, "%I:%M %p")
# [1] "2016-09-08 13:30:00 BST"
</code></pre>
<p>All I want is for this to work:</p>
<pre><code>t <- "1:30:00 PM"
SOME COMMAND HERE HERE
# [1] "13:30:00"
</code></pre>
<p>Any ideas?</p> | 0 |
Try With Resources Not Supported at This Language Level | <p>I'm using IntelliJ IDEA Ultimate 2016.2.1, have set Project SDK to my 1.8 version, Project Language Level to 8, Module SDK to my 1.8 version, and JDK home path to /Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/Contents/Home.</p>
<p>I have restarted the IDE.</p>
<p>Still, I am getting ugly warnings about try-with-resources not supported at this language level. I have not used less than language level 8 in IntelliJ so this can't be due to something not refreshing. I am using a gradle build configuration - cleaned built and tried to run - says I'm running 1.5 but I can't figure out where 1.5 is mentioned. In build.gradle i'm using:</p>
<pre><code> apply plugin: 'java'
apply plugin: 'application'
sourceCompatibility = 1.8
</code></pre>
<p>Should I file an IntelliJ bug or am I still missing something?</p>
<p>EDIT:</p>
<p>Running gradle in termianl outside of IntelliJ's system runs it fine. So the problem is IntelliJ related. </p> | 0 |
How to add new flaticons to my website? | <p>I have a website template which uses flaticons. It has a folder with files flaticon.css, flaticon.eot, flaticon.ttf, flaticon.svg, flaticon.woff and some others. I can use the icons by simply importing the CSS into a page and doing something like <code><i class="flaticon-world-grid"></code>. </p>
<p>Now I want to download some new flaticons and use them on my site. I found some on flaticon.com and it gives me an option to download it in multiple formats. How to "install" these files and edit my CSS so that I can use the new icons like the ones that are already there? </p>
<p>The css file has content like this:</p>
<pre><code>.flaticon-wand2:before {
content: "\e0fb";
}
.flaticon-wealth:before {
content: "\e0fc";
}
.flaticon-website34:before {
content: "\e0fd";
}
.flaticon-world-grid:before {
content: "\e0fe";
}
</code></pre>
<p>Which format should I download, where to put the new files, and what to add into the css file to be able to use them?</p> | 0 |
Bash time format HH:MM in 12 hour format AM/PM | <p>I am trying to print out the time in AM / PM format with this code:</p>
<pre><code> #!/bin/bash
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
--AMPM| --ampm)
while true;
do
#Time in AMPM format:
echo $(date +"%r")
sleep 1s;
clear;
done
esac
done
</code></pre>
<p>I get this: HH:MM:SS
I want to get this: HH:MM</p>
<p>How can i alter the code to do so ? or why doesnt it work ? </p> | 0 |
how to override an abstract method in a subclass? | <p>I have to create subclasses for an abstract parent class which print out shapes, however whenever I try to create an object it keeps telling me that I cannot instantiate an abstract class, and when I remove the keyword <code>abstract</code> from my code that overrides, it says I can't do that either.</p>
<p>My code:</p>
<pre><code>public class Rectangle extends VectorObject {
protected int ID, x, y, xlnth, ylnth;
protected int matrix[][];
Rectangle(int id, int ax, int ay, int xlen, int ylen) {
super(id, ax, ay);
xlnth = xlen;
ylnth = ylen;
}
public int getId() {
return ID;
}
public void draw() {
String [][] matrix = new String[20][20];
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
if (i == x) {
matrix[i][y] = "*";
}
if (j==y) {
matrix[i][y] = "*";
}
System.out.println(matrix[i][y]);
}
}
}
}
</code></pre>
<p>Abstract parent class:</p>
<pre><code>abstract class VectorObject {
protected int id, x, y;
VectorObject(int anId, int ax, int ay) {
id = anId;
x = ax;
y = ay;
}
int getId() {
return id;
}
void setNewCoords(int newx, int newy) {
x = newx;
y = newy;
}
public abstract void draw (char [][] matrix);
}
</code></pre> | 0 |
Context initialization failed due to org.springframework.core.ResolvableTypeProvider | <p>I upgraded Spring from version 1.5.8 to version 4.2.3.RELEASE. Project compiles fine but when i start tomcat i get following error.</p>
<pre><code>INFO: Initializing Spring root WebApplicationContext
02 Sep 2016 21:07:46,235 INFO ContextLoader:285 - Root WebApplicationContext: initialization started
02 Sep 2016 21:07:46,264 ERROR ContextLoader:336 - Context initialization failed
java.lang.NoClassDefFoundError: org/springframework/core/ResolvableTypeProvider
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:3116)
at org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:1344)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1825)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1705)
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2585)
at java.lang.Class.getConstructor0(Class.java:2885)
at java.lang.Class.getDeclaredConstructor(Class.java:2058)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:104)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:360)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:293)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5077)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5591)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1095)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1957)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.springframework.core.ResolvableTypeProvider
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1856)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1705)
... 28 more
</code></pre>
<p>Below is the pom.xml</p>
<pre><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.nationalpayment.cp20</groupId>
<artifactId>wsrv</artifactId>
<packaging>war</packaging>
<version>versionUpgrade-SNAPSHOT</version>
<name>wsrv Spring-WS Application</name>
<url>http://www.springframework.org/spring-ws</url>
<reporting>
<plugins>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<stylesheetfile>${basedir}/../../src/main/javadoc/javadoc.css</stylesheetfile>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<!-- <version>2.5.1</version> -->
<version>3.0.0</version>
<configuration>
<findbugsXmlOutput>true</findbugsXmlOutput>
<findbugsXmlWithMessages>true</findbugsXmlWithMessages>
<xmlOutput>true</xmlOutput>
<!-- <excludeFilterFile>${project.basedir}/conf/findbugs-exclude.xml</excludeFilterFile> -->
<effort>Max</effort>
</configuration>
</plugin>
</plugins>
</reporting>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
<!--<resource> <directory>src/main/resources</directory> <excludes> <exclude>**/*.properties</exclude>
</excludes> <filtering>false</filtering> </resource> -->
</resources>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<!-- <version>2.5.1</version> -->
<version>3.0.0</version>
</plugin>
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>replacer</artifactId>
<version>1.5.3</version>
<configuration>
<file>pom.xml</file>
<replacements>
<replacement>
<token>${current.build.version}</token>
<value>${replacer.current.build.version}</value>
</replacement>
</replacements>
</configuration>
</plugin>
<plugin>
<groupId>com.google.code.maven-svn-revision-number-plugin</groupId>
<artifactId>maven-svn-revision-number-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<goals>
<goal>revision</goal>
</goals>
</execution>
</executions>
<!-- put your configurations here -->
<configuration>
<entries>
<entry>
<prefix>CPIIWSRV-svn</prefix>
</entry>
</entries>
</configuration>
<dependencies>
<dependency>
<groupId>org.tmatesoft.svnkit</groupId>
<artifactId>svnkit</artifactId>
<version>1.8.0-SNAPSHOT</version>
</dependency>
</dependencies>
</plugin>
<!-- <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>aspectj-maven-plugin</artifactId>
<version>1.2</version> <configuration> <source>1.6</source> <verbose>true</verbose>
<complianceLevel>1.6</complianceLevel> <showWeaveInfo>true</showWeaveInfo>
<aspectLibraries> <aspectLibrary> <groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId> </aspectLibrary> </aspectLibraries>
</configuration> <executions> <execution> <goals> <goal>compile</goal> </goals>
</execution> </executions> <dependencies> <dependency> <groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId> <version>1.6.6</version> </dependency>
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjtools</artifactId>
<version>1.6.6</version> </dependency> </dependencies> </plugin> -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<!-- <version>1.2</version> -->
<version>1.6</version>
<configuration>
<source>1.7</source>
<verbose>true</verbose>
<complianceLevel>1.7</complianceLevel>
<showWeaveInfo>true</showWeaveInfo>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>eviware</groupId>
<artifactId>maven-soapui-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<projectFile>src/test/soap-ui-tests/webservicetestsuite1.xml</projectFile>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<executions>
<execution>
<id>enforce-versions</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireJavaVersion>
<version>1.7</version>
</requireJavaVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<!-- <plugin> <groupId>com.sun.tools.xjc.maven2</groupId> <artifactId>maven-jaxb-plugin</artifactId>
<version>1.1.1</version> <executions> <execution> <phase>generate-sources</phase>
<goals> <goal>generate</goal> </goals> </execution> </executions> <configuration>
<generatePackage>net.nationalpayment.cp20.ws.schema</generatePackage> <schemaDirectory>src/main/webapp/</schemaDirectory>
</configuration> </plugin> -->
<!-- Added for Stack Upgrade starts -->
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.12.3</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<generatePackage>net.nationalpayment.cp20.ws.schema</generatePackage>
<schemaDirectory>src/main/webapp/</schemaDirectory>
<!-- <generateDirectory>${project.build.directory}/generated-sources/kyc</generateDirectory> -->
<generateDirectory>src/main/java/</generateDirectory>
<verbose>true</verbose>
</configuration>
</plugin>
<!-- Added for Stack Upgrade ends -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.3</version>
<configuration>
<descriptors>
<descriptor>src/main/assembly/assembly.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Added for Stack Upgrade starts -->
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
<version>1.2</version>
</dependency>
<!-- Added for Stack Upgrade ends -->
<dependency>
<groupId>net.nationalpayment.cp20</groupId>
<artifactId>services</artifactId>
<version>${current.build.version}</version>
</dependency>
<!-- Spring-WS dependencies -->
<!-- <dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-xml</artifactId>
<version>2.2.0.RELEASE</version>
</dependency> -->
<!-- Added for Stack Upgrade starts -->
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-xml</artifactId>
<version>${spring.ws.version}</version>
</dependency>
<!-- Added for Stack Upgrade ends -->
<!-- <dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<version>2.2.4.RELEASE</version>
</dependency> -->
<!-- Added for Stack Upgrade starts -->
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<version>${spring.ws.version}</version>
</dependency>
<!-- Added for Stack Upgrade ends -->
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core-tiger</artifactId>
<version>1.5.10</version>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-oxm</artifactId>
<version>1.5.10</version>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-oxm-tiger</artifactId>
<version>1.5.10</version>
<scope>runtime</scope>
</dependency>
<!-- <dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-support</artifactId>
<version>2.2.0.RELEASE</version>
<scope>runtime</scope>
</dependency> -->
<!-- Added for Stack Upgrade starts -->
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-support</artifactId>
<version>${spring.ws.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Added for Stack Upgrade ends -->
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-security</artifactId>
<!-- <version>2.2.0.RELEASE</version> -->
<version>${spring.ws.version}</version>
<scope>runtime</scope>
<exclusions>
<exclusion>
<groupId>org.apache.ws.security</groupId>
<artifactId>wss4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Spring dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-api</artifactId>
<version>${cxf.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>${cxf.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>${cxf.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-bundle-jaxrs</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-bundle-jaxrs</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.neethi</groupId>
<artifactId>neethi</artifactId>
<version>3.0.2</version>
<exclusions>
<exclusion>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>woodstox-core-asl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.1.1</version>
<exclusions>
<exclusion>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt</artifactId>
<version>1.9.2</version>
<scope>compile</scope>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<scope>test</scope>
<version>2.2</version>
</dependency>
<dependency>
<groupId>xalan</groupId>
<artifactId>xalan</artifactId>
<version>2.7.2</version>
</dependency>
</dependencies>
<properties>
<!-- Database settings -->
<dbunit.dataTypeFactoryName>org.dbunit.ext.mysql.MySqlDataTypeFactory</dbunit.dataTypeFactoryName>
<hibernate.dialect>org.hibernate.dialect.MySQL5InnoDBDialect</hibernate.dialect>
<jdbc.groupId>mysql</jdbc.groupId>
<jdbc.artifactId>mysql-connector-java</jdbc.artifactId>
<cxf.version>2.6.0</cxf.version>
<jdbc.version>5.1.28</jdbc.version>
<jdbc.driverClassName>com.mysql.jdbc.Driver</jdbc.driverClassName>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<timestamp>${maven.build.timestamp}</timestamp>
<!-- Added for Stack Upgrade starts -->
<aspectj.version>1.7.4</aspectj.version>
<spring.version>4.2.3.RELEASE</spring.version>
<spring.ws.version>2.2.0.RELEASE</spring.ws.version>
<!-- <dao.framework>hibernate</dao.framework> <web.framework>spring</web.framework>
<commons.fileupload.version>1.2.1</commons.fileupload.version> <commons.io.version>1.3.2</commons.io.version>
<hibernate.version>4.0.1.Final</hibernate.version> <spring.version>4.2.3.RELEASE</spring.version> -->
<!-- Added for Stack Upgrade ends -->
<wsrv.timestamp>${timestamp}</wsrv.timestamp>
<maven.build.timestamp.format>yyyy-MM-dd_HH-mm-ss</maven.build.timestamp.format>
<current.build.version>versionUpgrade-SNAPSHOT</current.build.version>
</properties>
</project>
</code></pre>
<p>Below is web.xml</p>
<pre><code><?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>ws</servlet-name>
<servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ws</servlet-name>
<url-pattern>/services</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ws</servlet-name>
<url-pattern>/service</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ws</servlet-name>
<url-pattern>*.wsdl</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/cftRest/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/cftAuth/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--PBE encription configs-->
<servlet>
<servlet-name>webPBEConfigServlet</servlet-name>
<servlet-class>
org.jasypt.web.pbeconfig.WebPBEConfigServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>webPBEConfigServlet</servlet-name>
<url-pattern>/webPBEConfig.do</url-pattern>
</servlet-mapping>
<filter>
<filter-name>webPBEConfigFilter</filter-name>
<filter-class>org.jasypt.web.pbeconfig.WebPBEConfigFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>webPBEConfigFilter</filter-name>
<servlet-name>ws</servlet-name>
</filter-mapping>
<mime-mapping>
<extension>xsd</extension>
<mime-type>text/xml</mime-type>
</mime-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>file:${CONFIG_PATH}/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>1000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
</web-app>
</code></pre>
<p>Any help would be greatly appreciated.I am using Eclipse and Maven3.</p> | 0 |
AWS Lambda function - convert PDF to Image | <p>I am developing application where user can upload some drawings in pdf format. Uploaded files are stored on S3. After uploading, files has to be converted to images. For this purpose I have created lambda function which downloads file from S3 to /tmp folder in lambda execution environment and then I call ‘convert’ command from imagemagick. </p>
<p><code>convert sourceFile.pdf targetFile.png</code></p>
<p>Lambda runtime environment is nodejs 4.3. Memory is set to 128MB, timeout 30 sec.</p>
<p>Now the problem is that some files are converted successfully while others are failing with the following error: </p>
<blockquote>
<p>{ [Error: Command failed: /bin/sh -c convert /tmp/sourceFile.pdf
/tmp/targetFile.png convert: <code>%s' (%d) "gs" -q -dQUIET -dSAFER -dBATCH
-dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pngalpha" -dTextAlphaBits=4 -dGraphicsAlphaBits=4 "-r72x72" "-sOutputFile=/tmp/magick-QRH6nVLV--0000001" "-f/tmp/magick-B610L5uo"
"-f/tmp/magick-tIe1MjeR" @ error/utility.c/SystemCommand/1890.
convert: Postscript delegate failed</code>/tmp/sourceFile.pdf': No such
file or directory @ error/pdf.c/ReadPDFImage/678. convert: no images
defined `/tmp/targetFile.png' @
error/convert.c/ConvertImageCommand/3046. ] killed: false, code: 1,
signal: null, cmd: '/bin/sh -c convert /tmp/sourceFile.pdf
/tmp/targetFile.png' }</p>
</blockquote>
<p>At first I did not understand why this happens, then I tried to convert problematic files on my local Ubuntu machine with the same command. This is the output from terminal: </p>
<p><code>**** Warning: considering '0000000000 XXXXX n' as a free entry.
**** This file had errors that were repaired or ignored.
**** The file was produced by:
**** >>>> Mac OS X 10.10.5 Quartz PDFContext <<<<
**** Please notify the author of the software that produced this
**** file that it does not conform to Adobe's published PDF
**** specification.</code></p>
<p>So the message was very clear, but the file gets converted to png anyway. If I try to do <code>convert source.pdf target.pdf</code> and after that <code>convert target.pdf image.png</code>, file is repaired and converted without any errors. This doesn’t work with lambda. </p>
<p>Since the same thing works on one environment but not on the other, my best guess is that the version of Ghostscript is the problem. Installed version on AMI is 8.70. On my local machine Ghostsript version is 9.18.</p>
<p>My questions are: </p>
<ul>
<li>Is the version of ghostscript problem? Is this a bug with older
version of ghostscript? If not, how can I tell ghostscript (with or
without using imagemagick) to repair or ignore errors like it does on
my local environment?</li>
<li>If the old version is a problem, is it possible to build ghostscript
from source, create nodejs module and then use that version of
ghostscript instead the one that is installed?</li>
<li>Is there an easier way to convert pdf to image without using
imagemagick and ghostscript?</li>
</ul>
<p><strong>UPDATE</strong>
Relevant part of lambda code: </p>
<pre><code>var exec = require('child_process').exec;
var AWS = require('aws-sdk');
var fs = require('fs');
...
var localSourceFile = '/tmp/sourceFile.pdf';
var localTargetFile = '/tmp/targetFile.png';
var writeStream = fs.createWriteStream(localSourceFile);
writeStream.write(body);
writeStream.end();
writeStream.on('error', function (err) {
console.log("Error writing data from s3 to tmp folder.");
context.fail(err);
});
writeStream.on('finish', function () {
var cmd = 'convert ' + localSourceFile + ' ' + localTargetFile;
exec(cmd, function (err, stdout, stderr ) {
if (err) {
console.log("Error executing convert command.");
context.fail(err);
}
if (stderr) {
console.log("Command executed successfully but returned error.");
context.fail(stderr);
}else{
//file converted successfully - do something...
}
});
});
</code></pre> | 0 |
What is the difference between DB::beginTransaction() and DB::transaction()? | <p>I'm using Laravel 5.2.</p>
<p>I would like to know what are the differences between :</p>
<ol>
<li><code>DB::beginTransaction()</code> and <code>DB::transaction()</code></li>
<li><code>DB::commitTransction()</code> and <code>DB::commit()</code></li>
<li><code>DB::rollbackTransction()</code> and <code>DB::rollback()</code></li>
</ol>
<p>Any helps would be appreciated.</p> | 0 |
mongoDB query to find the document in nested array | <pre><code>[{
"username":"user1",
"products":[
{"productID":1,"itemCode":"CODE1"},
{"productID":2,"itemCode":"CODE1"},
{"productID":3,"itemCode":"CODE2"},
]
},
{
"username":"user2",
"products":[
{"productID":1,"itemCode":"CODE1"},
{"productID":2,"itemCode":"CODE2"},
]
}]
</code></pre>
<p>I want to find all the "productID" of "products" for "user1" such that "itemCode" for the product is "CODE1".</p>
<p>What query in mongoDB should be written to do so?</p> | 0 |
How to get bytes out of an UnsafeMutableRawPointer? | <p>How does one access bytes (or Int16's, floats, etc.) out of memory pointed to by an UnsafeMutableRawPointer (new in Swift 3) handed to a Swift function by a C API (Core Audio, etc.)</p> | 0 |
How to run a Laravel Job at specify Queue | <p>I have a Job to perform send SMS to user. I want to run this job on the specify queue-name. For example, this job added to "<strong>SMS</strong>" queue. So I found a way to do this but it's exists some errors.</p>
<p><strong>Create job instance and use onQueue() function to do this</strong>:</p>
<pre><code> $resetPasswordJob = new SendGeneratedPasswordResetCode(app()->make(ICodeNotifier::class), [
'number' => $user->getMobileNumber(),
'operationCode' => $operationCode
]);
$resetPasswordJob->onQueue('SMS');
$this->dispatch($resetPasswordJob);
</code></pre>
<p>My Job class like this:</p>
<pre><code>class SendGeneratedPasswordResetCode implements ShouldQueue
{
use InteractsWithQueue, Queueable;
/**
* The code notifier implementation.
*
* @var ICodeNotifier
*/
protected $codeNotifier;
/**
* Create the event listener.
*
* @param ICodeNotifier $codeNotifier
* @return self
*/
public function __construct(ICodeNotifier $codeNotifier)
{
$this->codeNotifier = $codeNotifier;
}
/**
* Handle the event.
*
* @return void
*/
public function handle()
{
echo "bla blaa bla";
#$this->codeNotifier->notify($event->contact->getMobileNumber(), $event->code);
}
public function failed()
{
var_dump("failll");
}
}
</code></pre>
<p>So I type this command to console:</p>
<pre><code>php artisan queue:listen --queue=SMS --tries=1
</code></pre>
<p>But this error message I get when executes this job:</p>
<blockquote>
<p>[InvalidArgumentException]</p>
<p>No handler registered for command [App\Services\Auth\User\Password\SendGeneratedPasswordResetCode]</p>
</blockquote>
<p><strong>Note</strong>: Other way is add event to EventServiceProvider's <strong>listen</strong> property and fire the event. But it's does not work with specify queue-name.</p> | 0 |
SpringRunner dependency Class couldn't be located | <p>I couldn't find which jar will provide me the dependency of <code>SpringRunner.class</code></p>
<p>I am trying to upgrade my Integration tests to spring-boot 1.4.0</p> | 0 |
React Native responsive image width while width/height ratio of image keeps the same | <p>I want a React Native Image to have a width of 50% of the available screen-width, no modification to width:height ratio of the image. </p>
<p>Any hints how to solve this?</p> | 0 |
Can someone please explain what is protected override void? | <p>I am learning about xamarin in basic stage. All the function calls are done by 'protected override void'. So that anyone please help what is the use of it. How it differs from public void.</p> | 0 |
Setting xlim with dates in R | <p>I need to set the x-axis limit of a plot in R, but my values are dates (%m/%d/%Y format). How would I go about changing this? I am trying to plot trophic position vs. collection date. All of my collection dates are in date format (%m/%d/%Y)</p>
<p>This is the code I have tried:</p>
<pre><code>plot(Trophic_Position~Collection_Date, data=BO,main="Burr Oak", col="red",xlab="Collection date",ylab="Trophic Position", xlim=c("6/09/2014","8/30/2014"), ylim=c(2,5))
</code></pre>
<p>I have just started to learn R, so I know that there must be a code that goes along with the xlim command, but I haven't been able to find out what code applies to my situation. </p> | 0 |
check if a row value is null in spark dataframe | <p>I am using a custom function in pyspark to check a condition for each row in a spark dataframe and add columns if condition is true.</p>
<p>The code is as below:</p>
<pre><code>from pyspark.sql.types import *
from pyspark.sql.functions import *
from pyspark.sql import Row
def customFunction(row):
if (row.prod.isNull()):
prod_1 = "new prod"
return (row + Row(prod_1))
else:
prod_1 = row.prod
return (row + Row(prod_1))
sdf = sdf_temp.map(customFunction)
sdf.show()
</code></pre>
<p>I get the error mention below:</p>
<p><strong>AttributeError: 'unicode' object has no attribute 'isNull'</strong></p>
<p>How can I check for null values for specific columns in the current row in my custom function?</p> | 0 |
Matplotlib plot_surface transparency artefact | <p>I'm trying to plot a surface in 3D from a set of data which specifies the z-values. I get some weird transparency artefact though, where I can see through the surface, even though I set alpha=1.0.</p>
<p>The artefact is present both when plotting and when saved to file (both as png and pdf):
<a href="https://i.stack.imgur.com/2bXbI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2bXbI.png" alt="enter image description here"></a></p>
<p>I have tried changing the line width, and changing the number of strides from 1 to 10 (in the latter case, the surface is not visible though due to too rough resolution).</p>
<p><strong>Q: How can I get rid of this transparency?</strong></p>
<p>Here is my code:</p>
<pre><code>import sys
import numpy as np
import numpy.ma as ma
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
y_label = r'x'
x_label = r'y'
z_label = r'z'
x_scale = 2.0*np.pi
y_scale = 2.0*np.pi
y_numPoints = 250
x_numPoints = 250
def quasiCrystal(x, y):
z = 0
for i in range(0,5):
z += np.sin(x * np.cos(float(i)*np.pi/5.0) +
y * np.sin(float(i)*np.pi/5.0))
return z
x = np.linspace(-x_scale, x_scale, x_numPoints)
y = np.linspace(-y_scale, y_scale, y_numPoints)
X,Y = np.meshgrid(x,y)
Z = quasiCrystal(X, Y)
f = plt.figure()
ax = f.gca(projection='3d')
surf = ax.plot_surface( X, Y, Z,
rstride=5, cstride=5,
cmap='seismic',
alpha=1,
linewidth=0,
antialiased=True,
vmin=np.min(Z),
vmax=np.max(Z)
)
ax.set_zlim3d(np.min(Z), np.max(Z))
f.colorbar(surf, label=z_label)
ax.set_xlabel(x_label)
ax.set_ylabel(y_label)
ax.set_zlabel(z_label)
plt.show()
</code></pre>
<p>Here is another picture of my actual data where it is easier to see the artefact:
<a href="https://i.stack.imgur.com/nXivZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nXivZ.png" alt="enter image description here"></a></p> | 0 |
Excel How to convert datetime into only date - m/d/YYYY format | <p>Date column has date and time in different formats.</p>
<pre><code>05-09-14 21:58
11-08-13 11:56
08/19/2016 11:08:46
11-08-13 11:56
11-08-13 12:16
05/24/2014 08:26:06
08/24/2016 11:00:29
12/20/2014 09:16:19
08/25/2016 09:38:22
08/24/2016 10:59:05
08/25/2016 12:36:33
08/19/2016 10:38:37
11-08-13 14:53
11-08-13 16:18
11-08-13 13:38
10-10-13 16:14
11-08-13 12:44
08/31/2016 17:13:57
</code></pre>
<p>I'm trying to convert these datetime into only date m/d/YYYY format.
I tried =TEXT(cellofdate, "m/d/YYYY") but i'm still getting time for some entries.</p> | 0 |
Color overlay over HTML img | <p>I'm stuck at styling HTML image (<code><img></code>). I can't find a way to add a white overlay over image.
I have been trying this - <a href="https://stackoverflow.com/questions/28710659/css-background-image-on-top-of-img">CSS background image on top of <img></a> (Doesn't work).</p>
<p>HTML</p>
<pre><code><img class="default-user" src="https://minotar.net/helm/Steve/16.png">
</code></pre>
<p>CSS</p>
<pre><code>.default-user {
position: absolute;
outline: #e8e8e8 solid 1px;
-webkit-filter: grayscale(50%);
filter: grayscale(50%);
}
</code></pre>
<p>Is there any way to add overlay? Thank you for your help!</p> | 0 |
__file__ does not exist in Jupyter Notebook | <p>I'm on a <a href="https://en.wikipedia.org/wiki/IPython#Project_Jupyter" rel="noreferrer">Jupyter Notebook</a> server (v4.2.2) with Python 3.4.2 and
I want to use the global name <code>__file__</code>, because the notebook will be cloned from other users and in one section I have to run:</p>
<pre><code>def __init__(self, trainingSamplesFolder='samples', maskFolder='masks'):
self.trainingSamplesFolder = self.__getAbsPath(trainingSamplesFolder)
self.maskFolder = self.__getAbsPath(maskFolder)
def __getAbsPath(self, path):
if os.path.isabs(path):
return path
else:
return os.path.join(os.path.dirname(__file__), path)
</code></pre>
<p>The <code>__getAbsPath(self, path)</code> checks if a <code>path</code> param is a relative or absolute path and returns the absolute version of <code>path</code>. So I can use the returned <code>path</code> safely later.</p>
<p>But I get the error</p>
<blockquote>
<p>NameError: name <code>'__file__'</code> is not defined</p>
</blockquote>
<p>I searched for this error online and found the "solution" that I should better use <code>sys.argv[0]</code>, but <code>print(sys.argv[0])</code> returns</p>
<blockquote>
<p><code>/usr/local/lib/python3.4/dist-packages/ipykernel/__main__.py</code></p>
</blockquote>
<p>But the correct notebook location should be <code>/home/ubuntu/notebooks/</code>.</p>
<p>Thanks for the reference <em><a href="https://stackoverflow.com/questions/12544056/how-to-i-get-the-current-ipython-notebook-name">How do I get the current IPython Notebook name</a></em> from Martijn Pieters (comments) the last answer (not accepted) fits perfect for my needs:</p>
<p><code>print(os.getcwd())</code></p>
<blockquote>
<p>/home/ubuntu/notebooks</p>
</blockquote> | 0 |
Using aria attributes on elements in react | <p>I have the following render method:</p>
<pre><code>render: function () {
return (
React.createElement('div', {className: 'modal', id: 'errorModal', tabIndex: '-1', role: 'dialog', ariaHidden: 'true', dataBackdrop: 'false', style: {marginTop: '30px'}}, 'text')
)
}
</code></pre>
<p>That gives me error:</p>
<blockquote>
<p>react.js:20541 Warning: Unknown props <code>ariaHidden</code>, <code>dataBackdrop</code> on
tag. Remove these props from the element. For details, see
in div (created by Constructor)
in Constructor</p>
</blockquote>
<p>How could I solve this? Documentation says that I can use these attributes. Lowercase does not work either. I don't want to use jsx.</p> | 0 |
Node express request call inside get | <p>I'm trying to use nodejs as a layer between my public website and a server on the inside of our network. </p>
<p>I'm using express.js to create a simple REST api. The API endpoint should trigger a request call to a webservice, and return the result. </p>
<p>But the request call inside my <code>.get()</code> function doesn't do anything.</p>
<p>I want to return the result from the nested call to be returned.</p>
<p>Code:</p>
<pre><code>// Dependencies
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
//Port
var port = process.env.PORT || 8080;
// Express
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Routes
app.get('/invoice', function(req, res){
res.send('Express is workiung on IISNode')
});
app.get('/invoice/api/costumer=:customerId&invoice=:invoiceId', function(req, res){
res.send('Customer ID: ' + req.params.customerId + ' Invoice ID: '+ req.params.invoiceId)
var url = 'http://xxx/invapp/getinvoice?company='+req.params.customerId+'S&customerno=13968&invoiceno='+req.params.invoiceId+'';
request('http://www.google.com', function (error, response, body) {
res.send(body);
})
});
// Start server
app.listen(port);
console.log("API is running on port " + port);
</code></pre>
<p>Any suggestions?</p> | 0 |
UnicodeDecodeError on python3 | <p>Im currently trying to use some simple regex on a very big .txt file (couple of million lines of text). The most simple code that causes the problem:</p>
<pre><code>file = open("exampleFileName", "r")
for line in file:
pass
</code></pre>
<p>The error message:</p>
<pre><code>Traceback (most recent call last):
File "example.py", line 34, in <module>
example()
File "example.py", line 16, in example
for line in file:
File "/usr/lib/python3.4/codecs.py", line 319, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 7332: invalid continuation byte
</code></pre>
<p>How can i fix this? is utf-8 the wrong encoding? And if it is, how do i know which one is right?</p>
<p>Thanks and best regards!</p> | 0 |
How to import org.apache in android studio? | <p>I downloaded <code>components-client-android-4.3.5.1.zip</code> file. But no jar file can import. How to import all java file in android Studio. please tell me detailed steps. Thank your help. p.s I am a beginner so I am not good at programming. Thank your help.</p> | 0 |
Python: How to group a list of objects by their characteristics or attributes? | <p>I want to separate a list of objects into sublists, where objects with same attribute/characteristic stay in the same sublist.</p>
<p>Suppose we have a list of strings:</p>
<pre><code>["This", "is", "a", "sentence", "of", "seven", "words"]
</code></pre>
<p>We want to separate the strings based on their length as follows:</p>
<pre><code>[['sentence'], ['a'], ['is', 'of'], ['This'], ['seven', 'words']]
</code></pre>
<p>The program I currently come up with is this</p>
<pre><code>sentence = ["This", "is", "a", "sentence", "of", "seven", "words"]
word_len_dict = {}
for word in sentence:
if len(word) not in word_len_dict.keys():
word_len_dict[len(word)] = [word]
else:
word_len_dict[len(word)].append(word)
print word_len_dict.values()
</code></pre>
<p>I want to know if there is a better way to achieve this?</p> | 0 |
Select all checkboxes in RecyclerView | <p>How can I select all checkboxes in <code>recyclerView?</code></p>
<p>I try to do it like this:</p>
<p><strong>in Adapter:</strong></p>
<pre><code> public void selectAll(){
Log.e("onClickSelectAll","yes");
isSelectedAll=true;
notifyDataSetChanged();
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
PersonDTO item = dataSet.get(position);
holder.tvName.setText(item.getName());
if (!isSelectedAll) holder.cbSelect.setSelected(false);
else holder.cbSelect.setSelected(true);}
</code></pre>
<p>In <code>layout</code> <code>Activity</code> I have a <code>button</code> with <code>onClickListener</code>:</p>
<pre><code> private void onClickSelectAll(View view) {
getSelectPersonsAdapter().selectAll();
}
</code></pre> | 0 |
What is the difference between URL parameters and query strings? | <p>I don't see much of a difference between the parameters and the query strings, in the URL. So what is the difference and when should one be used over the other?</p> | 0 |
Comparing time with MomentJS | <p>I'm trying to compare a time with momentJS. Here is My script</p>
<pre><code>$( document ).ready(function() {
var today =moment();
console.log(today.format("hh:mm"));
if((today.format('D') == (moment().day("Sunday").format('D')) || (today.format('D') == moment().day('Saturday').format('D'))))
{
$('.kompensasi').val("100,000");
$('.chk').hide();
}
else{
if((today.format("hh:mm") > moment('00:00', 'hh:mm')) && (today.format("hh:mm") < moment('03:00', 'hh:mm')))
{
$('.kompensasi').val("30,000");
$('.cekbok').val('');
}else{
$('.cekbok').val('Dapet RO 1');
$('.kompensasi').val("0");
}
}
});
</code></pre>
<p>and here is my form </p>
<pre><code><div class="col-sm-7">
Kompensasi : <input name="dapet" type="text" readonly class="kompensasi" />
</div>
</div>
<div class="form-group chk">
<label class="col-sm-3 control-label">Ro</label>
<div class="col-sm-7">
<input type="text" class='cekbok' name='rostatus' />
</div>
</div>
</code></pre>
<p>from <code>console.log(today.format("hh:mm"))</code> i get this resullt <code>01:44</code>. </p>
<p>With my script above i always go to the <code>else</code>, so is there any way to fix it ?</p>
<p>Here is my fiddle <a href="https://jsfiddle.net/s9wfh9ye/33/" rel="noreferrer">https://jsfiddle.net/s9wfh9ye/33/</a></p>
<p>My Upated Question </p>
<pre><code> var today =moment();
var after = moment(today.format("hh:mm")).isAfter(moment('00:00', "hh:mm"));
var before = moment(today.format("hh:mm")).isBefore(moment('03:00', "hh:mm"));
today.format('hh:mm').valueOf() -->02:17
moment('00:00', 'hh:mm').valueOf() --> 1472058000000
moment('03:00', 'hh:mm').valueOf() -->1472068800000
console.log(after); // false
console.log(before); // false
</code></pre> | 0 |
Can we have a multi-page JPEG image? | <p>Can we have a multi-page JPEG image?</p>
<p>I have a TIFF image file with multiple pages, but it's too big and first thing comes to mind is to change it to JPEG format, however in JPEG I can see only first page. Therefore I realized only TIFF format allows multiple images in one file. Is that true?</p>
<p>Now I tried to apply different <code>EncoderParameters</code> to reduce the size of TIFF file but no luck. Has someone worked on this issue before? How did you manage to reduce the size of TIFF image?</p>
<p><code>Encoder.Quality</code> does not seem to work with TIFF at all.
<code>EncoderValue.CompressionLZW</code> is the best option to reduce the size, but I still want to reduce the size more.</p>
<p>Changing dpi to 50 reduced the size, but that made image too blurry.</p>
<p>Thanks for any help.</p> | 0 |
Kotlin: How can I create a "static" inheritable function? | <p>For example, I want to have a function <code>example()</code> on a type <code>Child</code> that extends <code>Parent</code> so that I can use the function on both.</p>
<pre><code>Child.example()
Parent.example()
</code></pre>
<p>The first "obvious" way to do this is through the companion object of <code>Parent</code>, but this doesn't allow <code>example()</code> for <code>Child</code>.</p>
<p>The second way I tried was defining an extension function on <code>Parent.Companion</code>, which is inconvenient because you are forced to define a companion object. It also doesn't allow <code>example()</code> for <code>Child</code>.</p>
<p>Does anybody know how I can do this?</p> | 0 |
Cast a very long string as an integer or Long Integer in PySpark | <p>I'm working with a string column which is 38 characters long and is actually numerical.</p>
<p>for e.g. id = '678868938393937838947477478778877.....' ( 38 characters long). </p>
<p>How do I cast it into a long integer ? I have tried cast function with IntegerType, LongType and DoubleType and when i try to show the column it yields Nulls. </p>
<p>The reason I want to do this is because I need to do some inner joins using this column and doing it as String is giving me Java Heap Space Errors.</p>
<p>Any suggestions on how to cast it as a Long Integer ? { This question tries to cast a string into a Long Integer }</p> | 0 |
Safari not rendering SVGs to the desired size/height (SVGS are clipped) | <p>I have some responsive inline SVGs I made. Their sizes render as I want them to in Chrome, Firefox and Edge, but in Safari they escape their containers/are cut off. For some reason their containers doesn't stretch to accommodate them. The following screenshot demonstrates the unwanted, cut-off Safari rendering: </p>
<p><a href="https://i.stack.imgur.com/uKnNX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uKnNX.png" alt="SVGS don't fit"></a></p>
<p>There are known issues with SVG rendering in Safari, and I have tried all the fixes out there I have found to the best of my ability (<a href="https://benfrain.com/attempting-to-fix-responsive-svgs-in-desktop-safari/" rel="nofollow noreferrer">here</a>, <a href="https://stackoverflow.com/questions/17158717/svg-container-renders-wrong-size-in-safari-desktop-fine-in-chrome-ios">here</a>, <a href="https://stackoverflow.com/questions/26091989/svg-viewbox-height-issue-on-ios-safari">here</a>, and <a href="https://stackoverflow.com/questions/7570917/svg-height-incorrectly-calculated-in-webkit-browsers">here</a>), but I can't manage to make the containers fit the SVGs in Safari. It is in part because things are a little complicated with my javascript and I'm still a beginner, forgive me if my codepen is a bit messy. </p>
<p>This is my codepen. :<a href="http://codepen.io/ihatecoding/pen/Bzgqqa" rel="nofollow noreferrer">http://codepen.io/ihatecoding/pen/Bzgqqa</a></p>
<p>What my jquery does: it makes SVGs as large as possible until they take up 1/3 of the screen height, at that point it won't let them get taller.</p>
<p>To help you focus on what matters :</p>
<ul>
<li>The SVGs are all of class <code>.areaSVG</code> </li>
<li>The SVG parents/containers are always <code>.ey-col-svg</code> </li>
<li>The entire footer is <code>#indexFooter</code> </li>
<li>The main background image that is supposed to resize according to the height of the landing footer is <code>#section0img</code></li>
</ul>
<p>The current version that is working the best has the following format for the svg container:</p>
<pre><code>.ey-col-svg {
display: block;
max-height: calc(30vh - 1vw - 63px);
text-align: center;
box-sizing: content-box;
padding: 0;
margin: -2vh 0 0 0;
}
</code></pre>
<p>This is the css for the SVGs before the javascript makes them visible and adjusts their <code>height</code>:</p>
<pre><code>.areaSVG {
overflow: visible;
display: none;
box-sizing: content-box;
margin: 0;
padding: 1.6vh 0 1vh 0;
}
</code></pre>
<p>Again, to repeat The javascript I have currently implemented adjusts the <code>height</code> of the SVGs (whose class is <code>areaSVG</code>).</p>
<p>This is the most relevant part of my jQuery script; it controls the size of the the SVGs. As I mentioned above, this script makes the SVGs as large as possible until they take up 1/3 of the screen height, and at that point it won't let them get taller:</p>
<pre><code> function resizeSVG() {
// the row
var $linksRow = $('.ey-nav-bar');
// the text
var $areaText = $('.ey-text-content');
//the entire row below "research Area"
// the actual svg container
var $area = $('.areaSVG');
var scale = 0.6;
//the wrapper containing the svg div, its height and its width
var $eyCol = $(".ey-col-svg");
var eyWidth = $eyCol.width();
var eyHeight = $eyCol.height();
//the window
var winHeight = $(window).height();
var winWidth = $(window).width();
//max Height caclulated based on window
var maxHeight = .33 * winHeight;
// if the height of the column is less than the width, and below the max height
if (eyHeight < eyWidth && eyHeight < maxHeight)
//make the height of the svg the max heihgt
$area.height(maxHeight);
// use the scaling factor times the width of the svg wrapper
var imageWidth = scale * $eyCol.width();
// get the hight of the column
var imageHeight = $eyCol.height();
// will be the dimensions used to size lenth and width of the svg
var tot;
//apsect ratio of the screen (horizontal/vertical)
var ratio = winWidth / winHeight;
// if the screen is landscape or if the user has left the landing section
tot = imageWidth > imageHeight ? imageHeight: imageWidth;
maxTextHeight = maxHeight * .07;
maxTotHeight = maxHeight * .5;
if (tot < maxTotHeight)
{ $area.css("height", tot);
}
else
{
$area.css("height", maxTotHeight);
$areaText.css("height", maxTextHeight);
}
minLinksHeight = maxHeight * .8;
var linksHeight = $linksRow.height();
}
</code></pre>
<p><em>(Note: the resulting SVG heights are subsequently used by another function, not seen here, to control the size of the main image).</em> </p>
<p>This is my introductory formatting code for each inline svg:</p>
<pre><code> <svg class="areaSVG notFixed index" viewBox="20 0 37 75" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
</code></pre>
<p>Any help would be very appreciated, I really would like to see this to render properly in Safari!</p> | 0 |
How can I handle the base case of this recursive function? My base case is causing an output of zero | <pre><code>''' Returns number of pennies if pennies are doubled num_days times'''
def double_pennies(num_pennies, num_days):
total_pennies = 0
if num_days == 0:
return total_pennies
else:
total_pennies = double_pennies((num_pennies * 2), (num_days - 1));
return total_pennies
''' Program computes pennies if you have 1 penny today,'''
''' 2 pennies after one day, 4 after two days, and so on'''
starting_pennies = 1
user_days = 10
print('Number of pennies after', user_days, 'days: ', end="")
print(double_pennies(starting_pennies, user_days))
</code></pre> | 0 |
preg_match() expects parameter 2 to be string, array given Error | <p>I'm trying to insert array but I'm getting error:- </p>
<blockquote>
<p>preg_match() expects parameter 2 to be string, array given</p>
</blockquote>
<p>My form below like :</p>
<pre><code>{!! Form::text('description[]',null,['class' => 'input-field input-sm','v-model'=>'row.description']) !!}
{!! Form::text('log_time[]',null,['class' => 'input-field input-sm','v-model'=>'row.log_time']) !!}
</code></pre>
<p>My controller store function :</p>
<pre><code>$this->validate($request, $this->rules);
$data = array();
foreach($request->description as $key=>$value){
$data[]=[
'description'=> $value,
'log_time'=> $request->log_time[$key],
'call_id'=>$call->id,
];
}
PortLog::create($data);
</code></pre>
<p>when i check <strong>dd($data)</strong></p>
<pre><code>array:2 [▼
0 => array:3 [▼
"description" => "des"
"log_time" => ""
"call_id" => 16
]
1 => array:3 [▼
"description" => ""
"log_time" => "hi"
"call_id" => 16
]
]
</code></pre>
<p>here what im doing wrong ?</p> | 0 |
PrimeNG datatable checkbox selection with pagination | <p>I'm trying to bring a data table layout with pagination that has checkbox selection for data in it. I'm able to select a page's data and when I move to another page, and select different set of data, the first page selection is lost. </p>
<p>demo.html:
</p>
<pre><code> <p-dataTable [value]="cars" [rows]="10" [paginator]="true" [pageLinks]="3" [rowsPerPageOptions]="[5,10,20]" sortMode="multiple" [(selection)]="selectedCars2">
<p-column [style]="{'width':'38px'}" selectionMode="multiple" ></p-column>
<p-column field="vin" header="Vin"></p-column>
<p-column field="year" header="Year"></p-column>
<p-column field="brand" header="Brand"></p-column>
<p-column field="color" header="Color">
<template let-col let-car="rowData" pTemplate type="body">
<span [style.color]="car[col.field]">{{car[col.field]}}</span>
</template>
</p-column>
<!--<p-column styleClass="col-button">
<template pTemplate type="header">
<input type="checkbox" [(ngModel)]="checkUncheckAll" />
</template>
<template let-car="rowData" pTemplate type="body">
<input type="checkbox" [(ngModel)]="checkValue[car.vin]" (click)="selectCar(car, checkValue[car.vin])"/>
</template>
</p-column>-->
</p-dataTable>
<div class="table-controls-top"><div class="pager"><input type="button" class="button_tablecontrol" (click)="selectCar(selectedCars2)" value="Delete"></div></div>
</code></pre>
<p>demo.ts:</p>
<pre><code>import {Component,OnInit} from '@angular/core';
import {Car} from '../domain/car';
import {CarService} from '../service/carservice';
import {Message} from '../common/api';
@Component({
templateUrl: 'app/showcase/demo/datatable/datatabledemo.html'
})
export class DataTableDemo implements OnInit {
cars: Car[];
cols: any[];
msgs: Message[] = [];
checkValue: any;
selectedCars2: any[];
constructor(private carService: CarService) {
this.checkValue = {};
this.selectedCars2 = [];
}
ngOnInit() {
this.carService.getCarsCustom().then(
cars => {
this.cars = cars;
for (var car of this.cars) {
console.log(car.vin)
this.checkValue[car.vin] = false;
}
});
this.cols = [
{field: 'vin', header: 'Vin'},
{field: 'year', header: 'Year'},
{field: 'brand', header: 'Brand'},
{field: 'color', header: 'Color'}
];
}
selectCar(selectedCars) {
console.log(selectedCars)
console.log(this.selectedCars2)
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/TUkdV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TUkdV.png" alt="Screenshot of datatable"></a></p>
<p>I suppose the team hasn't implemented the functionality yet. Any idea/insights on how to retain the selection of rows (in model 'selectedCars2') with pagination?</p>
<p>Thanks in advance.</p> | 0 |
Laravel API return image from public folder with database data | <p>I want to return image with data.</p>
<pre><code>$ads = DB::table('ads')->whereRaw('category_id=' .$id)->orderBy('id', 'desc')->get();
$filename = public_path().'/uploads/images/'.$ads->ad_image;
$filename = (file_get_contents($filename));
$image = Array('image'=>json_encode(base64_encode($filename)));
$ads[0]->image = $image;
return $ads;
</code></pre> | 0 |
How to load Impala table directly to Spark using JDBC? | <p>I am trying to write a spark job with Python that would open a jdbc connection with Impala and load a VIEW directly from Impala into a Dataframe. This question is pretty close but in scala: <a href="https://stackoverflow.com/questions/26634853/calling-jdbc-to-impala-hive-from-within-a-spark-job-and-creating-a-table">Calling JDBC to impala/hive from within a spark job and creating a table</a></p>
<p>How do I do this? There are plenty of examples for other datasources such as MySQL, PostgreSQL, etc. but I haven't seen one for Impala + Python + Kerberos. An example would be of great help. Thank you!</p>
<p>Tried this with information from the web but it didn't work.</p>
<h3>SPARK Notebook</h3>
<pre><code>#!/bin/bash
export PYSPARK_PYTHON=/home/anave/anaconda2/bin/python
export HADOOP_CONF_DIR=/etc/hive/conf
export PYSPARK_DRIVER_PYTHON=/home/anave/anaconda2/bin/ipython
export PYSPARK_DRIVER_PYTHON_OPTS='notebook --ip=* --no-browser'
# use Java8
export JAVA_HOME=/usr/java/latest
export PATH=$JAVA_HOME/bin:$PATH
# JDBC Drivers for Impala
export CLASSPATH=/home/anave/impala_jdbc_2.5.30.1049/Cloudera_ImpalaJDBC41_2.5.30/*.jar:$CLASSPATH
export JDBC_PATH=/home/anave/impala_jdbc_2.5.30.1049/Cloudera_ImpalaJDBC41_2.5.30
# --jars $SRCDIR/spark-csv-assembly-1.4.0-SNAPSHOT.jar \
# --conf spark.sql.parquet.binaryAsString=true \
# --conf spark.sql.hive.convertMetastoreParquet=false
pyspark --master yarn-client \
--driver-memory 4G \
--executor-memory 2G \
# --num-executors 10 \
--jars /home/anave/spark-csv_2.11-1.4.0.jar $JDBC_PATH/*.jar
--driver-class-path $JDBC_PATH/*.jar
</code></pre>
<h3>Python Code</h3>
<pre><code>properties = {
"driver": "com.cloudera.impala.jdbc41.Driver",
"AuthMech": "1",
# "KrbRealm": "EXAMPLE.COM",
# "KrbHostFQDN": "impala.example.com",
"KrbServiceName": "impala"
}
# imp_env is the hostname of the db, works with other impala queries ran inside python
url = "jdbc:impala:imp_env;auth=noSasl"
db_df = sqlContext.read.jdbc(url=url, table='summary', properties=properties)
</code></pre>
<p>I received this error msg (<a href="http://pastebin.com/y7496a5i" rel="nofollow noreferrer" title="Full Error Log">Full Error Log</a>):<br>
Py4JJavaError: An error occurred while calling o42.jdbc.
: java.lang.ClassNotFoundException: com.cloudera.impala.jdbc41.Driver</p> | 0 |
How to use Metric value in Alias? | <p>I created a new Graph in Grafana that takes data from OpenTSDB.</p>
<p><a href="https://i.stack.imgur.com/nr2hA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nr2hA.png" alt="Add Panel Graph"></a></p>
<p>The <strong>Alias</strong> field has the following value: <code>Label $metric $tag_host</code>.</p>
<ul>
<li><p>when it is interpreted, it looks like this:</p>
<ul>
<li><code>Label $metric myhost1</code></li>
<li>...</li>
<li><code>Label $metric myhostn</code></li>
</ul></li>
<li><p>but I want to look like this:</p>
<ul>
<li><code>Label xyz myhost1</code></li>
<li>...</li>
<li><code>Label xyz myhostn</code>
where <code>xyz</code> is the value of the <strong>Metric</strong> field.</li>
</ul></li>
</ul>
<p>So, for a key (E.g.: <code>host</code>) in <strong>Tags</strong>, I can use <code>$tag_<key></code> (E.g.: <code>$tag_host</code>) in <strong>Alias</strong>.</p>
<p>I want to achieve the same behavior for the hard-coded <strong>Metric</strong> value (E.g.: <code>xyz</code>), such that if someone wants to change the Metric value in the future from <code>xyz</code> to <code>abc</code>, the Alias should be updated automatically.</p>
<p>I tried to use:</p>
<ul>
<li><code>$metric</code></li>
<li><code>$Metric</code></li>
<li><code>$tag_metric</code></li>
</ul>
<p>but they didn't work.</p>
<p><a href="https://i.stack.imgur.com/1eXOD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1eXOD.png" alt="Grafana Metrics"></a></p>
<p>Is it possible to use the <strong>Metric</strong> value in <strong>Alias</strong> without hard-coding in Alias (the hard-coding from Metric is enough)?</p> | 0 |
SQLite query to delete from multiple tables | <p>I use a query to retrieve a list of tables with a specific column name:</p>
<pre><code>select name from sqlite_master where type='table' and sql like '%unique_col_id%';
</code></pre>
<p>So, it return a list of table names for example, table_1, table_2, table_3..</p>
<p>I would like to delete all rows in the above tables with unique_col_id equal to specific value:</p>
<pre><code>DELETE FROM table_1 where unique_col_id=3;
DELETE FROM table_2 where unique_col_id=3;
DELETE FROM table_3 where unique_col_id=3;
</code></pre>
<p>Is there a way to delete all table in one query? I mean to integrate both queries (search the table and delete all of them with unique_col_id=3...)</p>
<p>Thanks</p> | 0 |
Insert Multiple Records At Once With Laravel | <p>I am inserting the data to the rows one by one, but I have heard somewhere that it requires much time if there are many data to insert. So what are the ways of inserting them all at once?</p>
<pre><code>public function add(Request $request)
{
if ($request->ajax()) {
$books = $request->books;
foreach ($books as $book) {
if (!empty($book)) {
$add = new Book;
$add->name = $book;
$add->user_id = Auth::user()->id;
$add->save();
}
}
}
}
</code></pre> | 0 |
How to git clone from *local bare* repository | <p>Say I have a bare repository on my local machine at <code>./new-bare.git</code>.
What is the correct way to clone it to another location on my machine?</p> | 0 |
Oracle - How to *correctly* convert from EST/EDT to GMT? | <p>I have a query that is doing some time zone conversions. As an example, I want to convert from an <code>EST</code> time to <code>GMT</code>:</p>
<p>For the EDT time of <code>3/13/2016 @2:00 AM</code> (immediately following the EST->EDT changeover) I should get a GMT time of <code>3/13/2016 7:00:00 AM</code> (<a href="http://www.worldtimebuddy.com/est-to-gmt-converter" rel="nofollow">verified here</a> for the date of 3/13/2016 @2am). Instead I am getting <code>3/13/2016 6:00:00 AM</code> from using this query:</p>
<pre><code>SELECT NEW_TIME(TO_DATE('2016/3/13 02:00:00 AM',
'YYYY/MM/DD HH:MI:SS AM'),'EDT','GMT')
FROM DUAL;
</code></pre>
<p>For the EST time of <code>3/13/2016 @1:00AM</code> (one second before the changeover) I am getting what appears to be the correct result:</p>
<pre><code>SELECT NEW_TIME(TO_DATE('2016/3/13 01:59:59 AM',
'YYYY/MM/DD HH:MI:SS AM'),'EST','GMT')
FROM DUAL;
</code></pre>
<p>Result:</p>
<pre><code>3/13/2016 6:59:59 AM
</code></pre>
<p>What am I doing wrong here? I have read the Oracle documentation on NEW_TIME and have tried switching the EDT/EST with the GMT (based on the one example they have at the bottom of the page) but that gives me even more odd results.</p> | 0 |
How can I draw a half arrow with asterisks in java? | <p>I am in my first java class, and I am trying to draw a half arrow using asterisks. I am supposed to use a nested loop where the inner loop draws the *s and the outer loop iterates the number of times equal to the height of the arrow base. I have learned if-else, while loops, and for loops. </p>
<p>So far, I have been able to correctly draw the arrow for input values of<br>
arrow base height: 5<br>
arrow base width: 2<br>
arrow head width: 4 </p>
<p>When I try to add a while loop as the outer loop, the program times out. I am at a loss. </p>
<p>The next input I need to use is 2, 3, 4. My code gets the height of the base right (2), but not the width. </p>
<p>The last input I need is 3, 3, 7. My code gets none of that right at all. This is what I have so far.</p>
<p>What kind of loops should I be using to get the widths correct?</p>
<pre><code> Scanner scnr = new Scanner(System.in);
int arrowBaseHeight = 0;
int arrowBaseWidth = 0;
int arrowHeadWidth = 0;
int i = 0;
System.out.println("Enter arrow base height: ");
arrowBaseHeight = scnr.nextInt();
System.out.println("Enter arrow base width: ");
arrowBaseWidth = scnr.nextInt();
System.out.println("Enter arrow head width: ");
arrowHeadWidth = scnr.nextInt();
for (i = 1; i <= arrowBaseHeight; ++i) {
// Draw arrow base (height = 3, width = 2)
System.out.println("**");
}
// Draw arrow head (width = 4)
System.out.println("****");
System.out.println("***");
System.out.println("**");
System.out.println("*");
</code></pre>
<p>Example of how the output arrow may look:</p>
<pre><code>**
**
**
**
****
***
**
*
</code></pre> | 0 |
DataTables: Cannot read property style of undefined | <p>I am getting this error with the following:</p>
<pre><code>jquery.dataTables.js:4089 Uncaught TypeError: Cannot read property 'style' of undefined(…)
_fnCalculateColumnWidths @ jquery.dataTables.js:4089
_fnInitialise @ jquery.dataTables.js:3216
(anonymous function) @ jquery.dataTables.js:6457
each @ jquery-2.0.2.min.js:4
each @ jquery-2.0.2.min.js:4
DataTable @ jquery.dataTables.js:5993
$.fn.DataTable @ jquery.dataTables.js:14595
(anonymous function) @ VM3329:1
(anonymous function) @ VM3156:180
l @ jquery-2.0.2.min.js:4
fireWith @ jquery-2.0.2.min.js:4
k @ jquery-2.0.2.min.js:6
(anonymous function) @ jquery-2.0.2.min.js:6
</code></pre>
<p>The line above referring to (anonymous function) @ VM3156:180 is:</p>
<pre><code> TASKLISTGRID = $("#TASK_LIST_GRID").DataTable({
data : response,
columns : columns.AdoptionTaskInfo.columns,
paging: true
});
</code></pre>
<p>So I am guessing this is where it is failing.</p>
<p>The HTML ID element exist:</p>
<pre><code> <table id="TASK_LIST_GRID" class="table table-striped table-bordered table-hover dataTable no-footer" width="100%" role="grid" aria-describedby="TASK_LIST_GRID_info">
<thead>
<tr role="row">
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Solution</th>
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Status</th>
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Category</th>
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Type</th>
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Due Date</th>
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Create Date</th>
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Owner</th>
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Comments</th>
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Mnemonic</th>
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Domain</th>
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Approve</th>
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Dismiss</th>
</tr>
</thead>
<tbody></tbody>
</table>
</code></pre>
<p>Also, the columns.AdoptionTaskInfo.columns & response object arrays exist. Not sure how to debug what's wrong.. Any suggestions will be helpful..</p> | 0 |
Attempt to call an undefined function glutInit | <p>I need a glut window in python.
I have the following exception using Python 3.5 and PyOpenGL.GLUT</p>
<pre><code>Traceback (most recent call last):
File "D:\...\Test.py", line 47, in <module>
if __name__ == '__main__': main()
File "D:\...\Test.py", line 9, in main
glutInit(sys.argv)
File "C:\...\OpenGL\GLUT\special.py", line 333, in glutInit
_base_glutInit( ctypes.byref(count), holder )
File "C:\...\OpenGL\platform\baseplatform.py", line 407, in __call__
self.__name__, self.__name__,
OpenGL.error.NullFunctionError: Attempt to call an undefined function glutInit,
check for bool(glutInit) before calling
</code></pre>
<p>Platform: <strong>Windows</strong></p>
<p>Why do i get this error?</p>
<p>Here is my code:</p>
<pre><code>from OpenGL.GLUT import *
import sys
glutInit(sys.argv)
</code></pre> | 0 |
how to count consecutive duplicates in a python list | <p>I have a list as follows, consisting of only (-1)s and 1s:</p>
<pre><code>list1=[-1,-1,1,1,1,-1,1]
</code></pre>
<p>I'm trying to append the number of consecutive duplicates into a list, e.g.:</p>
<pre><code>count_dups=[2,3,1,1]
</code></pre>
<p>I've tried creating a new list and using the zip function as the first step, but
can't seem to go on because of the cut-off end-value</p>
<pre><code>list2=list1[1:]
empty=[]
for x,y in zip(list1,list2):
if x==y:
empty.append(x)
else:
empty.append(0)
</code></pre> | 0 |
How could I ping my docker container from my host | <p>I have created a ubuntu docker container on my mac</p>
<pre><code>CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5d993a622d23 ubuntu "/bin/bash" 42 minutes ago Up 42 minutes 0.0.0.0:123->123/tcp kickass_ptolemy
</code></pre>
<p>I set port as 123.</p>
<p>My container IP is <code>172.17.0.2</code></p>
<pre><code>docker inspect 5d993a622d23 | grep IP
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"IPAMConfig": null,
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
</code></pre>
<p>On my Mac I try to ping my container,</p>
<p><code>Ping 172.17.0.2</code>, I got Request timeout for icmp_seq 0....</p>
<p>What should I do? So my local machine can ping the container I installed. Did I missing some app installation on my container, which is a plain ubuntu system?</p> | 0 |
Data Conversion Error while applying a function to each row in pandas Python | <p>I have a data frame in pandas in python which resembles something like this - </p>
<pre><code> contest_login_count contest_participation_count ipn_ratio
0 1 1 0.000000
1 3 3 0.083333
2 3 3 0.000000
3 3 3 0.066667
4 5 13 0.102804
5 2 3 0.407407
6 1 3 0.000000
7 1 2 0.000000
8 53 91 0.264151
9 1 2 0.000000
</code></pre>
<p>Now I want to apply a function to each row of this dataframe The function is written as this - </p>
<pre><code>def findCluster(clusterModel,data):
return clusterModel.predict(data)
</code></pre>
<p>I apply this function to each row in this manner - </p>
<pre><code>df_fil.apply(lambda x : findCluster(cluster_all,x.reshape(1,-1)),axis=1)
</code></pre>
<p>When I run this code, I get a warning saying - </p>
<blockquote>
<p>DataConversionWarning: Data with input dtype object was converted to float64.</p>
<p>warnings.warn(msg, DataConversionWarning)</p>
</blockquote>
<p>This warning is printed once for each row. Since, I have around 450K rows in my data frame, my computer hangs while printing all these warning messages that too on ipython notebook.</p>
<p>But to test my function I created a dummy dataframe and tried applying the same function on that and it works well. Here is the code for that - </p>
<pre><code>t = pd.DataFrame([[10.35,100.93,0.15],[10.35,100.93,0.15]])
t.apply(lambda x:findCluster(cluster_all,x.reshape(1,-1)),axis=1)
</code></pre>
<p>The output to this is - </p>
<pre><code> 0 1 2
0 4 4 4
1 4 4 4
</code></pre>
<p>Can anyone suggest what am I doing wrong or what can I change to make this error go away?</p> | 0 |
Replace value of Input field jquery | <p>I am just trying to replace the value of the following input field:</p>
<pre><code><input id="farbe" style="background-image: url('images/colors/RAL_1001.png'), no-repeat;" value="Farbton wählen">
</code></pre>
<p>the needed Value I get out of my autocomplete list. The alert works fine (correct value), but I do not get the value of the input field replaced. </p>
<pre><code>$(document).ready(function () {
$('#farbe').on('autocompletechange change', function () {
var wert = this.value;
alert(wert);
$('#farbe').attr("value",wert);
});
});
</code></pre>
<p>What am I doing wrong?</p> | 0 |
How do I store JWT and send them with every request using react | <p>So happy right know because I got my basic registration/authentication system going on.</p>
<p>so basically I got this :</p>
<pre><code>app.post('/login', function(req,res) {
Users.findOne({
email: req.body.email
}, function(err, user) {
if(err) throw err;
if(!user) {
res.send({success: false, message: 'Authentication Failed, User not found.'});
} else {
//Check passwords
checkingPassword(req.body.password, user.password, function(err, isMatch) {
if(isMatch && !err) {
//Create token
var token = jwt.sign(user,db.secret, {
expiresIn: 1008000
});
res.json({success: true, jwtToken: "JWT "+token});
} else {
res.json({success: false, message: 'Authentication failed, wrong password buddy'});
}
});
}
});
});
</code></pre>
<p>Then I secure my /admin routes and with POSTMAN whenever I send a get request with the jwt in the header everything works perfectly.</p>
<p>Now here is the tricky part, basically When i'm going to login if this a sucess then redirect me to the admin page, and everytime I try to access admin/* routes I want to send to the server my jwToken but the problem is, how do I achieve that ? I'm not using redux/flux, just using react/react-router.</p>
<p>I don't know how the mechanic works.</p>
<p>Thanks guys</p> | 0 |
PowerShell: how to delete a path in the Path environment variable | <p>I used "setx" to add a new path to my PATH environment variable. How do I see whether we can delete the newly added path from PATH environment variable?</p> | 0 |
What is the HTTP status code for License limit reached | <p>I want to know what is the ideal HTTP status code an API should return when a user's license has reached?</p>
<p>Initially I was thinking its 402 (Payment Required) but this is not my scenario. My case is if my user has a limit to add 10 plugins, if she tries to add the 11th plugin they should get an error that their limit has reached.</p>
<p>Please help me with the appropriate HTTP status code for this.</p>
<p>Thanks in advance</p> | 0 |
Full-width image inside container in Bootstrap 4 | <p>I am using Bootstrap 4 and I have a template layout with</p>
<pre><code><div class="navbar">
...
</div>
<div class="container">
{{content}}
</div>
</code></pre>
<p>This works in almost all cases. However, sometimes I want an image in the content to take up the full width, but this is not possible due to the <code>.container</code> which uses <code>left-padding</code> and <code>right-padding</code>.</p>
<p>I could solve this by adding the <code>.container</code> class in each view at the right places instead of in my template layout file, but this will become quite annoying. Especially if I have a CMS where different authors can write articles, and if they want a full-width image in the middle of their article, they have to write raw html to be something like</p>
<pre><code><div class="container">
some text
</div>
<div class="full-width-image">
<img src="" alt="">
</div>
<div class="container">
more text
</div>
..
</code></pre>
<p>How could I solve this problem?</p> | 0 |
Serializing image stream using protobuf | <p>I have two programs in Ubuntu: a C++ program (TORCS game) and a python program. The C++ program always generates images. I want to transfer these real-time images into python(maybe the numpy.ndarray format). So I think that maybe using Google protobuf to serialize the image to string and send string to python client by ZMQ is a feasible method.</p>
<p><strong>Question</strong>: which value type is suitable for the image(a pointer) in <code>.proto</code> file? In another words, which value type I should use to replace <code>string</code> type in the below example?</p>
<pre><code>message my_image{
repeated string image = 1
}
</code></pre>
<p>This is the way I write image to memory (uint8_t* image_data):</p>
<pre><code>glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)image_data);
</code></pre>
<p>At last, maybe there is a better way to transfer image (in the memory) to a python client?</p>
<p>Any suggestions are appreciated.</p> | 0 |
Is there a difference between ? and * in cron expressions? Strange example | <p>I have the following cron expression in my system:</p>
<pre><code>0 0 0/1 1/1 * ? *
</code></pre>
<p>and you know what? I have no idea what it means. The guy who has written it is on his holiday for the next 2 weeks so I have to find out on myself. The documentation can be found <a href="https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm#CIHBEEFA" rel="noreferrer">here</a></p>
<p>According to the <a href="https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm#CIHBEEFA" rel="noreferrer">documentation</a> we have:</p>
<pre><code>* * * * * * *
| | | | | | |
| | | | | | +-- Year (range: 1970-2099)
| | | | | +---- Day of the Week (range: 1-7 or SUN-SAT)
| | | | +------ Month of the Year (range: 0-11 or JAN-DEC)
| | | +-------- Day of the Month (range: 1-31)
| | +---------- Hour (range: 0-23)
| +------------ Minute (range: 0-59)
+-------------- Second (range: 0-59)
</code></pre>
<p>Ok, let me tell you what I think: I believe that the expression means:</p>
<pre><code>start when:
seconds: 0
minutes: 0
hours: 0
dayOfMonth 1
monthOfYear any
dayOfWeek any
year any
run every:
1 hour
1 dayOfWeek
when:
dayOfWeek same as on first execution
</code></pre>
<p>However available cron expression monitors says that it simply means every hour.
As the one who has written that is Senior Java Dev, he must have known any reason for writing such expression instead of:</p>
<pre><code>0 0 * * * * *
</code></pre>
<p>We use <code>org.springframework.scheduling.quartz.QuartzJobBean</code>.</p>
<p><strong>Short summary</strong></p>
<p>Well, I think that my question is: what is the difference between <code>0 0 0/1 1/1 * ? *</code> and <code>0 0 * * * * *</code>?</p>
<p><strong>Edit:</strong></p>
<p><a href="http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html" rel="noreferrer">The documentation</a> can be found here. </p> | 0 |
How do I install ruby gems on Mac | <p>How do I install RubyGems on my Mac?</p>
<p>I tried to run <code>$ gem install rubygems-update</code> with no luck . It returns</p>
<pre><code>ERROR: While executing gem ... (Gem::FilePermissionError)
You don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory.
</code></pre>
<p>Any help would be great. Thanks</p> | 0 |
Excel VBA - How to find a value in a column and return the row it is on | <p>I currently use a for loop to look through column A in the HDD database sheet and when it finds the matching search criteria it copies all the information in that row into a designated area. </p>
<p>I am trying to use the same for loop to tell me which row the search criteria is found on so i can delete that row from the HDD database sheet.</p>
<p>Tried a few things but nothing seems to work.</p>
<p>Any help is very welcome on this.</p>
<pre><code>Private Sub EditButton_Click()
Dim Userentry As String
Dim i As Long
Dim ws, ws1, ws2 As Worksheet
'Dim found As Range
Dim RowNumber As String
Set ws = Sheets("HDD database")
Set ws1 = Sheets("HDD log")
Set ws2 = Sheets("Sheet3")
Userentry = editTxtbox.Value
'ws1.Range("A36").Value = Userentry
For i = 1 To ws.Range("A" & Rows.Count).End(xlUp).Row
If (ws.Cells(i, 1).Value) = Userentry Then
ws2.Range("A1").Offset(1, 0).Resize(1, 8).Value = _
ws.Cells(i, 1).Resize(1, 8).Value
End If
Next i
addnewHDDtxtbox.Value = ws2.Range("A2")
MakeModeltxtbox.Value = ws2.Range("B2")
SerialNumbertxtbox.Value = ws2.Range("C2")
Sizetxtbox.Value = ws2.Range("D2")
Locationtxtbox.Value = ws2.Range("E2")
Statetxtbox.Value = ws2.Range("F2")
For i = 1 To ws.Range("A" & Rows.Count).End(xlUp).Row
If (ws.Cells(i, 1).Value) = Userentry Then
RowNumber = ws.Cells.Row
End If
Next i
ws1.Range("I3").Value = RowNumber
End Sub
</code></pre> | 0 |
How to set UICollectionView bottom padding and scrolling size | <p>Hello I have working <code>uicollectionview</code> custom layout and i have <code>issues</code>for <code>bottom padding</code> and <code>scrolling sizes</code>. Under below <code>picture</code> you can see;</p>
<blockquote>
<p>Also top side first cell always stays on top when scrolling ( Left side cell must be always stay right now no problem there , but top side cell must be scroll when scrolling )</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/hq0xK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hq0xK.png" alt="enter image description here"></a></p>
<p>I try to set in <code>viewDidLoad</code> under below codes but <code>dont</code> work</p>
<pre><code>self.automaticallyAdjustsScrollViewInsets = false
self.collectionView.contentInset = UIEdgeInsetsMake(20, 20, 120, 100);
</code></pre>
<p>My custom <code>collectionview layout</code> file</p>
<pre><code>import UIKit
public var CELL_HEIGHT = CGFloat(22)
protocol CustomCollectionViewDelegateLayout: NSObjectProtocol {
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, widthForItemAtIndexPath indexPath: NSIndexPath) -> CGFloat
}
class CustomCollectionViewLayout: UICollectionViewLayout {
// Used for calculating each cells CGRect on screen.
// CGRect will define the Origin and Size of the cell.
let STATUS_BAR = UIApplication.sharedApplication().statusBarFrame.height
// Dictionary to hold the UICollectionViewLayoutAttributes for
// each cell. The layout attribtues will define the cell's size
// and position (x, y, and z index). I have found this process
// to be one of the heavier parts of the layout. I recommend
// holding onto this data after it has been calculated in either
// a dictionary or data store of some kind for a smooth performance.
var cellAttrsDictionary = Dictionary<NSIndexPath, UICollectionViewLayoutAttributes>()
// Defines the size of the area the user can move around in
// within the collection view.
var contentSize = CGSize.zero
// Used to determine if a data source update has occured.
// Note: The data source would be responsible for updating
// this value if an update was performed.
var dataSourceDidUpdate = true
weak var delegate: CustomCollectionViewDelegateLayout?
override func collectionViewContentSize() -> CGSize {
return self.contentSize
}
override func prepareLayout() {
// Only update header cells.
if !dataSourceDidUpdate {
// Determine current content offsets.
let xOffset = collectionView!.contentOffset.x
let yOffset = collectionView!.contentOffset.y
if collectionView?.numberOfSections() > 0 {
for section in 0...collectionView!.numberOfSections()-1 {
// Confirm the section has items.
if collectionView?.numberOfItemsInSection(section) > 0 {
// Update all items in the first row.
if section == 0 {
for item in 0...collectionView!.numberOfItemsInSection(section)-1 {
// Build indexPath to get attributes from dictionary.
let indexPath = NSIndexPath(forItem: item, inSection: section)
// Update y-position to follow user.
if let attrs = cellAttrsDictionary[indexPath] {
var frame = attrs.frame
// Also update x-position for corner cell.
if item == 0 {
frame.origin.x = xOffset
}
frame.origin.y = yOffset
attrs.frame = frame
}
}
// For all other sections, we only need to update
// the x-position for the fist item.
} else {
// Build indexPath to get attributes from dictionary.
let indexPath = NSIndexPath(forItem: 0, inSection: section)
// Update y-position to follow user.
if let attrs = cellAttrsDictionary[indexPath] {
var frame = attrs.frame
frame.origin.x = xOffset
attrs.frame = frame
}
}
}
}
}
// Do not run attribute generation code
// unless data source has been updated.
return
}
// Acknowledge data source change, and disable for next time.
dataSourceDidUpdate = false
var maxWidthInASection = CGFloat(0)
// Cycle through each section of the data source.
if collectionView?.numberOfSections() > 0 {
for section in 0...collectionView!.numberOfSections()-1 {
// Cycle through each item in the section.
if collectionView?.numberOfItemsInSection(section) > 0 {
var prevCellAttributes: UICollectionViewLayoutAttributes?
for item in 0...collectionView!.numberOfItemsInSection(section)-1 {
let cellIndex = NSIndexPath(forItem: item, inSection: section)
guard let width = delegate?.collectionView(collectionView!, layout: self, widthForItemAtIndexPath: cellIndex) else {
print("Please comform to CustomCollectionViewDelegateLayout protocol")
return
}
// Build the UICollectionVieLayoutAttributes for the cell.
var xPos = CGFloat(0)
let yPos = CGFloat(section) * CELL_HEIGHT
if let prevCellAttributes = prevCellAttributes {
xPos = CGRectGetMaxX(prevCellAttributes.frame)
}
let cellAttributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: cellIndex)
cellAttributes.frame = CGRect(x: xPos, y: yPos, width: width, height: CELL_HEIGHT)
// Determine zIndex based on cell type.
if section == 0 && item == 0 {
cellAttributes.zIndex = 4
} else if section == 0 {
cellAttributes.zIndex = 3
} else if item == 0 {
cellAttributes.zIndex = 2
} else {
cellAttributes.zIndex = 1
}
// Save the attributes.
cellAttrsDictionary[cellIndex] = cellAttributes
prevCellAttributes = cellAttributes
let maxX = CGRectGetMaxX(cellAttributes.frame)
if maxWidthInASection < maxX {
maxWidthInASection = maxX
}
}
}
}
}
// Update content size.
let contentWidth = maxWidthInASection
let contentHeight = Double(collectionView!.numberOfSections())
self.contentSize = CGSize(width: Double(contentWidth), height: contentHeight)
self.contentSize.height = CGFloat(Double(collectionView!.numberOfSections()))
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
// Create an array to hold all elements found in our current view.
var attributesInRect = [UICollectionViewLayoutAttributes]()
// Check each element to see if it should be returned.
for cellAttributes in cellAttrsDictionary.values.elements {
if CGRectIntersectsRect(rect, cellAttributes.frame) {
attributesInRect.append(cellAttributes)
}
}
// Return list of elements.
return attributesInRect
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
return cellAttrsDictionary[indexPath]!
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
}
</code></pre>
<p>I try change collecionview properties in <code>storyboard</code> but doesnt works also i attached current <code>collectionview</code> object properties picture under below</p>
<p><a href="https://i.stack.imgur.com/yUpE3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yUpE3.png" alt="enter image description here"></a></p>
<blockquote>
<p>Also i selected zoom 4 but zoom feature doesnt work ? why ? it must be work also zoom feature.</p>
</blockquote> | 0 |
Docker doesn't resolve hostname | <p>I need to know the hostnames (or ip addresses) of some container running on the same machine.
As I already commented <a href="https://stackoverflow.com/questions/26269870/how-do-docker-containers-resolve-hostname-of-other-docker-containers-running-on/26274232#comment65923973_26274232">here</a> (but with no answer yet), I use <code>docker-compose</code>. The <a href="https://docs.docker.com/compose/networking/" rel="noreferrer">documentation</a> says, compose will automatically create a hostname entry for all container defined in the same <code>docker-compose.yml</code> file:</p>
<blockquote>
<p>Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.</p>
</blockquote>
<p>But I can't see any host entry via <code>docker exec -it my_container tail -20 /etc/hosts</code>.
I also tried to add <code>links</code> to my container, but nothing changed.</p> | 0 |
"TypeError: Unsupported type <class 'list'> in write()" | <p>I wish to print 'out.csv' data in excel file when the condition is not uppercase. But the data in out.csv is list of data instead of string. How do I write the list to excel file without converting it to string? (As I have other file which may need to use list instead of string)</p>
<p>Python version #3.5.1</p>
<pre><code>import xlsxwriter
import csv
import xlwt
f1= open('out.csv')
data=csv.reader(f1)
# Create a new workbook and add a worksheet
workbook = xlsxwriter.Workbook('1.xlsx')
worksheet = workbook.add_worksheet()
# Write some test data.
for module in data:
str1 = ''.join(module)
if str1.isupper():
pass
else:
worksheet.write('A', module)
workbook.close()
</code></pre> | 0 |
fixing apache v9.0 Server Tomcat v9.0 Server at localhost failed to start error | <p>i have a simple java ee project which i need to send an email to a user, i found that it is possible with javamail and the gmail free smtp.</p>
<p>my mail sender implementation:</p>
<pre><code>package duck.reg.pack;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
@WebServlet("/sendmailtls")
public class SendMailTLS extends HttpServlet {
public static void main(){
final String username = "[email protected]";
final String password = "Password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
</code></pre>
<p>now the problem is that when ever i compile my program i get apache error saying:</p>
<blockquote>
<p>'Starting tomcat v9.0 Server at localhost' has encountered a problem.
Server Tomcat v9.0 Server at localhost failed to start.</p>
</blockquote>
<p>and i found that if i remove </p>
<pre><code>Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
</code></pre>
<p>it compile just fine.</p> | 0 |
require() node module from Electron renderer process served over HTTP | <p>Typically, in an Electron app, you can <code>require</code> node modules from both the main process and the renderer process:</p>
<pre><code>var myModule = require('my-module');
</code></pre>
<p>However, this doesn't seem to work if the page was loaded via HTTP instead of from the local filesystem. In other words, if I open a window like this:</p>
<pre><code>win.loadURL(`file://${__dirname}/index.html`);
</code></pre>
<p>I can <code>require</code> a node module without problems. But if I instead open a window like this:</p>
<pre><code>win.loadURL(`http://localhost:1234/index.html`);
</code></pre>
<p>I no longer can <code>require</code> node modules inside my web page - I get <code>Uncaught Error: Cannot find module 'my-module'</code> in the web page's console. Is there any way to use node modules in an Electron page that was served over HTTP?</p>
<hr />
<p>A little context: My company is building an application that needs the ability to be hosted as a web application <em>and</em> inside an Electron shell. To make this simpler and consistent across both environments, my Electron app starts a local web server and opens the app hosted at <code>http://localhost:1234</code>. Now I'd like the ability to add spell checking/spelling suggestions into the application using <a href="https://www.npmjs.com/package/electron-spell-check-provider" rel="noreferrer"><code>electron-spell-check-provider</code></a>. This module needs to be imported and initialized inside the renderer process, so I'm trying to <code>require('electron-spell-check-provider')</code> inside my web page, but this fails with the <code>Cannot find module</code> error.</p> | 0 |
copy and paste one cell value to multiple cells | <p>If I work in my spreadsheed, without using any vba-code, I could select a single cell, copy, then select a bunch of cells, and paste. The result would be that all the target cells are filled with whatever value was in the source cell. </p>
<p>How would I do this in vba-code?</p>
<p><s>You would think the following would work because it mimics the behavior described above, but it doesn't. It will fill the top cell of the target range with the value and leave the rest of the cells empty. </s></p>
<pre><code> Range("A1").Select
Selection.Copy
Range("B1:B12").Select
ActiveSheet.Paste
</code></pre> | 0 |
Firebase cloud messaging duplicate notifications | <p>We are using Firebase cloud messaging.
Sometimes when Android or iOS app is in sleep mode the cell phone receives same (duplicates) notifications messages.
For device identifications the FIRInstanceID token is used. An external server on node.js is used for sending notifications to Firebase service.
No duplications in our server log file are presented.</p> | 0 |
CORS issue in vertx Application not working | <p>My Vertx Server resides in server A and client resides in server B. When i tried to access vertx server, CORS error pops in. I added some server side code to handle CORS issue but it's not working. Do we need to add some header in client side. what am i missing here? Can anyone help</p>
<p>Vertx Server Side: </p>
<pre><code>Router router = Router.router(vertx);
router.route().handler(BodyHandler.create());
router.route().handler(io.vertx.rxjava.ext.web.handler.CorsHandler.create("*")
.allowedMethod(io.vertx.core.http.HttpMethod.GET)
.allowedMethod(io.vertx.core.http.HttpMethod.POST)
.allowedMethod(io.vertx.core.http.HttpMethod.OPTIONS)
.allowedHeader("Access-Control-Request-Method")
.allowedHeader("Access-Control-Allow-Credentials")
.allowedHeader("Access-Control-Allow-Origin")
.allowedHeader("Access-Control-Allow-Headers")
.allowedHeader("Content-Type"));
</code></pre>
<p>Client implementation:</p>
<pre><code> function(url, user) {
eventBus = new EventBus(url);
eventBus.onopen = function() {
//Do Something
}
}
</code></pre>
<p><strong>Update:</strong></p>
<p>I removed the withCredential attribute in header.Now my code looks like </p>
<pre><code>if (ar.succeeded()) {
routingContext.response().setStatusCode(200).setStatusMessage("OK")
.putHeader("content-type", "application/json")
.putHeader("Access-Control-Allow-Origin", "*")
.putHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS")
.end(
Json.encodePrettily(ar.result().body())
//(String) ar.result().body()
);
routingContext.response().close();
</code></pre>
<p>but still following error pops up. Can you help?</p>
<pre><code>XMLHttpRequest cannot load https://192.168.1.20:7070/Notify/571/rn4nh0r4/xhr_send?t=1471592391921. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'https://login.com' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.
</code></pre>
<p><strong>Update2:</strong>
After adding my client address in </p>
<pre><code>.putHeader("Access-Control-Allow-Origin", "*")
</code></pre>
<p>I got following log:</p>
<pre><code>XMLHttpRequest cannot LOAD https://192.168.1.20:7070/Notify/773/k3zq1z2z/xhr_send?t=1471601521206. Credentials flag IS 'true', but the 'Access-Control-Allow-Credentials' header IS ''. It must be 'true' TO allow credentials. Origin 'https://login.com' IS therefore NOT allowed access.
</code></pre>
<p>My code is as follows:</p>
<pre><code> if (ar.succeeded()) {
routingContext.response().setStatusCode(200).setStatusMessage("OK")
.putHeader("content-type", "application/json")
.putHeader("Access-Control-Allow-Origin", "https://login.com")
.putHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS")
.putHeader("Access-Control-Allow-Credentials", "true")
.end(
Json.encodePrettily(ar.result().body())
//(String) ar.result().body()
);
routingContext.response().close();
</code></pre> | 0 |
How do I find which object is EventSystem.current.IsPointerOverGameObject detecting? | <p>I am using EventSystem.current.IsPointerOverGameObject in a script and Unity returns True even though I would swear there is no UI/EventSystem object beneath the pointer.</p>
<p>How can I find information about the object the EventSystem is detecting?</p> | 0 |
Python Argparse: Raw string input | <p>Apologies if this has been asked before, I did search for it but all hits seemed to be about python raw strings in general rather than regarding argparse.</p>
<p>Anyways, I have a code where the user feeds in a string and then this string is processed. However, I have a problem as I want my code to be able to differentiate between <code>\n</code> and <code>\\n</code> so that the user can control if they get a line break or <code>\n</code> appear in the output (respectively). </p>
<p>This in itself is quite simple, and I can get the logic working to check the string, etc. However, argparse doesn't seem to keep the input string raw. So if I were to write: <code>Here is a list:\nItem 1</code> it gets parsed as <code>Here is a list:\\nItem 1</code>. As the exact same thing gets parsed if I were to replace <code>\n</code> with <code>\\n</code> in the input string, it becomes impossible to differentiate between the two.</p>
<p>I could include a bodge (for example, I could make the user enter say <code>$\n</code> for <code>\n</code> to appear in the output, or just <code>\n</code> for a line break). But this is messy and complicates the usage of the code.</p>
<p>Is there a way to ensure the string being parsed by argparse is raw? (I.e. if I enter <code>\n</code> it parses <code>\n</code> and not <code>\\n</code>)</p>
<p>Again, sorry if this has been asked before, but I couldn't find an answer and after over an hour of trying to find an answer, I'm out of ideas (bar the bodge). Cheers in advance for any and all help.</p>
<p>Example code (sorry if this doesn't work, not sure how best to do example code for argparse!):</p>
<pre><code>import argparse
parser = argparse.ArgumentParser( description = 'Test.' )
parser.add_argument( 'text', action = 'store', type = str, help = 'The text to parse.' )
args = parser.parse_args( )
print( repr( args.text ) )
</code></pre> | 0 |
How to treat uppercase and lowercase words the same in Python | <p>Code:</p>
<pre><code>str1 = input("Please enter a full sentence: ")
print("Thank you, You entered:" , str1)
str2 = input("Now please enter a word included in your sentence in anyway you like: ")
if str2 in str1:
print("That word was found!")
else:
print("Sorry, that word was not found")
</code></pre>
<p>I have done some research on forums etc and the only solutions i can find for this subject are converting words into uppercase/lowercase. I don't want to do it like that.</p>
<p>I want something that will ignore the fact that it is uppercase or lowercase and will assume it to be the same word, so when someone inputs a sentence it will automatically assume it t be the same word. For example: (Treat = treat, TREAT, TreAT etc). So it will essentially read the characters in the word and will ignore the uppercase/lowercase letters. </p>
<p>I do have something (string.ascii_letters) which i think might do it, but if anyone know any better way of doing it then that would be greatly appreciated! :)</p> | 0 |