title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
Is metadata or attributes allowed in Golang? | <p>How are these various validation libraries adding this meta data to structs like:</p>
<pre><code>type Post struct {
Title string `valid:"alphanum,required"`
Message string `valid:"duck,ascii"`
AuthorIP string `valid:"ipv4"`
Date string `valid:"-"`
}
</code></pre>
<p>I'm confused, the property is Title, the type is string. Beyond that how can you just add <code>valid:"alphanum,required"</code> Is this using reflection?</p>
<p>Is this like attributes in other languages?</p>
<pre><code>[Required]
public int Title { get;set; }
</code></pre> | 1 |
VBA Excel to Mac - file path | <p>The person that previously had my job used VBA in Excel on PC to create reports to track the finances in the office. It takes info from multiple workbooks. I would like to run it on a Mac. I moved all the relevant files to my computer. I know I need to update the file paths but I am lost even doing that. </p>
<p>The current file path looks like:
Application.Workbooks.Open ("C:\Users\Chris Treeman\My Documents\Dept MathCS Financials\Accounting Files\Dept. Fund Tracking\Daily Compass Report Files\" & "CFSPPSUM - " & SpecifiedDate & ".xls")</p>
<p>I have copied the path from my Mac using Get Info. Would this be correct?
Application.Workbooks.Open ("/Users/robert/Documents/Reporting/Dept MathCS Financials/Accounting Files/Dept. Fund Tracking/Daily Compass Report Files/" & "CFSPPSUM - " & SpecifiedDate & ".xls")</p>
<p>OS X El Capitan Version 10.11.3<br>
Microsoft Excel for Mac 2011 Version 14.5.9</p>
<p>Below is the code from the main module.</p>
<pre><code>Sub Test()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim i As Integer
i = 6
Dim SpecifiedDate As String
SpecifiedDate = Cells(4, ActiveCell.Column)
SpecifiedDate = Format(SpecifiedDate, "mm/dd/yyyy")
SpecifiedDate = Replace(SpecifiedDate, "/", "-")
Dim TWB As Workbook
Set TWB = ThisWorkbook
Col = ActiveCell.Column
'CFSPPSUM Data Transfer
Application.Workbooks.Open ("C:\Users\Chris Treeman\My Documents\Dept MathCS Financials\Accounting Files\Dept. Fund Tracking\Daily Compass Report Files\" & "CFSPPSUM - " & SpecifiedDate & ".xls")
While TWB.Worksheets("Import-Data").Cells(i, 3).Value <> "END"
On Error Resume Next
TWB.Worksheets("Import-Data").Cells(i, Col) = Application.WorksheetFunction.VLookup(TWB.Worksheets("Import-Data").Cells(i, 3).Value, _
Workbooks("CFSPPSUM - " & SpecifiedDate & ".xls").Worksheets("Output Data Sheet").Range("$E$9:$AA$100"), 23, False)
i = i + 1
Wend
Cells(6, ActiveCell.Column).Select
Windows("CFSPPSUM - " & SpecifiedDate & ".xls").Close (False)
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Sub Test_Final_Build()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
If ActiveCell.Row = 6 Then
Dim SpecifiedDate As String
SpecifiedDate = Cells(4, ActiveCell.Column)
SpecifiedDate = Format(SpecifiedDate, "mm/dd/yyyy")
SpecifiedDate = Replace(SpecifiedDate, "/", "-")
Dim TWB As Workbook
Set TWB = ThisWorkbook
Col = ActiveCell.Column
Dim NSPLoc As String, NSPL As Integer
NSPLoc = Application.WorksheetFunction.Match("NSP SUM", Range("B1:B200"), 0)
NSPL = NSPLoc
Dim D831020Loc As String, D831020L As Integer
D831020Loc = Application.WorksheetFunction.Match("Dept. 831020", Range("B1:B200"), 0)
D831020L = D831020Loc
Dim SPPISUMLoc As String, SPPISUML As Integer, NSPISUMLoc As String, NSPISUML As Integer
SPPISUMLoc = Application.WorksheetFunction.Match("SPP I-SUM", Range("C1:C200"), 0)
SPPISUML = SPPISUMLoc
NSPISUMLoc = Application.WorksheetFunction.Match("NSP I-SUM", Range("C1:C200"), 0)
NSPISUML = NSPISUMLoc
Dim i As Integer, j As Integer, k As Integer, l As Integer, m As Integer, n As Integer, o As Integer, p As Integer, q As Integer, r As Integer, s As Integer, t As Integer, u As Integer
i = 6 'SPP Sum Location
j = 6 'NSP Sum Location
k = 6
l = 6
m = 6
n = 6
o = 6
p = 6
q = 6
r = 6
s = 6
t = 6
u = 6
'CFNSPSUM Data Transfer
Application.Workbooks.Open ("C:\Users\Chris Treeman\My Documents\Dept MathCS Financials\Accounting Files\Dept. Fund Tracking\Daily Compass Report Files\" & "CFNSPSUM - " & SpecifiedDate & ".xls")
While TWB.Worksheets("Import-Data").Cells(j, 3).Value <> "END"
On Error Resume Next
TWB.Worksheets("Import-Data").Cells(j, Col) = Application.WorksheetFunction.VLookup(TWB.Worksheets("Import-Data").Cells(j, 3).Value, _
Workbooks("CFNSPSUM - " & SpecifiedDate & ".xls").Worksheets("Sheet1").Range("$E$11:$BI$150"), 57, False)
j = j + 1
Wend
Windows("CFNSPSUM - " & SpecifiedDate & ".xls").Activate 'Sum Total Check Figure Import
Sheets("Sheet1").Select
Range("BI106").Copy
TWB.Sheets("Import-Data").Activate
Cells(NSPISUML, ActiveCell.Column).PasteSpecial xlPasteValues
Windows("CFNSPSUM - " & SpecifiedDate & ".xls").Close (False)
'CFSPPSUM Data Transfer
Application.Workbooks.Open ("C:\Users\Chris Treeman\My Documents\Dept MathCS Financials\Accounting Files\Dept. Fund Tracking\Daily Compass Report Files\" & "CFSPPSUM - " & SpecifiedDate & ".xls")
While TWB.Worksheets("Import-Data").Cells(i, 3).Value <> "END"
On Error Resume Next
TWB.Worksheets("Import-Data").Cells(i, Col) = Application.WorksheetFunction.VLookup(TWB.Worksheets("Import-Data").Cells(i, 3).Value, _
Workbooks("CFSPPSUM - " & SpecifiedDate & ".xls").Worksheets("Output Data Sheet").Range("$E$9:$AA$100"), 23, False)
i = i + 1
Wend
Windows("CFSPPSUM - " & SpecifiedDate & ".xls").Activate 'Sum Total Check figure import
Sheets("Output Data Sheet").Select
Range("AA80").Copy
TWB.Sheets("Import-Data").Activate
Cells(SPPISUML, ActiveCell.Column).PasteSpecial xlPasteValues
Windows("CFSPPSUM - " & SpecifiedDate & ".xls").Close (False)
'Dept. 831020 Data Transfer
Application.Workbooks.Open ("C:\Users\Chris Treeman\My Documents\Dept MathCS Financials\Accounting Files\Dept. Fund Tracking\Daily Compass Report Files\" & "Dept. 831020 - " & SpecifiedDate & ".xls")
While TWB.Worksheets("Import-Data").Cells(k, 3).Value <> "END"
On Error Resume Next
TWB.Worksheets("Import-Data").Cells(k, Col) = Application.WorksheetFunction.VLookup(TWB.Worksheets("Import-Data").Cells(k, 3).Value, _
Workbooks("Dept. 831020 - " & SpecifiedDate & ".xls").Worksheets("Sheet1").Range("$E$10:$AY$100"), 47, False)
k = k + 1
Wend
Windows("Dept. 831020 - " & SpecifiedDate & ".xls").Close (False)
'Dept. 831021 Data Transfer
Application.Workbooks.Open ("C:\Users\Chris Treeman\My Documents\Dept MathCS Financials\Accounting Files\Dept. Fund Tracking\Daily Compass Report Files\" & "Dept. 831021 - " & SpecifiedDate & ".xls")
While TWB.Worksheets("Import-Data").Cells(l, 3).Value <> "END"
On Error Resume Next
TWB.Worksheets("Import-Data").Cells(l, Col) = Application.WorksheetFunction.VLookup(TWB.Worksheets("Import-Data").Cells(l, 3).Value, _
Workbooks("Dept. 831021 - " & SpecifiedDate & ".xls").Worksheets("Sheet1").Range("$E$10:$AY$100"), 47, False)
l = l + 1
Wend
Windows("Dept. 831021 - " & SpecifiedDate & ".xls").Close (False)
'Dept. 831022 Data Transfer
Application.Workbooks.Open ("C:\Users\Chris Treeman\My Documents\Dept MathCS Financials\Accounting Files\Dept. Fund Tracking\Daily Compass Report Files\" & "Dept. 831022 - " & SpecifiedDate & ".xls")
While TWB.Worksheets("Import-Data").Cells(m, 3).Value <> "END"
On Error Resume Next
TWB.Worksheets("Import-Data").Cells(m, Col) = Application.WorksheetFunction.VLookup(TWB.Worksheets("Import-Data").Cells(m, 3).Value, _
Workbooks("Dept. 831022 - " & SpecifiedDate & ".xls").Worksheets("Sheet1").Range("$E$10:$AY$100"), 47, False)
m = m + 1
Wend
Windows("Dept. 831022 - " & SpecifiedDate & ".xls").Close (False)
'Dept. 831023 Data Transfer
Application.Workbooks.Open ("C:\Users\Chris Treeman\My Documents\Dept MathCS Financials\Accounting Files\Dept. Fund Tracking\Daily Compass Report Files\" & "Dept. 831023 - " & SpecifiedDate & ".xls")
While TWB.Worksheets("Import-Data").Cells(n, 3).Value <> "END"
On Error Resume Next
TWB.Worksheets("Import-Data").Cells(n, Col) = Application.WorksheetFunction.VLookup(TWB.Worksheets("Import-Data").Cells(n, 3).Value, _
Workbooks("Dept. 831023 - " & SpecifiedDate & ".xls").Worksheets("Sheet1").Range("$E$10:$AY$100"), 47, False)
n = n + 1
Wend
Windows("Dept. 831023 - " & SpecifiedDate & ".xls").Close (False)
'CFNSPS01 Data Transfer
Application.Workbooks.Open ("C:\Users\Chris Treeman\My Documents\Dept MathCS Financials\Accounting Files\Dept. Fund Tracking\Daily Compass Report Files\" & "CFNSPS01 - PROVOST BAYH-DOLE RESTRICTED S" & SpecifiedDate & ".xls")
While TWB.Worksheets("Import-Data").Cells(o, 3).Value <> "END"
On Error Resume Next
TWB.Worksheets("Import-Data").Cells(o, Col) = Application.WorksheetFunction.VLookup(TWB.Worksheets("Import-Data").Cells(o, 3).Value, _
Workbooks("CFNSPS01 - PROVOST BAYH-DOLE RESTRICTED S" & SpecifiedDate & ".xls").Worksheets("Sheet1").Range("$E$11:$BI$200"), 57, False)
o = o + 1
Wend
Windows("CFNSPS01 - PROVOST BAYH-DOLE RESTRICTED S" & SpecifiedDate & ".xls").Close (False)
'CFNSPS02 Data Transfer
Application.Workbooks.Open ("C:\Users\Chris Treeman\My Documents\Dept MathCS Financials\Accounting Files\Dept. Fund Tracking\Daily Compass Report Files\" & "CFNSPS02 - N16 SCIENCE HIRE INITIATIVE" & SpecifiedDate & ".xls")
While TWB.Worksheets("Import-Data").Cells(p, 3).Value <> "END"
On Error Resume Next
TWB.Worksheets("Import-Data").Cells(p, Col) = Application.WorksheetFunction.VLookup(TWB.Worksheets("Import-Data").Cells(p, 3).Value, _
Workbooks("CFNSPS02 - N16 SCIENCE HIRE INITIATIVE" & SpecifiedDate & ".xls").Worksheets("Sheet1").Range("$E$11:$BI$200"), 57, False)
p = p + 1
Wend
Windows("CFNSPS02 - N16 SCIENCE HIRE INITIATIVE" & SpecifiedDate & ".xls").Close (False)
'CFNSPS03 Data Transfer
Application.Workbooks.Open ("C:\Users\Chris Treeman\My Documents\Dept MathCS Financials\Accounting Files\Dept. Fund Tracking\Daily Compass Report Files\" & "CFNSPS03 - MICHELANGELO GRIGNI START-UP F" & SpecifiedDate & ".xls")
While TWB.Worksheets("Import-Data").Cells(q, 3).Value <> "END"
On Error Resume Next
TWB.Worksheets("Import-Data").Cells(q, Col) = Application.WorksheetFunction.VLookup(TWB.Worksheets("Import-Data").Cells(q, 3).Value, _
Workbooks("CFNSPS03 - MICHELANGELO GRIGNI START-UP F" & SpecifiedDate & ".xls").Worksheets("Sheet1").Range("$E$11:$BI$200"), 57, False)
q = q + 1
Wend
Windows("CFNSPS03 - MICHELANGELO GRIGNI START-UP F" & SpecifiedDate & ".xls").Close (False)
'CFNSPS04 Data Transfer
Application.Workbooks.Open ("C:\Users\Chris Treeman\My Documents\Dept MathCS Financials\Accounting Files\Dept. Fund Tracking\Daily Compass Report Files\" & "CFNSPS04 - CLS J Taylor" & SpecifiedDate & ".xls")
While TWB.Worksheets("Import-Data").Cells(r, 3).Value <> "END"
On Error Resume Next
TWB.Worksheets("Import-Data").Cells(r, Col) = Application.WorksheetFunction.VLookup(TWB.Worksheets("Import-Data").Cells(r, 3).Value, _
Workbooks("CFNSPS04 - CLS J Taylor" & SpecifiedDate & ".xls").Worksheets("Sheet1").Range("$E$11:$BI$200"), 57, False)
r = r + 1
Wend
Windows("CFNSPS04 - CLS J Taylor" & SpecifiedDate & ".xls").Close (False)
'CFNSPS05 Data Transfer
Application.Workbooks.Open ("C:\Users\Chris Treeman\My Documents\Dept MathCS Financials\Accounting Files\Dept. Fund Tracking\Daily Compass Report Files\" & "CFNSPS05 - Equipment - Taylor" & SpecifiedDate & ".xls")
While TWB.Worksheets("Import-Data").Cells(s, 3).Value <> "END"
On Error Resume Next
TWB.Worksheets("Import-Data").Cells(s, Col) = Application.WorksheetFunction.VLookup(TWB.Worksheets("Import-Data").Cells(s, 3).Value, _
Workbooks("CFNSPS05 - Equipment - Taylor" & SpecifiedDate & ".xls").Worksheets("Sheet1").Range("$E$11:$BI$200"), 57, False)
s = s + 1
Wend
Windows("CFNSPS05 - Equipment - Taylor" & SpecifiedDate & ".xls").Close (False)
'CFNSPS06 Data Transfer
Application.Workbooks.Open ("C:\Users\Chris Treeman\My Documents\Dept MathCS Financials\Accounting Files\Dept. Fund Tracking\Daily Compass Report Files\" & "CFNSPS06 - SOM Equipment" & SpecifiedDate & ".xls")
While TWB.Worksheets("Import-Data").Cells(t, 3).Value <> "END"
On Error Resume Next
TWB.Worksheets("Import-Data").Cells(t, Col) = Application.WorksheetFunction.VLookup(TWB.Worksheets("Import-Data").Cells(t, 3).Value, _
Workbooks("CFNSPS06 - SOM Equipment" & SpecifiedDate & ".xls").Worksheets("Sheet1").Range("$E$11:$BI$200"), 57, False)
t = t + 1
Wend
Windows("CFNSPS06 - SOM Equipment" & SpecifiedDate & ".xls").Close (False)
'CFNSPS07 Data Transfer
Application.Workbooks.Open ("C:\Users\Chris Treeman\My Documents\Dept MathCS Financials\Accounting Files\Dept. Fund Tracking\Daily Compass Report Files\" & "CFNSPS07 - JACKSON MATH AND SCIENCE FUND" & SpecifiedDate & ".xls")
While TWB.Worksheets("Import-Data").Cells(u, 3).Value <> "END"
On Error Resume Next
TWB.Worksheets("Import-Data").Cells(u, Col) = Application.WorksheetFunction.VLookup(TWB.Worksheets("Import-Data").Cells(u, 3).Value, _
Workbooks("CFNSPS07 - JACKSON MATH AND SCIENCE FUND" & SpecifiedDate & ".xls").Worksheets("Sheet1").Range("$E$11:$BI$200"), 57, False)
u = u + 1
Wend
Windows("CFNSPS07 - JACKSON MATH AND SCIENCE FUND" & SpecifiedDate & ".xls").Close (False)
TWB.Sheets("Import-Data").Activate
Cells(6, CLoc).Select
TWB.Sheets("Dept. NSPs & SPPs").Activate
Application.Calculation = xlCalculationAutomatic
Columns(ActiveCell.Column).AutoFit
Else
MsgBox ("Please select the correct cell for Import")
End If
Application.ScreenUpdating = True
End Sub
</code></pre> | 1 |
Adobe AEM sidekick not showing components | <p>No components show up in my sidekick on one of my pages. I've enabled them on the designs tab and still no luck. I've also tried resizing window, inspect the dom to see if they are there and they aren't. Any ideas? </p> | 1 |
socket.io session does not update when req.session changes | <p>I am currently working on a basic app where a user needs to authenticate (with passportJS) and then send a message to my server with socket.io. Here is the nodeJS code:</p>
<pre><code>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressSession = require('express-session');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var routes = require('./routes/index');
var api = require('./api/index');
var auth = require('./routes/auth');
var session = expressSession({secret: 'mySecret', resave: true, saveUninitialized: true});
var port = normalizePort(process.env.PORT || '3000');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var sharedsession = require('express-socket.io-session');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.set('port', port);
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session);
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/bower_components', express.static(path.join(__dirname, 'bower_components')));
app.use('/', routes);
app.use('/api', api);
app.use('/auth', auth);
// passport config
var User = require('./models/user');
passport.use(new LocalStrategy({
usernameField: 'email'
}, User.authenticate()));
passport.use(require('./strategies/facebook'));
passport.use(require('./strategies/google'));
passport.serializeUser(function(user, done) {
done(null, { id: user._id });
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
io.use(sharedsession(session, {
autoSave:true
}));
io.on('connection', function(socket) {
console.log('user connected');
console.log(socket.handshake.session);
socket.on('message-new', function(data) {
console.log('receiving message to create');
console.log(socket.handshake.session);
});
socket.on('disconnect', function() {
console.log('user disconnected');
});
});
server.listen(port);
</code></pre>
<p>So as you can see I use express-socket.io-session to be able to access the session in my socket and it is supposed to be the same than req.session. So at first when a user is connected to the socket.io (but not authenticated), his socket.handshake.session is equal to req.session so:</p>
<pre><code>Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true } }
</code></pre>
<p>once he authenticates, req.session becomes:</p>
<pre><code>cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true },
passport: { user: { id: 56a13e58150f42fc29b44b7a } } }
</code></pre>
<p>but when I emit a message-new from the client and that it displays socket.handshake.session, it is still equals to </p>
<pre><code>Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true } }
</code></pre>
<p>So the socket's session was not updated when req.session was. How can I change this behavior? I need to be able to know in my socket if the user is connected or not...</p> | 1 |
Docker compose file ownership | <p>I created Django project with Docker Compose:</p>
<p>Dockerfile</p>
<pre><code>FROM python:2.7
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD . /code/
RUN pip install -r requirements.txt
WORKDIR /code/example
ENTRYPOINT ["python", "manage.py"]
</code></pre>
<p>docker-compose.yml</p>
<pre><code>postgres:
image: postgres
ports:
- '5432:5432'
django-project:
build: .
command: runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- '8000:8000'
links:
- postgres
</code></pre>
<p>It work nice.
But all new files which create through container 'django-project' have root owner and group.</p>
<p>I try add <code>user: user</code> in Compose config for container <code>django-project</code>.
But got exception <code>User user not found</code>.</p>
<p>I try add <code>user</code> in container with code:</p>
<pre><code>ENV HOME_USER user
ENV HOME_PASS password
RUN useradd -m -s /bin/bash ${HOME_USER} && \
echo "${HOME_USER}:${HOME_PASS}"|chpasswd && \
adduser ${HOME_USER} sudo && \
echo ${HOME_USER}' ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers
</code></pre>
<p>But exception stayed.</p>
<p>How I can apply non-root ownership for all new files which will create through docker container?</p> | 1 |
How to use Windows Runtime classes in .NET Core libraries? | <p>I'm developing a library for use with WPF and Windows 10. I'm running into issues getting it to compile on the latter. Here is some of the code:</p>
<p><strong>project.json</strong></p>
<pre><code>{
"frameworks": {
"net46": {
"frameworkAssemblies": {
"WindowsBase": "4.0.0.0"
}
},
"netcore50": {
"dependencies": {
"Microsoft.NETCore.UniversalWindowsPlatform": "5.0.0"
}
}
}
}
</code></pre>
<p><strong>Dependency.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
#if NET46
using System.Windows; // .NET Framework 4.6
#elif NETCORE50
using Windows.UI.Xaml; // Windows 10 apps
#endif
public static class Dependency
{
public static DependencyProperty Register<T, TOwner>(string name, PropertyChangedCallback<T, TOwner> callback)
where TOwner : DependencyObject
{
// Code here....
}
}
</code></pre>
<p>While this compiles fine for <code>net46</code> (which is the traditional .NET Framework), I'm having trouble getting it to work for <code>netcore50</code> (which can be used by Windows 10 apps). For some reason, it looks like types like <code>DependencyProperty</code> or <code>DependencyObject</code> are not included in that configuration.</p>
<p>Is there a <code>netcore50</code>-compatible NuGet package I can install that contains these types, so I can use them from my library?</p>
<p>Thanks for helping.</p>
<hr>
<p><strong>EDIT:</strong> I just typed in <code>DependencyProperty</code> in VS and hit F12. It appears that the type lives in the <strong>Windows.Foundation.UniversalApiContract</strong> assembly, but there's no such package on NuGet.</p> | 1 |
Is it possible to use sed to replace dependencies's version in a pom file? | <p>I have a <code>pom.xml</code> file and I want to replace the version inside any of the <code>dependency</code> nodes from <code>0.1-SNAPSHOT</code> to a different version (let's say <code>NEW-VERSION</code>), the only restriction I have is that the replacement should be done only if the <code>groupId</code> matches a particular text, lets say: <code>com.company.xyz</code>. </p>
<p>That being said, let's say this is the <code>dependencies</code> section of my <code>pom.xml</code>:</p>
<pre><code><dependencies>
<dependency>
<groupId>com.company.xyz</groupId>
<artifactId>xyz-xx-utils</artifactId>
<version>0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.ibm.xyz</groupId>
<artifactId>xyz</artifactId>
<version>56.1</version>
</dependency>
</dependencies>
</code></pre>
<p>After applying the sed command I want it to look like:</p>
<pre><code><dependencies>
<dependency>
<groupId>com.company.xyz</groupId>
<artifactId>xyz-xx-utils</artifactId>
<version>NEW-VERSION</version>
</dependency>
<dependency>
<groupId>com.ibm.xyz</groupId>
<artifactId>xyz</artifactId>
<version>56.1</version>
</dependency>
</dependencies>
</code></pre>
<p>Here is what I have tried without any success:</p>
<pre><code>newVersion="NEW-VERSION"
sed -i "s/\(<dependency>\)\(<groupId>com.company.xyz</groupId>\)\(<artifactId>.*\</artifactId>\)\(<version>0.1-SNAPSHOT</version>\)\(</dependency>\)/\1\2\3$newVersion\5/" pom.xml
</code></pre>
<p>I was wondering if the reason why this does not work is because my text has multiple lines, so I researched a little bit but I did not understand the syntax used to work with multiple lines (some <code>N</code> thing).</p>
<p>Btw, I am including this piece of code in a bash file that performs other operations, that is why I want to do this using sed or any other "tool" that is bash compatible.</p> | 1 |
koa.js streaming response from remote url | <p>I want to create a <code>koa</code> route that acts like a proxy for another url, which delivers a file that is usually a few dozens of Megabytes.</p>
<p>Therefore I would like not to block when making the response. I am using <code>this.body = yield request.get(url);</code> currently, where request is the <code>[co-request</code>]<a href="https://www.npmjs.com/package/co-request" rel="noreferrer">1</a> module.</p>
<p>How do I stream the response back to the client ?</p>
<p><em>Edit :</em> </p>
<p>I am now doing the following :</p>
<pre><code>var req = require('request');
//...
this.body = req(url).pipe(fs.createWriteStream(this.params.what));
</code></pre>
<p>If I paste the <code>url</code> in my browser, I get a file just fine.
However if I get a <code>Error: Cannot pipe. Not readable.</code> in my route.</p> | 1 |
Forbid scroll recyclerview if focus edittext | <p>I have a recycler view with horizontal scroll. Every item in recyclerview has edittext. When i click on edittext, recyclerview scroll to end. How i can forbid scrolling?
Thanks! </p> | 1 |
How to create a DOT file in Python? | <p>I have a digital circuit simulator and need to draw a circuit diagram almost exactly like in this question (and answer) <a href="https://stackoverflow.com/questions/7922960/block-diagram-layout-with-dot-graphviz">Block diagram layout with dot/graphviz</a></p>
<p>This is my first encounter with DOT and graphviz. Fortunately the DOT language specification is available and there are many examples as well.</p>
<p>However one detail is still unclear to me and I'm asking as a total newbie: I have a complete data to draw a graph. How do I create a DOT file from it?</p>
<p>As a text line by line?</p>
<pre><code># SIMPLIFIED PSEUDOCODE
dotlines = ["digraph CIRCUIT {"]
for node in all_nodes:
dotlines.append(" {}[{}];".format(node.name, node.data))
for edge in all_edges:
dotlines.append(" {} -> {};".format(edge.from_name, edge.to_name))
dotlines.append['}']
dot = "\n".join(dotlines)
</code></pre>
<p>Or should I convert my data somehow and use some module which exports it in the DOT format?</p> | 1 |
How to replace NAs with characters within a df | <p>I want all NAs to be replaced with "Not Found" in a df .</p>
<p>i have this df</p>
<pre><code>A B
1 NA
2 NA
3 NA
</code></pre>
<p>How can i get that .</p>
<pre><code>A B
1 Not Found
2 Not Found
3 Not Found
</code></pre> | 1 |
SQLite not updating table | <p>I'm learning database right now. I created an SQLite database. I've 6 EditText in my layout and when I click on "Save to DB" button the data gets saved to DB. And when I click on "Show" button, it displays the DB details in EditTexts. But the problem is, when I try to save different data in the same database, it doesn't gets updated with the new data and the "Show" button shows the old data only.</p>
<pre><code>public class FragmentFour extends Fragment {
EditText name_ET, website_ET, bio_ET, altEmail_ET, phone_ET, facebook_ET;
String name_str="", website_str="", bio_str="", altEmail_str="", phone_str="", facebook_str="";
Button save, show, clear;
private SQLiteHandler db;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_four, container, false);
db = new SQLiteHandler(getActivity());
name_ET = (EditText)rootView.findViewById(R.id.name);
website_ET = (EditText)rootView.findViewById(R.id.webiste);
bio_ET = (EditText)rootView.findViewById(R.id.bio);
altEmail_ET = (EditText)rootView.findViewById(R.id.altEmail);
phone_ET = (EditText)rootView.findViewById(R.id.phone);
facebook_ET = (EditText)rootView.findViewById(R.id.facebook);
save = (Button)rootView.findViewById(R.id.btn_save);
show = (Button)rootView.findViewById(R.id.btn_show);
clear = (Button)rootView.findViewById(R.id.btn_clr);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
name_str = name_ET.getText().toString();
website_str = website_ET.getText().toString();
bio_str = bio_ET.getText().toString();
altEmail_str = altEmail_ET.getText().toString();
phone_str = phone_ET.getText().toString();
facebook_str = facebook_ET.getText().toString();
db.addProfile(name_str, website_str, bio_str, altEmail_str, phone_str, facebook_str);
name_ET.setText("");
website_ET.setText("");
bio_ET.setText("");
altEmail_ET.setText("");
phone_ET.setText("");
facebook_ET.setText("");
}
});
show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HashMap<String, String> pro = db.getProfDetails();
String name = pro.get("name");
String website = pro.get("website");
String bio = pro.get("bio");
String email = pro.get("email");
String phone = pro.get("phone");
String facebook = pro.get("facebook");
name_ET.setText(name);
website_ET.setText(website);
bio_ET.setText(bio);
altEmail_ET.setText(email);
phone_ET.setText(phone);
facebook_ET.setText(facebook);
}
});
clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
name_ET.setText("");
website_ET.setText("");
bio_ET.setText("");
altEmail_ET.setText("");
phone_ET.setText("");
facebook_ET.setText("");
}
});
return rootView;
}
}
</code></pre>
<p>SQLite Database</p>
<pre><code>public class SQLiteHandler extends SQLiteOpenHelper {
private static final String TAG = SQLiteHandler.class.getSimpleName();
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "android_api";
// Profile Settings table name
private static final String TABLE_PROF = "prof";
// Profile Settings information names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_WEBSITE = "website";
private static final String KEY_BIO = "bio";
private static final String KEY_ALT_EMAIL = "alt_email";
private static final String KEY_PHONE = "phone";
private static final String KEY_FACEBOOK = "facebook";
public SQLiteHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_PROF_TABLE = "CREATE TABLE " + TABLE_PROF + "("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_NAME+" TEXT, "+KEY_WEBSITE+" TEXT, "+KEY_BIO+" TEXT, "+KEY_ALT_EMAIL+" TEXT, "+KEY_PHONE+" TEXT, "+KEY_FACEBOOK+" TEXT" + ")";
db.execSQL(CREATE_PROF_TABLE);
Log.d(TAG, "Database tables created");
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PROF);
// Create tables again
onCreate(db);
}
/**
* Storing Prof_settings details in database
* */
public void addProfile(String name, String website, String bio, String alt_email, String phone, String facebook){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name);
values.put(KEY_WEBSITE, website);
values.put(KEY_BIO, bio);
values.put(KEY_ALT_EMAIL, alt_email);
values.put(KEY_PHONE, phone);
values.put(KEY_FACEBOOK, facebook);
// Inserting Row
long id = db.insert(TABLE_PROF, null, values);
db.close(); // Closing database connection
Log.d(TAG, "New profile settings inserted into sqlite: " + id);
}
/**
* Getting Profile Settings data from database
* */
public HashMap<String, String> getProfDetails() {
HashMap<String, String> pro = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_PROF;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
pro.put("name", cursor.getString(1));
pro.put("website", cursor.getString(2));
pro.put("bio", cursor.getString(3));
pro.put("email", cursor.getString(4));
pro.put("phone", cursor.getString(5));
pro.put("facebook", cursor.getString(6));
}
cursor.close();
db.close();
// return log details
Log.d(TAG, "Fetching profile details from Sqlite: " + pro.toString());
return pro;
}
/**
* Re crate database Delete all tables and create them again
* */
public void deleteUsers() {
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_PROF, null, null);
db.close();
Log.d(TAG, "Deleted all profile info from sqlite");
}
}
</code></pre> | 1 |
How could I fix the unquoted nan value in JSON using Python | <p>An external C routine called in a Python script returns a "big" and "deep" JSON that contains here and there a few unquoted <code>nan</code> values for certain keys.</p>
<p>Because of these values, the JSON appears as invalid and it can't be sent over a websocket for instance.</p>
<p>e.g.</p>
<pre><code>{'myKey': nan}
</code></pre>
<p><strong>How could fix this JSON without having to check exhaustively each value?</strong> Fixing the source generating the JSON is not an option. I need to fix the JSON before I send it over the websocket.</p>
<p>Is there a way that I could substitute the unquoted <code>nan</code> by something that wouldn't cause an error when I try to <code>emit</code> via WebSocket.</p>
<p>Alternatively, Is there a way to configure <a href="https://python-socketio.readthedocs.org/en/latest/" rel="nofollow"><code>python-socket.io</code></a> to allow these unquoted <code>nan</code> values? My current research, says it can't.</p>
<h2>AN IDEA (?)</h2>
<p>I am thinking, I could stringify, replace the <code>nan</code> string by something that works, and JSONify again. </p>
<p>But what could I replace the unquoted <code>nan</code> with?</p>
<h2>UPDATE</h2>
<p><code>json.dumps</code> to convert to string</p>
<p><code>replace("nan", "'nan'")</code> or better, use @Jaco answer</p>
<p><code>json.loads</code> to create the JSON obj</p> | 1 |
Google Places Autocomplete, how to deal with Unit number in the address | <p>I'm using <a href="https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete" rel="nofollow">Google Place Autocomplete</a> to allow user to provide address and it works mostly fine for basic addresses e.g. </p>
<pre><code>Some st Ashfield NSW 2019
</code></pre>
<p>But it doesn't work when someone provides additional info like unit number e.g.:</p>
<pre><code>Unit 2/42, Some st Ashfield NSW 2019
</code></pre>
<p>What would be the best way to deal with this kind of address given that Unit might be Apartment and in all different formats. Some crazy regex or is there any setting in Google Autocomplete I missed? Or just provide additional field for Unit/Appartment/everything else is the only option?</p> | 1 |
Altering a Postgres integer column to type boolean | <p>I've recently been optimizing some of our Postgres tables by converting more complex data types to simpler ones where possible. In every case except one so far, this has been fairly straightforward, for instance:</p>
<p><code>ALTER TABLE products ALTER COLUMN price TYPE integer USING price::integer;</code></p>
<p>For converting text into custom enumerated data types, this has also been simple enough. I just wrote a PLPGSQL function that would convert text to the enum, then converted the column like so:</p>
<p><code>ALTER TABLE products ALTER COLUMN color TYPE color_enum USING text_to_color_enum(color);</code></p>
<p>This syntax fails though, in cases where I have to convert an integer to a boolean. These all fail:</p>
<p><code>ALTER TABLE products ALTER return_policy TYPE boolean USING return_policy > 0;</code></p>
<p><code>ALTER TABLE products ALTER return_policy TYPE boolean USING bool(return_policy);</code></p>
<p><code>ALTER TABLE products ALTER COLUMN return_policy TYPE boolean USING bool(return_policy);</code></p>
<p><code>ALTER TABLE products ALTER COLUMN return_policy TYPE boolean USING CASE WHEN return_policy <> 0 THEN TRUE ELSE FALSE END;</code></p>
<p>The error message is always the same:</p>
<p><code>ERROR: operator does not exist: boolean = integer</code></p>
<p><code>HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.</code></p>
<p>There are no null values in that column. All values are either zero or positive. <code>SELECT pg_typeof(return_policy) FROM products LIMIT 1;</code> returns <code>integer</code>. Creating a custom cast from integer to boolean fails, because apparently one already exists. The same thing happen in Postgres 9.4 and 9.5. What am I doing wrong here?</p> | 1 |
Replacing vue.js template with setInterval | <p>I've been trying to refresh the content of a div at a given interval using vue.js, but up until now have had little if no success. Here's what I have at this point:</p>
<pre><code>var vm = new Vue({
el: '#feature',
template: '<div id={{content}}></div>',
data:
featureList: [{
content: 'a'
}, {
content: 'b'
}, {
content: 'c'
}]
}
});
</code></pre>
<p>On my html, I've the following:</p>
<pre><code><div id="feature"></div>
</code></pre>
<p>My approach here is to iterate through this array and replace <em>content</em> in the template at a given interval. The problem is that I'm not sure how to do it. </p>
<p>This is what I tried as an alternative to having an array in <em>data</em>: making <em>content</em> a computed property with a setter function, with a single string in <em>data</em>. Like this: </p>
<pre><code>var vm = new Vue({
el: '#feature',
template: '<div id={{content}}></div>',
data: {
content: 'a'
},
computed: {
setTemplate: {
set: function(newValue) {
var values= newValue
this.content = values
}
}
}
});
vm.setTemplate = 'c'
</code></pre>
<p>(jsfiddle <a href="http://jsfiddle.net/pierrebonbon/0r6cf4uf/15/" rel="nofollow">here</a>)</p>
<p>Now, how do I go from here? How do I change <em>content</em> at a certain interval from a set of given strings?</p> | 1 |
Running executable application on Chrome? | <p>Is it possible to run executable .exe application on Chrome browser or what option do I have?</p>
<p>I have seen example of JavaScript and it is desgined to work on IE because it use <code>WScript.Shell</code> (Not tested)</p>
<pre><code>var ws = new ActiveXObject("WScript.Shell");
ws.run("C:\\System\\Display\\Display.exe \"" + message1 + "\" \"" + message2 + "\"");
</code></pre>
<p>So basically javascript it will execute <code>Display.exe <Message></code></p>
<p>Display.exe connect to COM3 (serial port) to display price on the Customer Display Pole (Till system)</p> | 1 |
onCreateOptionsMenu() is not getting called on FragmentActivity | <p>Colleagues, <code>MainActivity</code> class is derived from <code>FragmentActivity</code>, and for some reason activity's <code>onCreateOptionsMenu()</code> is not getting called. I have the first breakpoint in <code>onCreate()</code>, which is getting triggered, and the second one in <code>onCreateOptionsMenu()</code>, which is not getting triggered.</p>
<pre><code>import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
private FragmentPagerAdapter m_fragmentPagerAdapter;
private ViewPager m_viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the primary sections of the activity.
m_fragmentPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
m_viewPager = (ViewPager) findViewById(R.id.container);
m_viewPager.setAdapter(m_fragmentPagerAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu); // Inflate the menu; this adds items to the action bar if it is present.
return true;
}
}
</code></pre>
<p>Fragments in this app don't have their own menus. One menu belonging to the activity "covers" everything.</p>
<p>Theme is Holo.Light</p>
<p>What prevent <code>onCreateOptionsMenu()</code> from getting called? What am I missing?</p> | 1 |
How to load an assembly as reflection-only in a new AppDomain? | <p>I'm experienced in C# but relatively unfamiliar with the concepts of <code>AppDomain</code> and the like. Anyway, I'm trying to get an assembly to load in a reflection-only context so I can grab all of its namespaces. Here is the code I have right now (warning: PowerShell):</p>
<pre><code>function Get-Namespaces($assembly)
{
$assemblyClass = [Reflection.Assembly]
$winmdClass = [Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata]
$domain = [AppDomain]::CurrentDomain
# Since desktop .NET can't work with winmd files,
# we have to use the reflection-only APIs and preload
# all the dependencies manually.
$appDomainHandler =
{
Param($sender, $e);
$assemblyClass::ReflectionOnlyLoad($e.Name)
}
$winmdHandler =
{
Param($sender, $e)
[string[]] $empty = @()
$path = $winmdClass::ResolveNamespace($e.NamespaceName, $empty) | select -Index 0
$e.ResolvedAssemblies.Add($assemblyClass::ReflectionOnlyLoadFrom($path))
}
# Hook up the handlers
$domain.add_ReflectionOnlyAssemblyResolve($appDomainHandler)
$winmdClass::add_ReflectionOnlyNamespaceResolve($winmdHandler)
# Do the actual work
$assemblyObject = $assemblyClass::ReflectionOnlyLoadFrom($assembly)
$types = $assemblyObject.GetTypes()
$namespaces = $types | ? IsPublic | select Namespace -Unique
# Deregister the handlers
$domain.remove_ReflectionOnlyAssemblyResolve($appDomainHandler)
$winmdClass::remove_ReflectionOnlyNamespaceResolve($winmdHandler)
return $namespaces
}
</code></pre>
<p>For some reason, when I'm running the function on assemblies like <code>System.Xaml</code> or <code>WindowsBase</code> I'm getting these errors:</p>
<pre>Exception calling "ReflectionOnlyLoadFrom" with "1" argument(s): "API restriction:
The assembly 'file:///C:\Program Files (x86)\Reference Assemblies\Microsoft\
Framework\.NETFramework\v4.6.1\System.Xaml.dll' has already loaded from a
different location. It cannot be loaded from a new location within the same
appdomain."
At C:\Users\James\Code\csharp\Shims.Xaml\generate.ps1:50 char:5
+ $assemblyObject = $assemblyClass::ReflectionOnlyLoadFrom($assembl ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FileLoadException</pre>
<p>So what I'd like to know is, how can I load the assembly in a new AppDomain? I checked <a href="https://msdn.microsoft.com/en-us/library/25y1ya39(v=vs.110).aspx" rel="nofollow">MSDN</a> but all I can find are methods like <code>CreateInstanceAndUnwrap</code>, which I can't/don't want to do since this is reflection-only.</p>
<p><strong>TL;DR:</strong> How can I load assemblies in a reflection-only context in a new AppDomain? Both C# and PowerShell code samples welcome.</p>
<hr>
<p><strong>EDIT:</strong> <a href="https://gist.github.com/jamesqo/a1c737b4cfe9b0341ab4" rel="nofollow">Here</a> is a GitHub gist of the script I've made, so others can repro the error/test changes.</p> | 1 |
Is it possible to use python to establish a putty ssh session and send some input? | <p>Fist of all, due to Company Policy, Paramiko, or installing anything that requires administrative access to local machine it right out; otherwise I would have just done that.</p>
<p>All I have to work with is python with standard libraries & putty.</p>
<p>I am attempting to automate some tedious work that involves logging into a network device (usually Cisco, occasionally Alcatel-Lucent, or Juniper), running some show commands, and saving the data. (I am planning on using some other scripts to pull data from this file, parse it, and do other things, but that should be irrelevant to the task of retrieving the data.) I know this can be done with telnet, however I need to do this via ssh.</p>
<p>My thought is to use putty's logging ability to record output from a session to a file. I would like to use Python to establish a putty session, send scripted log-in and show commands, and then close the session. Before I set out on this crusade, does anyone know of any way to do this? The closest answers I have found to this all suggest to use Paramiko, or other python ssh library; I am looking for a way to do this given the constraints I am under.</p>
<p>The end-result would ideal be able to be used as a function, so that I can iterate through hundreds of devices from a list of ip addresses.</p>
<p>Thank you for your time and consideration.</p> | 1 |
DB query is returning undefined value in node.js with oracledb | <p>i am new to node.js and javascript and trying to learn the things. in my tests i need to pick a value from Oracle DB through select query and need to use it in to my code later. i am referring the same code given on <a href="https://blogs.oracle.com/opal/entry/introducing_node_oracledb_a_node" rel="nofollow">https://blogs.oracle.com/opal/entry/introducing_node_oracledb_a_node</a> and it is working fine but am not able to return the result value.</p>
<p>below is my code :</p>
<pre><code>this.getTableData = function(){
var res;
oracledb.getConnection(
{
user : "user",
password : "password",
connectString : "db "
},
function (err, connection) {
if (err) {
console.error(err);
console.log("errorrrrrrrrrrr : "+err);
return;
}
connection.execute("SELECT query",
function(err, result) {
if (err) {
console.error(err);
return;
}
else if(result) {
res = result.rows[0][0];
console.log("result in else if: "+res);
return res;
}});
});
};
</code></pre>
<p>the function returns undefined value.</p> | 1 |
Sonata admin file uploads : Upload files apart from the admin panel | <p>I have a Symfony 2.8 based project, I have Sonata admin bundle and Sonata user bundle well installed and all is working good.</p>
<p>I have an "Image" entity that it meant to contain my uploaded file. I followed the official Sonata tutorial to how to upload a file (<a href="https://sonata-project.org/bundles/admin/master/doc/cookbook/recipe_file_uploads.html" rel="nofollow">https://sonata-project.org/bundles/admin/master/doc/cookbook/recipe_file_uploads.html</a>) and all is working perfectly when I want to upload a file from the admin panel.</p>
<p>Now, I need a to offer the possibility to a simple connected user (not admin) to upload a file as well from a form.</p>
<p>Here's the example I have:</p>
<p>I have this "Offer" class that has an "Image" attribute:</p>
<pre><code>class Offer {
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* @var string
*
* @ORM\Column(name="body", type="text")
*/
private $body;
/**
* @var \DateTime
*
* @ORM\Column(name="date", type="datetime")
*/
private $date;
/**
* @ORM\OneToOne(targetEntity="AIEM\PlatformBundle\Entity\Image", cascade={"all"})
*/
private $image;
//Getters and Setters
}
</code></pre>
<p>Before adding the "Image" entity, I persisted an offer using the classic way : Getting my data from the request (example : <code>$offer->setTitre($request->request->get('title'));</code>). But now since I have a OneToMany with a file, I don't know how to proceed.</p>
<p>I'll be grateful if you can share some ideas.</p>
<p><strong>EDIT</strong>
Here's my OfferAdmin, and it's working perfectly in sonata admin</p>
<pre><code>class OfferAdmin extends Admin {
protected function configureFormFields(FormMapper $formMapper) {
$formMapper->add('title', 'text')
->add('image', 'sonata_type_admin')
->add('body', 'textarea', array("attr" => array("class" => "ckeditor")));
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper) {
$datagridMapper->add('titre')
->add('date');
}
protected function configureListFields(ListMapper $listMapper) {
$listMapper->addIdentifier('titre');
}
public function prePersist($page) {
$this->manageEmbeddedImageAdmins($page);
}
public function preUpdate($page) {
$this->manageEmbeddedImageAdmins($page);
}
private function manageEmbeddedImageAdmins($page) {
/** @var Image $image */
$image = $page->getImage();
if ($image) {
if ($image->getFile()) {
// update the Image to trigger file management
$image->refreshUpdated();
} elseif (!$image->getFile() && !$image->getFilename()) {
// prevent Sf/Sonata trying to create and persist an empty Image
$page->$setImage(null);
}
}
}
}
</code></pre>
<p>And the form I want the user to add the file from looks like this</p>
<pre><code><form method="post" action="{{ path('aiem_platform_add_offer')}}">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Title">
</div>
<div class="form-group">
<input type="file" class="form-control" id="myFile" name="myFile">
</div>
<div class="form-group">
<label for="contenu">Contenu</label>
<textarea class="form-control ckeditor" id="body" name="body"></textarea>
</div>
<button type="submit" class="btn btn-default">Add</button>
</form>
</code></pre>
<p>Thank you</p> | 1 |
Common table expression (CTE) in table-valued function | <p>I am used to using common table expressions (CTEs) with MSSQL 2008 R2. I know that the grammar is a bit fiddly about where they can appear, and that in ordinary T-SQL an explicit semicolon (or starting a new batch) is needed before a <code>with</code> expression. I would like to use CTEs in a user-defined function. For simple cases, this works:</p>
<pre><code>create function dbo.udf_test()
returns table
with schemabinding
as
return (
with foo as (
select 5 as f
)
select f
from foo
)
</code></pre>
<p>But now I would like to make my function <code>udf_test</code> a bit more elaborate. For example to declare a variable inside the body of the function. To start with I need to have explicit <code>begin</code> and <code>end</code> since the function body will no longer be a single statement. So I try to create one thus:</p>
<pre><code>create function dbo.udf_test()
returns table
with schemabinding
as
begin
return (
with foo as (
select 5 as f
)
select f
from foo
)
end
</code></pre>
<p>However this gives the error</p>
<pre><code>Incorrect syntax near the keyword 'with'.
</code></pre>
<p>How can I use a CTE in my table-valued function if it is more complex than a single <code>return</code> statement?</p> | 1 |
java.lang.ClassCastException: org.apache.xerces.jaxp.DocumentBuilderFactoryImpl cannot be cast to javax.xml.parsers.DocumentBuilderFactory | <p>I am using <code>java1.6</code>,<code>jboss5.1</code> and <code>Spring</code> maven <code>3.2.5</code> in my project.I am getting </p>
<blockquote>
<p>java.lang.ClassCastException: org.apache.xerces.jaxp.DocumentBuilderFactoryImpl cannot be cast to javax.xml.parsers.DocumentBuilderFactory</p>
</blockquote>
<p>This is my 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>com.varun.batch</groupId>
<artifactId>myproject</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>myproject Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- Spring ORM support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<!-- Spring Batch -->
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-infrastructure</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-transport-local</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-transport-http</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>3.1.0.CR2</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.3.1.ga</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.3.0.CR2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>3.3.0.CR2</version>
<exclusions>
<exclusion>
<artifactId>jboss-logging</artifactId>
<groupId>org.jboss.logging</groupId>
</exclusion>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.1</version>
</dependency>
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>stax</groupId>
<artifactId>stax-api</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-kernel</artifactId>
<version>1.6.1</version>
<exclusions>
<exclusion>
<artifactId>servlet-api</artifactId>
<groupId>javax.servlet</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-api</artifactId>
<version>1.2.12</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-activation_1.1_spec</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-javamail_1.4_spec</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.1</version>
<exclusions>
<exclusion>
<artifactId>xercesImpl</artifactId>
<groupId>xerces</groupId>
</exclusion>
<exclusion>
<artifactId>xml-apis</artifactId>
<groupId>xml-apis</groupId>
</exclusion>
<exclusion>
<artifactId>xmlParserAPIs</artifactId>
<groupId>xerces</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-stax-api_1.0_spec</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-ws-metadata_2.0_spec</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-impl</artifactId>
<version>1.2.12</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>wstx-asl</artifactId>
<version>3.2.9</version>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jta_1.1_spec</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.ws.commons.schema</groupId>
<artifactId>XmlSchema</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>com.javaetmoi.core</groupId>
<artifactId>javaetmoi-spring4-vfs2-support</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.13.RELEASE</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc5</artifactId>
<version>11.2.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.11</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>logkit</groupId>
<artifactId>logkit</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>1.7.11</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.18.1-GA</version>
</dependency>
<dependency>
<groupId>javax.batch</groupId>
<artifactId>javax.batch-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.3.0.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-wsdl2code-maven-plugin</artifactId>
<version>1.6.2</version>
<executions>
<execution>
<goals>
<goal>wsdl2code</goal>
</goals>
<configuration>
<unpackClasses>true</unpackClasses>
<packageName>com.globalss.data.processor.service</packageName>
<wsdlFile>src/main/resources/wsdl/MonitoringService.wsdl</wsdlFile>
<databindingName>xmlbeans</databindingName>
<syncMode>sync</syncMode>
<generateServerSide>true</generateServerSide>
<generateServicesXml>true</generateServicesXml>
<generateServerSideInterface>true</generateServerSideInterface>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>true</overWriteSnapshots>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>target/generated-sources/axis2/wsdl2code/resources</directory>
</resource>
<resource>
<directory>target/generated-sources/xmlbeans/resources</directory>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/java/com/globalss/dnb/monitor/model/</directory>
<targetPath>com/globalss/dnb/monitor/model/</targetPath>
<includes>
<include>*.hbm.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
</code></pre>
<p>I tried multiple solutions,but could not resolve it.</p>
<p><strong>1st method)</strong>
In jboss-5.1.0.GA\lib\endorsed folder I have this jar<code>(xercesImpl)</code>.
so I removed that jar, and run the project.</p>
<p><em>Now I get this exception</em></p>
<blockquote>
<p>xception sending context initialized event to listener instance of
class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanDefinitionStoreException:
Unexpected exception parsing XML document from class path resource
[spring-batch-context.xml]; nested exception is
javax.xml.parsers.FactoryConfigurationError: Provider for
javax.xml.parsers.DocumentBuilderFactory cannot be found</p>
</blockquote>
<p><strong>2nd) method</strong>
I tried commented the bellow dependency from pom.xml</p>
<pre><code><dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.1</version>
<exclusions>
<exclusion>
<artifactId>xercesImpl</artifactId>
<groupId>xerces</groupId>
</exclusion>
<exclusion>
<artifactId>xml-apis</artifactId>
<groupId>xml-apis</groupId>
</exclusion>
<exclusion>
<artifactId>xmlParserAPIs</artifactId>
<groupId>xerces</groupId>
</exclusion>
</exclusions>
</dependency>
</code></pre>
<p>But I get the same exception</p>
<blockquote>
<p>org.springframework.beans.factory.BeanDefinitionStoreException:
Unexpected exception parsing XML document from class path resource
[spring-batch-context.xml]; nested exception is
java.lang.ClassCastException:
org.apache.xerces.jaxp.DocumentBuilderFactoryImpl cannot be cast to
javax.xml.parsers.DocumentBuilderFactory at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:413)</p>
</blockquote>
<p><strong>3rd) Method</strong>
I saw some solution regarding the same problem and the solution says to add the bellow dependency</p>
<pre><code><dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.11.0</version>
</dependency>
</code></pre>
<p>After adding the above dependency in my pom.xml
I get this exception</p>
<blockquote>
<p>org.jboss.xb.binding.JBossXBRuntimeException: Failed to create a new
SAX parser at
org.jboss.xb.binding.UnmarshallerFactory$UnmarshallerFactoryImpl.newUnmarshaller(UnmarshallerFactory.java:100)
at
org.jboss.web.tomcat.service.deployers.JBossContextConfig.processContextConfig(JBossContextConfig.java:549)
at
org.jboss.web.tomcat.service.deployers.JBossContextConfig.init(JBossContextConfig.java:536)
at
org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:279)
at
org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at
org.apache.catalina.core.StandardContext.init(StandardContext.java:5436)
at
org.apache.catalina.core.StandardContext.start(StandardContext.java:4148)</p>
</blockquote>
<p><strong>4th) method</strong>
I tried deleting this jar also
<a href="https://i.stack.imgur.com/AYsyR.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/AYsyR.jpg" alt="enter image description here"></a></p>
<p>This also dint work for me.</p>
<p>I am damn frustrated with this exception, but I am not able to fix this,</p>
<p>This link is really good and it address the same problem, but still I am not able to fix this can any one help me this.
<a href="https://stackoverflow.com/questions/11677572/dealing-with-xerces-hell-in-java-maven">Dealing with "Xerces hell" in Java/Maven?</a></p>
<p><strong>Edited</strong> </p>
<p>I have found out the root cause.
This is snapshot from <code>Jboss 5.1 Run-time</code></p>
<p><a href="https://i.stack.imgur.com/1OTha.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/1OTha.jpg" alt="enter image description here"></a></p>
<p>This is the snapshot from <code>Maven dependency</code>
<a href="https://i.stack.imgur.com/eauhd.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/eauhd.jpg" alt="enter image description here"></a></p>
<p>So this two jars are conflicting.</p>
<p>So What I did. After building the project I removed the<code>(xml-api1.0.b2.jar)</code> from <code>Myproject.war</code> and manually deployed the project in <code>Jboos</code>, and jboss does not throw error.</p>
<p>But When I do not remove the <code>(xml-api1.0.b2.jar)</code> from <code>myproject.war</code> and deployed in jboss it throws the same error.</p>
<p><strong>So I have to remove the dependency from <code>pom.xml</code>.</strong></p>
<p>for <code>(xml-api1.0.b2.jar)</code> I have defined the bellow dependency </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.1</version>
<exclusions>
<exclusion>
<artifactId>xercesImpl</artifactId>
<groupId>xerces</groupId>
</exclusion>
<exclusion>
<artifactId>xml-apis</artifactId>
<groupId>xml-apis</groupId>
</exclusion>
<exclusion>
<artifactId>xmlParserAPIs</artifactId>
<groupId>xerces</groupId>
</exclusion>
</exclusions>
</dependency> </code></pre>
</div>
</div>
</p>
<p>But when I comment this dependency from my <code>pom.xml</code> Still I get the jar in Maven dependency as I have shown in the image.</p>
<p><strong>I am really not getting from where this <code>(xml-api1.0.b2.jar)</code> is cumming.</strong> can any one let me by looking my <code>pom.xml</code>.</p> | 1 |
(android.support.v4.widget.DrawerLayout$DrawerListener)' on a null object reference | <p>Can you help me about this error on my logcat?
<a href="http://pastebin.com/uSXruD54" rel="nofollow noreferrer">http://pastebin.com/uSXruD54</a> </p>
<p>Where: </p>
<pre><code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.setDrawerListener(android.support.v4.widget.DrawerLayout$DrawerListener)' on a null object reference
</code></pre>
<p>on my Home class at line 79 which is: </p>
<pre><code>drawer.setDrawerListener(toggle);
</code></pre>
<p><a href="http://pastebin.com/cixZ7d9d" rel="nofollow noreferrer">http://pastebin.com/cixZ7d9d</a> (MainActivity class, line 48)</p>
<p>I don't have any idea how setDrawerListener works sorry, I found the same problem here on stackoverflow: <a href="https://stackoverflow.com/questions/31500963/how-to-rectify-nullpointerexception-in-v4-drawerlayout">How to rectify NullPointerException in v4.DrawerLayout?</a></p>
<p>The answer says that it has to make sure that I'm using the same id for nav drawer and in layout file but I didn't made any changes on nav drawer because it's the activity itself that I chose in Android Studio, I just implemented tabs on it.</p> | 1 |
position a child <div> inside a fixed positioned parent <div> | <p>So I'm trying to build a modal window (with a white background) with HTML/CSS and I want the modal window itself to be fixed positioned relative to the browser window. In addition, the modal contains a child img at the top and a child div at the bottom that will contain some description text in it. My purpose is to position the child div relative to the parent fixed modal window so that the child div has a left offset of about 8.33% of the width of the parent.</p>
<p>So initially I thought I should absolute position the child div, but once I do that the background of the parent modal windows does not extend to the child div:
<a href="https://i.stack.imgur.com/6SDHW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6SDHW.jpg" alt="enter image description here" /></a></p>
<p>here is the html/css for the above:
html:</p>
<pre><code><div class="modal col-4 l-offset-4" id="robot-modal">
<img src="media/robot_modal.jpg">
<div class="col-10 l-offset-1">
</div>
</div>
</code></pre>
<p>css:</p>
<pre><code>.col-10 {
width: 83.33333%;
}
.l-offset-1 {
left: 8.33333%;
}
.modal {
@include align-vertically(fixed);
display: none;
z-index: 2000;
background: white;
img {
width: 100%;
}
div{
position: absolute;
background-color: blue;
height: 100px;
}
}
</code></pre>
<p>But when I change the child div's position to 'relative', then the correct background will show up:</p>
<p><a href="https://i.stack.imgur.com/SMisG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SMisG.jpg" alt="enter image description here" /></a></p>
<p>I don't get the intuition why I should always relative position an element inside a fixed parent. Wouldn't positioning an element as relative make it impossible to adjust offset relative to its parent ? According to this article: <a href="http://www.webdevdoor.com/html-css/css-position-child-div-parent" rel="nofollow noreferrer">http://www.webdevdoor.com/html-css/css-position-child-div-parent</a> , if we want to position an element relative to its immediate parent, the parent better be absolute or relative positioned and the child must be absolute positioned. So in my case why does adjusting the offset of a relative positioned child also work? I don't want to assign a height to the parent modal. i want it to automatically enlarge itself when new elements are contained in it.</p> | 1 |
How to rename key/header in csv DictReader | <p>For instance given <code>mycsv.csv</code> file</p>
<pre><code>h1,h2
a,b
c,d
</code></pre>
<p>how to rename <code>h2</code> onto <code>HTwo</code> with <code>reader</code> </p>
<pre><code>reader = csv.DictReader(open('mycsv.csv'))
</code></pre>
<p>(Additionally how to write the csv file back with the updated header.)</p>
<p><strong>Note</strong> approaches with awk are also valued.</p> | 1 |
Using ProcessBuilder with argument list as single String | <p>I try to switch from <code>Runtime.exec(command)</code> to <code>ProcessBuilder</code> for executing ImageMagick's <code>convert</code> from a Java programm. The options for convert are passed-in from the user as a String, so I cannot easily separate the arguments to pass them indvidually to <code>ProcessBuilder</code>'s constructor. The actual command that works on the (Unix) commandline is</p>
<pre><code>convert -colorspace gray -enhance -density 300 in.pdf out.pdf
</code></pre>
<p>How can I get this could to work:</p>
<pre><code>public class Demo {
public static void main(String[] args) throws IOException, InterruptedException {
String convertOptions = "-colorspace gray -enhance -density 300"; // arguments passed in at runtime
ProcessBuilder bp = new ProcessBuilder(new String []{"convert",convertOptions,"in.pdf","out.pdf"});
Process process = bp.start();
process.waitFor();
}
}
</code></pre>
<p>Currently, the code justs run</p> | 1 |
What does an asterisk in a scanf format specifier mean? | <p>So I stumbled across this code and I haven't been able to figure out what the purpose of it is, or how it works:</p>
<pre><code>int word_count;
scanf("%d%*c", &word_count);
</code></pre>
<p>My first thought was that <code>%*d</code> was referencing a <code>char</code> pointer or disallowing <code>word_count</code> from taking <code>char</code> variables. </p>
<p>Can someone please shed some light on this? </p> | 1 |
version control for binary files | <p>I'm in the process of writing a program that will use its own binary format for storing data. </p>
<p>I would like to make possible to have some form of version control, at the very least two different people should be able to make changes on a file and after that merge this changes. </p>
<p>As git seems to be a very common and very powerful version control system, I am wondering if it is possible to use it. I have only basic knowledge of git (pull add commit push), but I understand it has more advanced features. I want to understand if I can implement some basic functionality and get all the advanced features for free. </p>
<p>So the use case is that each project would consist of a sole binary file, and git would have to be able to work with it.</p>
<p>I've been searching and got to understand that I would have to write a custom mergetool ? Is my understanding correct? </p>
<p>I also understand that a three-way merge is done by a diff3 program or at least that git has some of it functionality embedded. Would I have to write a custom version of it? Would it be even possible to use it with git? Would it be necessary to recompile git? </p>
<p>git also stores commits as changes in order to save space. Does it use diff for it? Would be possible to replace it? Would git need to be recompiled?<br>
Is there any other kind of functionality that I would have to implement?<br>
My initial plan was to use a single file for the project, but each project is made of independent sub-projects, that would be merged independently. Would I gain anything by storing the project as different files for each subproject? </p>
<p>Is there anywhere some good documentation on to what interface a diff , diff3 and mergetool must conform? In which languages could these be written? </p>
<p>I'm quite confused because everyone seems to be interested in eliminating binary files from version control and apparently nobody wants to use git on them. Is it a bad idea? I feel like any kind of data for which merging makes sense in some way should be version controlled.</p> | 1 |
Not able to run as Exception in Application start method | <p>I am using Netbeans IDE and created that file using Scene Builder 2.0. I created all the user interface using Scene Builder.</p>
<p>When I try to run the application this exception comes. I created JavaFX FXML application in Netbeans IDE and opened the fxml in scene builder and edited and after completion ran it in Netbeans but failed to get the desired screen.</p>
<p><strong>ERROR:</strong></p>
<pre><code>Executing C:\J_Progs\Login\dist\run1115386562\Login.jar using platform C:\Program Files\Java\jdk1.8.0_66\jre/bin/java
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)
Caused by: javafx.fxml.LoadException:
file:/C:/J_Progs/Login/dist/run1115386562/Login.jar!/login/Login.fxml:35
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at login.Login.start(Login.java:23)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more
Caused by: java.lang.IllegalArgumentException: Can not set javafx.scene.control.Label field login.LoginController.txtUser to javafx.scene.control.TextField
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
at java.lang.reflect.Field.set(Field.java:764)
at javafx.fxml.FXMLLoader.injectFields(FXMLLoader.java:1163)
at javafx.fxml.FXMLLoader.access$1600(FXMLLoader.java:103)
at javafx.fxml.FXMLLoader$ValueElement.processValue(FXMLLoader.java:857)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:751)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
... 17 more
Exception running application login.Login
</code></pre>
<p><strong>Login.fxml</strong>:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.shape.*?>
<?import javafx.scene.effect.*?>
<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="600.0" prefWidth="650.0" style="-fx-background-color: #DCDCDC;" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="login.LoginController">
<children>
<Label fx:id="lblMsg" layoutX="47.0" layoutY="39.0" text="WELCOME" textAlignment="CENTER">
<font>
<Font name="System Bold" size="40.0" />
</font>
</Label>
<Label layoutX="271.0" layoutY="229.0" text="SIGN IN">
<font>
<Font name="System Bold" size="24.0" />
</font>
</Label>
<Label layoutX="130.0" layoutY="300.0" text="USERNAME">
<font>
<Font size="15.0" />
</font>
</Label>
<Label layoutX="129.0" layoutY="379.0" text="PASSWORD">
<font>
<Font size="15.0" />
</font>
</Label>
<TextField fx:id="txtUser" layoutX="265.0" layoutY="298.0" prefHeight="25.0" prefWidth="235.0" promptText="Enter Username" />
<Button layoutX="289.0" layoutY="481.0" mnemonicParsing="false" onAction="#loginAction" opacity="0.84" style="-fx-background-color: #1e90ff;" text="SIGN IN" textFill="WHITE">
<font>
<Font size="15.0" />
</font>
</Button>
<PasswordField fx:id="txtPass" layoutX="265.0" layoutY="377.0" prefHeight="25.0" prefWidth="235.0" promptText="Enter Password" />
<Rectangle arcHeight="18.0" arcWidth="18.0" fill="SILVER" height="174.0" layoutX="83.0" layoutY="264.0" opacity="0.41" stroke="BLACK" strokeType="INSIDE" width="506.0" />
<Rectangle arcHeight="12.0" arcWidth="12.0" fill="DODGERBLUE" height="35.0" layoutX="86.0" layoutY="229.0" opacity="0.67" stroke="BLACK" strokeType="INSIDE" width="500.0" />
</children>
</AnchorPane>
</code></pre>
<p><strong>LoginController.java</strong>:</p>
<pre><code>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package login;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
public class LoginController implements Initializable {
@FXML
private Label lblMsg;
@FXML
private Label txtUser;
@FXML
private Label txtPass;
@FXML
private void loginAction(ActionEvent event) {
if(txtUser.getText().equals("rs954") && txtPass.getText().equals("admin"))
{
lblMsg.setText("WELCOME");
}
else
{
lblMsg.setText("WRONG CREDENTIALS");
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
</code></pre>
<p><strong>Login.java</strong>:</p>
<pre><code>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package login;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Login extends Application {
@Override
public void start(Stage primaryStage) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("Login.fxml"));
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
</code></pre>
<p><strong>NEW ERROR:</strong></p>
<pre><code>Executing C:\J_Progs\Login\dist\run384200010\Login.jar using platform C:\Program Files\Java\jdk1.8.0_66\jre/bin/java
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)
Caused by: javafx.fxml.LoadException:
file:/C:/J_Progs/Login/dist/run384200010/Login.jar!/login/Login.fxml
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at login.Login.start(Login.java:23)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more
Caused by: java.lang.UnsupportedOperationException: Not supported yet.
at login.LoginController.initialize(LoginController.java:44)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
... 17 more
Exception running application login.Login
</code></pre>
<p><strong>NEW EDIT IN LoginController.java</strong></p>
<pre><code>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package login;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
public class LoginController implements Initializable {
@FXML
private Label lblMsg = new Label();
@FXML
private TextField txtUser = new TextField ();
@FXML
private TextField txtPass = new TextField ();
@FXML
private void loginAction(ActionEvent event) {
if(txtUser.getText().equals("rs95 4") && txtPass.getText().equals("admin"))
{
lblMsg.setText("WELCOME");
}
else
{
lblMsg.setText("WRONG CREDENTIALS");
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
</code></pre> | 1 |
How to print a char a certain number of times? | <p>I am trying to create code that takes a user-inputted number, and store it as an int. I then print out 'int' number of lines, with 'int' number of 'char' in each of them. So say for example, the inputted number was 3, it would then output</p>
<pre><code>XXX
XXX
XXX
</code></pre>
<p>However, when I try to do this, it just gives me the number it would calculate of the ASCII number * the inputted number. This is my current code:</p>
<pre><code>public static void main(String[] args) {
Scanner kb = new Scanner (System.in);
System.out.println("Please enter a number:");
int number = kb.nextInt();
kb.close();
char letter = 'X';
int sqnumber = number * number;
for (int i = 0; i < number; i++) {
System.out.println (letter * number);
}
}
</code></pre>
<p>However, this just gives me:</p>
<pre><code>Please enter a number:
3
264
264
264
</code></pre> | 1 |
rename files with list of special characters in python | <p>What's an efficient way to remove a list of special characters from a filename? I want to replace 'spaces' with '.' and '(', ')', '[',']' with '_'. I can do it for one, but I'm not sure how to rename multiple characters.</p>
<pre><code>import os
import sys
files = os.listdir(os.getcwd())
for f in files:
os.rename(f, f.replace(' ', '.'))
</code></pre> | 1 |
Run Python .py File from any folder | <p>I'm starting to create lots of python scripts. These scripts are made to run on a number of files from the same folder the script is in. I want to store this script in an organized folder, and be able to access the script from any folder I navigate to in the console. How do I do this? </p>
<p>Thanks!</p>
<p>Edit: this is what I wanted to do,
<a href="https://stackoverflow.com/questions/12475678/how-to-import-custom-python-package-by-name">How to import custom python package by name</a></p> | 1 |
Plotly.js adds top-margin to graphs inconsistently, how to prevent it | <p>With Plotly.js I'm getting a top-margin added sometimes (not consistently), where the total height of the graph is 300px, but the graph itself is only 150px high. The SVG container then is stretched and the actual graph is smaller. What can I do to prevent this white-space, and why does it only show up selectively? </p>
<p><a href="https://i.stack.imgur.com/P1NrR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/P1NrR.png" alt="Margin above graph"></a></p>
<p>Plotly Matlab syntax that results in 300px div instead of a 300px graph:</p>
<pre><code>`% PLOT MEAN MOVEMENT
data = {...
struct(...
'x', nScan, ...
'y',fastmotion, ...
'type', 'scatter')...
};
if max(fastmotion) < 0.3
yminval = 0.3;
else
yminval = round(max(fastmotion) + 1);
end
layout = struct(...
'yaxis', struct(...
'title', 'Movement (mm)', ...
'range', [0, yminval]));
header{3} = 'Absolute Movement';
layout.width = 800;
layout.height = 300;
p = plotlyfig;
p.data = data;
p.layout = layout;
p.PlotOptions.FileName = 'plot_5';
html_file = plotlyoffline(p);
html_file;`
</code></pre> | 1 |
why is logged_out.html not overriding in django registration? | <p>I am using built-in django login and logout. In my Project/urls.py i have added url's for both login and logout.</p>
<pre><code>from django.conf.urls import include, url
from account import views
from django.contrib.auth import views as auth_views
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$',views.index,name='Index'),
url(r'^accounts/login/$',auth_views.login,name='login'),
url(r'^accounts/logout/$',auth_views.logout,name='logout'),
url(r'^accounts/register/$',views.register,name='register'),
url(r'^accounts/profile/$',views.profile,name='profile'),
]
</code></pre>
<p>and i've templates folder inside my account app folder. i have directory structure like this</p>
<pre><code>account
-templates
-registration
-login.html
-logged_out.html
-register.html
-rest_html_files
-rest files
</code></pre>
<p>i've read django docs which say that for login() default template is registration/login.html which is working fine in my project and logout() default template is registration/logged_out.html if no arguments is supplied but whenever it Logout button ( which has a href={% url 'logout' %} ) is clicked it redirects to the admin logout page rather than my custom logout page.
what could possibly be wrong??</p> | 1 |
How can I change my CefSharp browser's user agent string and proxy? | <p>I already know how to set my CefSharp browser's <strong>starting</strong> user agent and proxy. But, I don't know how to <strong>change</strong> my browser's user agent and proxy while the program is running.</p>
<p>How can I change my CefSharp browser's user agent string to the text contents of <em>UserAgentStringTextBox</em> whenever I click the <em>LoadUserAgentStringButton</em> button?</p>
<p>How can I change my CefSharp browser's proxy to the text contents of <em>ProxyTextBox</em> whenever I click the <em>LoadProxyButton</em> button?</p>
<p>I've tried the following code, but it didn't visibly do anything:</p>
<pre><code>using CefSharp;
using CefSharp.WinForms;
using System.Windows.Forms;
namespace Proxy
{
public partial class ProxyForm : Form
{
private ChromiumWebBrowser browser;
private CefSettings settings;
public ProxyForm()
{
InitializeComponent();
InitializeWebBrowser();
}
private void InitializeWebBrowser()
{
settings = new CefSettings();
settings.CefCommandLineArgs.Add("proxy-server", "111.47.13.3:80");
settings.UserAgent = "Hello!";
Cef.Initialize(settings);
browser = new ChromiumWebBrowser(string.Empty) { Dock = DockStyle.Fill };
Controls.Add(browser);
}
private void LoadProxyButton_Click(object sender, System.EventArgs e)
{
settings.CefCommandLineArgs.Remove("proxy-server");
settings.CefCommandLineArgs.Add("proxy-server", ProxyTextBox.Text);
}
private void LoadUserAgentStringButton_Click(object sender, System.EventArgs e)
{
settings.UserAgent = UserAgentStringTextBox.Text;
}
private void LoadWebsiteButton_Click(object sender, System.EventArgs e)
{
browser.Load(WebsiteTextBox.Text);
}
}
}
</code></pre>
<p>The following 2 pictures show what happens when I load the website "whatsmyuseragent.com" <strong>WITHOUT</strong> attempting to change the default user agent string (Hello!) and proxy (111.47.13.3:80).</p>
<p><img src="https://i.stack.imgur.com/AEzog.png" width="500" height="500">
<img src="https://i.stack.imgur.com/XDLNG.png" width="500" height="500"></p>
<p>The following 2 pictures show what happens when I load the website "whatsmyuseragent.com" <strong>WITH</strong> attempting to change the default user agent string (Hello!) and proxy (111.47.13.3:80) -----> to the user agent string "Hey!" and proxy "213.85.92.10:80".</p>
<p><img src="https://i.stack.imgur.com/zhUbJ.png" width="500" height="500">
<img src="https://i.stack.imgur.com/Jvsj7.png" width="500" height="500"></p>
<p>Which, as you can see, was unsuccessful.</p>
<h1><strong>Thank you for taking the time to read my question!</strong></h1> | 1 |
Error: package ‘XLConnectJars’ could not be loaded in mac os | <p>I got a problem when I called 'XLConnect' library in R.</p>
<blockquote>
<p>Loading required package: XLConnectJars JavaVM: requested Java version
((null)) not available. Using Java at "" instead. JavaVM: Failed to
load JVM: /bundle/Libraries/libserver.dylib JavaVM FATAL: Failed to
load the jvm library. Error : .onLoad failed in loadNamespace() for
'XLConnectJars', details: call: .jinit() error:
JNI_GetCreatedJavaVMs returned -1</p>
<p>Error: package ‘XLConnectJars’ could not be loaded</p>
</blockquote>
<p>This error happened after I installed XLConnect and wrote library(XLconnect).</p>
<p>I googled this problem but there are no proper solution in my case.
I have already installed Java 8 and checked java location in terminal.
I run R in mac OS X (10.10.5)</p>
<p>Thank you for your help.</p> | 1 |
building failure in jenkins as build.sh: not found | <p>I am building a free style project in jenkins. configure setting for execute shell script as</p>
<pre><code>build.sh -label $JOB_NAME -$BUILD_NUMBER -java_home $JAVA_HOME
</code></pre>
<p>when i try to build the project, i have a console output as build failure.</p>
<pre><code>Building in workspace /var/lib/jenkins/workspace/jmxweb
[jmxweb] $ /bin/sh -xe /tmp/hudson4723307331600368596.sh
+ build.sh -label jmxweb -8 -java_home /usr/lib/jvm/java-7-oracle
/tmp/hudson4723307331600368596.sh: 2: /tmp/hudson4723307331600368596.sh: build.sh: not found
Build step 'Execute shell' marked build as failure
Finished: FAILURE
</code></pre> | 1 |
How can I make an HTTP DELETE request through JavaScript? | <p>I work in advertising. I am using the FB graph API to 'DELETE' ad assignments from the platform for a client using the HTTP DELETE method.</p>
<p>My requests are in the format:</p>
<pre><code>https://graph.facebook.com/v2.5/{{NODE_ID}}/{{EDGE_NAME}}?field_ids=['123456']
</code></pre>
<p>I normally use the graph explorer tool (<a href="https://developers.facebook.com/tools/explorer" rel="nofollow">https://developers.facebook.com/tools/explorer</a>) to accomplish such a task, but the client has provided over 8000 assignment to delete so doing it manually one by one would be tough.</p>
<p>How can I invoke an HTTP DELETE method using JavaScript? I want to use a for loop like this:</p>
<pre><code>var node_ids = ["123","456","789"];
var field_ids = ["abc","def","ghi"];
for (i = 0; i < node_ids.length < i++){
// MAKE DELETE REQUEST to "https://graph.facebook.com/v2.5/" + node_ids[i] + "/{{EDGE_NAME}}/?field_ids=['" + field_ids[i] + "']";
}
</code></pre>
<p>I saw a code like this online that I thought might be applicable, but I don't know how it works...</p>
<pre><code>$.ajax({
url: '/script.cgi',
type: 'DELETE',
success: function(result) {
console.log(result)
}
});
</code></pre>
<p>It looks like jquery but I guess it must be ajax? Does ajax need a library to be referenced like jquery does? Is it as simple as putting this function inside my for-loop and passing the URL I'm building inside the for loop to the 'url' field in the ajax call...?</p>
<p>What is the best function to pass to the 'success' parameter here so I know my request was successful? Is it possible to return the response from the delete request i.e. success:true if it works?</p>
<p>The more explicit you can be, the better!</p>
<p>Do you foresee any issues with me looping through 8000 entries across two arrays (one contains the node ID / object I am editing, and one contains a field related to the edge I'm accessing which will delete aka 'remove' the assignment from the node I am accessing...?</p>
<p>Thanks!</p> | 1 |
UWP focus control | <p>I have ListView with TextBoxes in universal windows 10 app. I want to write code: where user is editing any TextBox in Listiew and click enter key, I want to move focus to next TextBox in ListView (I want take the same action what happens where user click Tab key).</p>
<p>My question is: How to move focus programatically to the next listView element</p> | 1 |
JavaScript regex: Find a tag and get some attribute values | <p>i need to capture a html tag by class and some attribute value.</p>
<p>I've resolved the first part, capturing the tag by class (the <code>querySelector</code> should be something like: <code>'input.hashtag'</code>):</p>
<pre class="lang-html prettyprint-override"><code><input type="text" value="#tag3" notified="true" class="label-primary hashtag">
</code></pre>
<p>So, im using this regex:</p>
<pre class="lang-js prettyprint-override"><code>/(?=<input[^>]+(?=[\s+class=\"]hashtag[\s+\"]).+)([^>]+>)/g
</code></pre>
<p>You can checkout the test here <a href="https://regex101.com/r/zY4sH9/6" rel="nofollow">https://regex101.com/r/zY4sH9/6</a></p>
<p>What i need is to capture also the attribute values: <code>value</code> and <code>nofified</code>, to finally get:</p>
<ul>
<li>match1 <code><input type="text" value="#tag3" notified="true" class="label-primary hashtag"></code></li>
<li>match2 <code>#tag</code></li>
<li>match3 <code>true</code></li>
</ul> | 1 |
Windows Forms Transparent TextBox C# Existing solutions don't work | <p>I am creating my textbox programmatically in a console application that builds a form window on the fly. I am trying to get Input boxes such as the textbox to show up invisible but still allow the user to input data such as username and password or any other customisation fields I provide. This is for a game launcher and I am attempting to make it NOT look like a windows component.
I have tried some of the solutions on the post below.</p>
<p><a href="https://stackoverflow.com/questions/16050249/transparency-for-windows-forms-textbox">Transparency for windows forms textbox</a></p>
<p>EDIT: As you can see above I have already cited that this does not solve my issue. I do not use the form designer as it has a nasty habit of deleting my code because I presume "It knows better".</p>
<p>The Accepted answer for that does not work for me as I do not use the form designer and <code>InitializeComponent();</code>
Does not work it just tells me that it is not a function of the component.
I have gotten as far as this.</p>
<pre><code>using System.Windows.Forms;
namespace Launcher_Namespace
{
public class TransparentTextBox : TextBox
{
public TransparentTextBox()
{
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
}
}
}
</code></pre>
<p>And in the main body of code that initialises fields</p>
<pre><code> //Initialise Inputs
_username = new TransparentTextBox();
_username.Bounds = new Rectangle(120, 10, 120, 21);
_username.BackColor = Color.Transparent;
_username.BorderStyle = 0;
_username.Visible = false;
</code></pre>
<p>But all this has achieved is allow me to set <code>_username.BackColor = Color.Transparent;</code> Without throwing an error. The Input box remains White with no border. I just want to make the background transparent. Even MSDN recomends this solution but It does not work for me. My only solution left is to build a custom Label class that grabs the inputs and reads the key inputs and adds them to the .Text property but I don't want to do this.</p> | 1 |
How do I validate an URL? | <p>I'm trying to validate a url using NSURL but it doesn't work for me.</p>
<h2>Example:</h2>
<pre><code>func verifyUrl (urlString: String?) -> Bool {
if let urlString = urlString {
if let _ = NSURL(string: urlString) {
return true
}
}
return false
}
let ex1 = "http://google.com"
let ex2 = "http://stackoverflow.com"
let ex3 = "Escolas" // Not a valid url, I think
verifyUrl(ex1) // true
verifyUrl(ex2) // true
verifyUrl(ex3) // true
</code></pre>
<p>I think that "Escolas" can't return true, what am I doing wrong?</p> | 1 |
File uploading error in Codeigniter | <p>I am trying to upload an image in codeigniter.</p>
<p>here is my view file code.</p>
<pre><code><form action="<?php echo site_url('pages/data_submitted') ?>" method="get" enctype="multipart/form-data">
Image: <input type="file" name="image"/>
<button>Submit</button>
</form>
</code></pre>
<p>and this is my controller code.</p>
<pre><code>class Pages extends CI_Controller
{
public function data_submitted(){
$config['upload_path'] = "img/";
$this->load->library('upload',$config);
$this->upload->do_upload();
$finfo=$this->upload->data();
$data = $this->upload->display_errors();
$this->load->model('user_model');
$this->user_model->insert_item($data);
}
}
</code></pre>
<p>and here is my model code</p>
<pre><code><?php
class User_model extends CI_Model {
function __construct(){
/* Call the Model constructor */
parent::__construct();
}
public function insert_item($item){
print_r($item);
}
}
?>
</code></pre>
<p>What is wrong with this code...
Here I passed $data just to check whether any error occur or not.
And it is showing "You did not select a file to upload.' even I select a file.
please help me.</p> | 1 |
How to pass data from PHP to python | <p>How to pass data from PHP to Python?
This is my code.
PHP:</p>
<pre><code>$data = 'hello';
$result = shell_exec('/home/pi/Python.py' .$data);
</code></pre>
<p>Python:</p>
<pre><code>result = sys.argv[1]
print(result)
</code></pre>
<p>But when run python code it show error:</p>
<p><code>"IndexError: list index out of range"</code>.<br/> don't know Why?
Is it have other code for pass data from PHP to python?</p> | 1 |
Wordpress Order by date on custom post type archive page | <p>I have a custom post type called city guide and i created a archive page with the following code in wordpress. The posts displays but not in the order.I need it with date and desc ordering. When i changed <strong>$args</strong> <strong>orderby</strong> and <strong>order</strong> from the below code but it was displaying the same. </p>
<pre><code><?php
$args = array( 'hide_empty' => false, 'orderby' => 'id', 'order' => 'ASC' );
$taxonomy = 'city-guide-category';
$tax_terms = get_terms( $taxonomy, $args );
foreach($tax_terms as $tt):
$cat_arr[] = $tt->term_id;
endforeach;
?>
<?php
global $wp_query, $paged;
if( get_query_var('paged') ){
$paged = get_query_var('paged' );
} else if ( get_query_var('page') ){
$paged = get_query_var('page' );
} else{
$paged = 1;
}
?>
<?php $i=1; while( $wp_query->have_posts() ): $wp_query->the_post(); ?>
<?php get_template_part( 'templates/content-city-guide', get_post_format() ); ?>
<?php if( $i%2 == 0 && $i != $wp_query->post_count): ?>
<div class="clearfix visible-xs hidden-sm hidden-md hidden-lg"></div>
<?php endif; ?>
<?php if( $i%3 == 0 && $i != $wp_query->post_count): ?>
<div class="clearfix hidden-xs hidden-md hidden-lg"></div>
<?php endif; ?>
<?php if( $i%4 == 0 && $i != $wp_query->post_count): ?>
<div class="clearfix hidden-xs hidden-sm"></div>
<?php endif; ?>
<?php $i++; endwhile; ?>
</div>
</code></pre>
<p>I also tried </p>
<pre><code><?php
$wp_query->set('orderby','date');
$wp_query->set('order','desc');
?>
</code></pre>
<p>before and also after </p>
<pre><code><?php $i=1; while( $wp_query->have_posts() ): $wp_query->the_post(); ?>
</code></pre>
<p>which also did not work.Where I am wrong.Please help me out.</p>
<p>I tried this</p>
<pre><code> <?php
global $wp_query, $paged;
if( get_query_var('paged') ){
$paged = get_query_var('paged' );
} else if ( get_query_var('page') ){
$paged = get_query_var('page' );
} else{
$paged = 1;
}
//ddbug( $wp_query->request );
$args = array(
'orderby' => 'date',
'order' => 'DESC',
);
$query = new WP_Query( $args ); ?>
<?php $i=1; while( $query->have_posts() ): $query->the_post(); ?>
<?php get_template_part( 'templates/content-city-guide', get_post_format() ); ?>
<?php if( $i%2 == 0 && $i != $query->post_count): ?>
<div class="clearfix visible-xs hidden-sm hidden-md hidden-lg"> </div>
<?php endif; ?>
<?php if( $i%3 == 0 && $i != $query->post_count): ?>
<div class="clearfix hidden-xs hidden-md hidden-lg"></div>
<?php endif; ?>
<?php if( $i%4 == 0 && $i != $query->post_count): ?>
<div class="clearfix hidden-xs hidden-sm"></div>
<?php endif; ?>
<?php $i++; endwhile; ?>
</div>
<?php if( $query->max_num_pages > 1) : ?>
<div class="more-posts-link-wrapper">
<?php next_posts_link(__('<span class="more-posts-text">More <i class="bits-arrow-down"></i></span><img src="' . get_stylesheet_directory_uri() . '/assets/img/ajax-loader.gif" alt="Loading..." class="ajax-loader" height="15px;" width="auto" style="display:none;">','roots') ); ?>
</div>
<?php endif; ?>
</div>
</div>
</code></pre>
<p>It is displaying now by date but when i click the more link ore next page to see the second set of posts it is displaying the same set of posts.Imean theyre repeating even if i go to 12th page of pagination.
please help.</p> | 1 |
How can I include my resource files in my framework without using a separate bundle? | <p>I've been following this guide to create an iOS static library: <a href="https://github.com/jverkoey/iOS-Framework#walkthrough" rel="noreferrer">https://github.com/jverkoey/iOS-Framework#walkthrough</a>. I managed to create a framework that can be imported into another Xcode project.</p>
<p>Now, I want my framework to be able to show a Storyboard. I imagine that the <code>.storyboard</code> file counts as a resource. The previous guide states that I should create a Bundle for my resource files, such as images, instead of putting them in the framework itself.</p>
<p>However, I <strong>do</strong> want to put them in the framework itself. I don't want to use a separate bundle.</p>
<p>All guides I find around tell me the same thing. I understand the advantages of using a separate bundle, but I just don't want to do it right now.</p>
<p>Now then, I am lost on how to include my <code>.storyboard</code> file in my framework so that I can show it with this:</p>
<pre><code>UIStoryboard *sb = [UIStoryboard storyboardWithName:@"NameOfStoryboard" bundle:[NSBundle bundleForClass:[self class]]];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"NameOfViewController"];
[otherView presentViewController:vc animated:YES completion:NULL];
</code></pre>
<p>The above code does not seem to work (it can't find the storyboard file). I imagine this is because the <code>.storyboard</code> is not currently included in the framework. Sadly, I don't know how to include it.</p>
<p>In the framework's Xcode project, under Build Phases, I see a tab labeled "Copy files" which looks like what I need.</p>
<p><a href="https://i.stack.imgur.com/UGb0U.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UGb0U.png" alt="enter image description here"></a></p>
<p>Now, I'm not sure what this is doing, but in any case, it doesn't seem to be working anyway.</p>
<p>I also did this:</p>
<p><a href="https://i.stack.imgur.com/nDymY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nDymY.png" alt="enter image description here"></a></p>
<p>How can I include my <code>.storyboard</code> file in my framework without using a separate bundle?</p> | 1 |
Javascript match returns only first match | <p>I am having problems to get the matches to a simple regex. Here is the code:</p>
<pre><code>var keyWordRegex = /\{\w+\}/;
"idSalaVirtual={idSalaVirtual}&idSalaVirtualOferta={idSalaVirtualOferta}".match(keyWordRegex)
</code></pre>
<p>This code returns <code>["{idSalaVirtual}"] instead of ["{idSalaVirtual}", "{idSalaVirtualOferta}"]</code> that was the result I was specting. If I remove {idSalaVirtual} from the test string, then it returns <code>["{idSalaVirtualOferta}"]</code>.</p>
<p>Does anyone know why it is not returning the two words from the method?</p>
<p>Thanks in advance.</p>
<p>The problem was solved using the 'g' flag, but I didn't even know the existance of this flag. So there is no reason the mark it as duplicate of <a href="https://stackoverflow.com/questions/12993629/the-g-flag-in-regular-expressions">The 'g' flag in regular expressions</a><br>
If someone goes through the same problem that I did without knowing the existance of the 'g' flag, they won't find an answer.</p> | 1 |
How to add new woocommerce attribute type? | <p>Woocommerce has two attribute type (text , select) !</p>
<p>How can I add new attribute type <strong>checkbox</strong></p>
<p>I prefer to don't use plugin : )</p> | 1 |
Automatically next line in a label if a string is too long in XAML | <p>I have a label that is binded to something. I want the label to expand in width and height if the string is too long, so that it fits on screen.</p>
<p>I had this: </p>
<pre><code><StackPanel Orientation="Horizontal" Margin="0,0,0,200" Height="50" Width="900">
<Label HorizontalContentAlignment="Left" VerticalAlignment="Center" Padding="5" FontSize="24" Content="Instruction: " Width="290" />
<TextBlock HorizontalAlignment="Center" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="25" Text="{Binding InstructionLabel}" Width="auto" Height="auto" />
</StackPanel>
</code></pre>
<p>Notice that I tried using a TextBlock instead of a Label. This didn't work tough, so I tried:</p>
<pre><code><Label HorizontalAlignment="Center" VerticalAlignment="Top" FontSize="25" Width="auto" Height="auto">
<AccessText TextWrapping="WrapWithOverflow" Text="{Binding InstructionLabel}"/>
</Label>
</code></pre>
<p>But this doesn't work either.</p>
<p>The View is now like this:</p>
<p><a href="https://i.stack.imgur.com/U9Ka8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/U9Ka8.png" alt="enter image description here"></a></p> | 1 |
What's the alternative to Azure Cloud Service (Classic)? | <p>Considering Azure Cloud Services are considered 'classic' and MS is steering towards using the Resource Manager. </p>
<p>What is the recommended path for hosting a WCF webservice? I used to do this with a Azure Cloud Service so I didn't have to manage a Virtual Machine, but I can't find the obvious successor to Cloud Services.</p> | 1 |
python.exe is not a valid win32 application | <p>I found several topics relating to this issue (when I try to run python.exe in command line, I get the subject error message), but none of the suggestions worked for me. I have installed and uninstalled around 5 times now. I wasn't getting this error earlier tonight after first installing, FWIW.</p>
<p>I am running Windows 7 64 bit. I realized that my first default 3.5.1 install was 32-bit so I uninstalled. Then I installed Windows x86-64 executable installer. I tried that twice. I switched to version 2.7.11 Windows x86-64 MSI installer. I still get this error. On the latest try (2.7.11), I ran Dependency Walker and got 3 errors:</p>
<blockquote>
<p>Error: At least one required implicit or forwarded dependency was not found.<br>
Error: At least one module has an unresolved import due to a missing export function in an implicitly dependent module.<br>
Error: Modules with different CPU types were found.</p>
</blockquote>
<p>The first error is that python27.dll is missing. I found that in the System folder and copied it into the main folder of my install (C:\Python27) and then also tried the DLL folder. Still getting my same error. Pulling me hair out and it doesn't help that I am brand new to python in general! I am worried that the uninstalls haven't been scrubbing properly or I have otherwise messed this up.</p>
<p>Thanks and sorry!</p> | 1 |
JavaFX fxml loader does not work properly | <p>testFX.java :</p>
<pre><code>public class testFX extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
try{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/testFX/view/test.fxml"));
System.out.println("after set location");
//PROBLEM
AnchorPane root = (AnchorPane)loader.load();
System.out.println("Does not happen");
testFXController listController = loader.getController();
listController.start();
Scene scene = new Scene(root, 200, 300);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
catch (Exception ex){
System.out.println("Error");
}
}
public static void main(String[] args) {
launch(args);
}
}
</code></pre>
<p>testFXController.java :</p>
<pre><code>package testFX.view;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ListView;
public class testFXController {
@FXML ListView<String> listView;
private ObservableList<String> obsList;
public void start() {
// create an ObservableList
// from an ArrayList
obsList = FXCollections.observableArrayList("Giants", "Patriots", "Jaguars");
listView.setItems(obsList);
}
}
</code></pre>
<p>test.fxml :</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.control.ListView?>
<AnchorPane xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="view.testFXController">
<ListView fx:id="listView"
AnchorPane.topAnchor="10"
AnchorPane.leftAnchor="10"
AnchorPane.rightAnchor="10"
AnchorPane.bottomAnchor="10" />
</AnchorPane>
</code></pre>
<p>When I run the testFX.java, the system prints: </p>
<pre><code>after set location
Error
</code></pre>
<p>This is the professor's code and I cannot seem to get it running. I realized that the main problem is in the line of code <code>AnchorPane root = (AnchorPane)loader.load();</code> but I have no idea how to fix this, can someone help?</p> | 1 |
Multiple conditions in a jade conditional | <p>I'm a bit stumped as to why... <code>if (data.query && data.query != '[object Object]')</code> works</p>
<p>but <code>if (data.query && data.query != ('[object Object]' || data.query != 'undefined'))</code></p>
<p>How can you have multiple conditions inside of a jade <code>if</code>?</p> | 1 |
unhandled level 3 permission fault (11) [ error disappears when running gdb...! ] | <p>So I am trying to run my c++ application on an aarch64(ARM 8). ***When run using GDB the application runs without any problem. But otherwise it gives me a segmentation fault.***I checked dmesg and it goes as </p>
<pre><code>unhandled level 3 permission fault (11) at 0x004ac010, esr 0x8300000f
[241808.064733] pgd = ffffffc0fe270000
[241808.068270] [004ac010] *pgd=00000001615c9003, *pmd=000000016f316003, *pte=02e0000147f42f53
[241808.076813]
[241808.076824] CPU: 2 PID: 12503 Comm: Jumpi Not tainted 3.10.67-g3a5c467 #1
[241808.076832] task: ffffffc0fef9c080 ti: ffffffc0f0fe4000 task.ti: ffffffc0f0fe4000
[241808.076841] PC is at 0x4ac010
[241808.076846] LR is at 0x401cb8
[241808.076852] pc : [<00000000004ac010>] lr : [<0000000000401cb8>] pstate: 20000000
[241808.076857] sp : 0000007fc044b600
[241808.076863] x29: 0000007fc044b680 x28: 0000000000000000
[241808.076873] x27: 0000000000000000 x26: 0000000000000000
[241808.076882] x25: 00000000004186ec x24: 0000000000418634
</code></pre>
<p>I tried set disable-randomization off in gdb but still no error.I then tried valgrind. I get a lot of error messages saying unitialised value was created ,mostly at dl_init_paths.But more importantly I get the bad permission generating SISGEV at a memory address which when i went through memory seems to be in (env_path_list) .
That where i am at after debugging for hours.If anyone has any suggestions/ideas about the next steps that would be helpful.
Another interesting fact is when the same code was compiled using a cross compiler and ran on this (ARM8) it works fine...!!</p> | 1 |
Refresh page automatically after submitting form | <p>After I submit my data from form I don't see it immediate on my screen, I have to refresh it via browser refresh button. </p>
<pre><code><form action="" method="post">
<input type="submit" name="submit" >
</code></pre>
<p>I was using the <code>setTimeout</code> function but it gave me lot of issues in submitting to the database and retrieving from it. I could not debug it properly, and so I removed this function. Without <code>setTimeout</code>, I am able to store in the database and retrieve via the refresh button. But how do I make it immediately auto refresh?</p> | 1 |
How to get the next number in a sequence | <p>I have a table like this:</p>
<pre><code>+----+-----------+------+-------+--+
| id | Part | Seq | Model | |
+----+-----------+------+-------+--+
| 1 | Head | 0 | 3 | |
| 2 | Neck | 1 | 3 | |
| 3 | Shoulders | 2 | 29 | |
| 4 | Shoulders | 2 | 3 | |
| 5 | Stomach | 5 | 3 | |
+----+-----------+------+-------+--+
</code></pre>
<p>How can I insert another record with the next seq after <code>Stomach</code> for Model 3. So here is what the new table suppose to look like:</p>
<pre><code>+----+-----------+------+-------+--+
| id | Part | Seq | Model | |
+----+-----------+------+-------+--+
| 1 | Head | 0 | 3 | |
| 2 | Neck | 1 | 3 | |
| 3 | Shoulders | 2 | 29 | |
| 4 | Shoulders | 2 | 3 | |
| 5 | Stomach | 5 | 3 | |
| 6 | Groin | 6 | 3 | |
+----+-----------+------+-------+--+
</code></pre>
<p>Is there a way to craft an insert query that will give the next number after the highest seq for Model 3 only. Also, looking for something that is concurrency safe.</p> | 1 |
git - Git asking for SSH password every time | <p>I use SSH to connect to my server (Ubuntu 15.10) where I push and pull to Git repositories.
However, despite installing the <code>gnome-keyring</code> with instructions from <a href="https://stackoverflow.com/questions/13385690/how-to-use-git-with-gnome-keyring-integration">here</a>.</p>
<p>Strangely, the Credential Helper works correctly with repositories I clone from GitHub using HTTPS, but not with my own SSH server.</p> | 1 |
Marshmallow Fingerprint Scanner Hardware Presence | <p>I am looking to get started with the Marshmallow Fingerprint Authentication API. I understand that to ask for permission, I must use the following method:</p>
<pre><code>ContextCompat.checkSelfPermission(getContext(), Manifest.permission.USE_FINGERPRINT);
</code></pre>
<p>And I must check if the device is running API level 23 or higher. But before I ask for permission, I would like to check if the device actually has a fingerprint scanner to begin with. I found the following two methods to do this check:</p>
<pre><code>FingerprintManager manager = (FingerprintManager) getSystemService(Context.FINGERPRINT_SERVICE);
manager.isHardwareDetected();
manager.hasEnrolledFingerprints();
</code></pre>
<p>But both methods require <code>USE_FINGERPRINT</code> permission to be called at all. Why would I want to ask for permission to use a fingerprint scanner that I do not even know exists? Are there any other methods to find out if a scanner exists? Or is the only way to ask for permission first?</p> | 1 |
How do I edit an event in fullCalendar? | <p>I have this sample:</p>
<p><a href="http://jsfiddle.net/rho79s7w/44/" rel="nofollow">link</a></p>
<p><strong>CODE HTML:</strong></p>
<pre><code><div id='calendar'></div>
<div class="cont" style="display:none">
<button type="button" class="btn btn-primary btn-save" id="edit">Save</button>
<input id="required-input" type="text" name="firstname" id="firstname" placeholder="John">
</code></pre>
<p><strong>CODE JS:</strong></p>
<pre><code> $(function() { // document ready
var calendar=$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2014-11-12',
editable: true,
eventLimit: true, // allow "more" link when too many events
defaultView: 'agendaDay',
selectable: true, //permite sa selectezi mai multe zile
selectHelper: true, //coloreaza selctia ta
eventClick: function(event, jsEvent, view) {
$(".cont").show();
$( "#edit" ).click(function(e) {
e.preventDefault();
alert(event._id);
event.title = $("#required-input").val();
$('#calendar').fullCalendar('updateEvent', event);
$(".cont").hide();
});
// event.title = "CLICKED!";
},
select: function(start, end, allDay)
{
var title = "test"
if(title)
{
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
//allDay: allDay
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
events: [
{
title : 'titleEvent',
start : '2014-11-12',
allDay : false // will make the time show
},
]
});
});
</code></pre>
<p>Unfortunately at this time to edit all events, I just want the current event.</p>
<p>The reason this happens? Because button click?</p>
<p>I put an alert and run twice, you can test the link above and see more clearly.</p>
<p>Thanks in advance!</p> | 1 |
Running docker commands as a build step in Jenkins | <p>I am running some docker commands as a post build step in Jenkins, and it is failing. My job is running on a slave node, and when I go to the slave host and execute the docker commands directly, everything works. Just as a simple test, I use the following as a post-build step:</p>
<pre><code>docker ps
</code></pre>
<p>The output in the console is this:</p>
<ul>
<li>docker ps
Cannot connect to the Docker daemon. Is the docker daemon running on this host?
Build step 'Execute shell' marked build as failure</li>
</ul>
<p>The only user on this machine is the one that is building, and it is set to the docker group. What might be different about the environment of the build itself, and when I ssh into the node host that could cause this problem?</p>
<p>Thanks.</p> | 1 |
Selecting section of polyline - Google Maps Api | <p>Is it possible to select only a section of a polyline in a Google Map? I have markers which are added by the user and a polyline is drawn between the markers. The polyline between two markers represents the route between the two places.I want the user to be able to click on the polyline, that section changes colour and then insert another point. I'd also like to get the marker ID's (which are set when the marker is added), of the markers which the polyline connects.</p>
<p>This is the google sample code which my code is based off, since my code is quite messy, i'm posting this instead.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Complex Polylines</title>
<style>
html, body
{
height: 100%;
margin: 0;
padding: 0;
}
#map
{
height: 100%;
}
</style>
</head>
<body>
<div id="map">
</div>
<script>
var poly;
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: { lat: 41.879, lng: -87.624} // Center the map on Chicago, USA.
});
poly = new google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
});
poly.setMap(map);
// Add a listener for the click event
map.addListener('click', addLatLng);
}
// Handles click events on a map, and adds a new point to the Polyline.
function addLatLng(event) {
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear.
path.push(event.latLng);
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&signed_in=true&callback=initMap"></script>
</body>
</html>
</code></pre>
<p>So far, i've only managed to add a click event listener to the entire polyline:</p>
<pre><code> google.maps.event.addListener(poly, 'click', function() {
poly.setOptions({strokeColor: '#76EE00'});
});
</code></pre> | 1 |
Picasso loads image with triangle in corner of image | <p>I'm using picasso library for loading images from server into my application. my problem is when image loaded it has a triangle in top-left corner of image with color(like blue,green,red).
this is my code for loading image:</p>
<pre><code>public static void loadDynamicImage(final String url, final Context context, final ImageView imageView, final int width, final int height){
Picasso.with(context).load(url)
.networkPolicy(NetworkPolicy.OFFLINE)
.resize(width,height)
.onlyScaleDown()
.into(imageView, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
Picasso.with(context).load(url).resize(width,height).onlyScaleDown().into(imageView);
}
});
}
</code></pre>
<p>the image shown is :
<a href="https://i.stack.imgur.com/bvJ81.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/bvJ81.jpg" alt="the image that picasso loads in application"></a></p> | 1 |
xcode 7.2 couldn’t communicate with a helper application | <p>When i create an xcode project getting following error, this error appears every time when i create a new project can any one help me to figure out the reason</p>
<p><a href="https://i.stack.imgur.com/yUP3o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yUP3o.png" alt="Screenshot added"></a></p> | 1 |
Grails 3 Spring Security override login form | <p>I've found a few things from spring documentation that you can override the login controller and form. I just want to override the login form itself while keeping the default controller. I found this: </p>
<blockquote>
<p>In the grails security plugin, the login gsp page is located at grails-app/views/login/auth.gsp and the controller at grails-app/controllers/grails/plugin/springsecurity/LoginController.groovy. I don't think the controller can be overwritten by simply creating your own implementation, but you should be able to override the gsp page by placing your own auth.gsp in the same path shown above, in your app. </p>
</blockquote>
<p><a href="https://plus.google.com/117486613280979732172/posts/cvqcfAQVWE6" rel="nofollow">https://plus.google.com/117486613280979732172/posts/cvqcfAQVWE6</a></p>
<p>However, this is just not working to override the page and the default page keeps coming up. Has anyone done this with Grails 3 and spring security libraries?</p>
<p>EDIT:
I'm using OAuth2 by using these libraries and setting up my own beans. I think the other way might be to use grails plugins for spring security. Is there a way to override the login page using these libraries?</p>
<pre><code>compile "org.springframework.boot:spring-boot-starter-security"
compile "org.springframework.security.oauth:spring-security-oauth2:2.0.8.RELEASE"
</code></pre> | 1 |
Spark RDD: set difference | <pre><code>val data: RDD [(String, Array[Int])] = sc.parallelize(Seq(
("100",Array(1, 2, 3, 4, 5)), ("1000",Array(10, 11, 12, 13, 14))
))
val codes = sc.parallelize(Seq(2, 3, 12, 13))
val result = data.map {case (id,values) => (id, values.diff(codes))}
</code></pre>
<p>I would like to get the result as:</p>
<pre><code>val result: Array[(String, Array[Int])] = Array(
("100", Array(1, 4, 5)), ("1000", Array(10, 11, 14))
)
</code></pre>
<p>However, when I do the set difference, I get type mismatch error. </p> | 1 |
How to Find the Neighbors of a Cell in an ndarray? | <p>I'm working with n-dimensional arrays in Python, and I want to find the "neighbors" (adjacent cells) of a given cell based on its coordinates. The issue is that I don't know the number of dimensions beforehand.</p>
<p>I attempted to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html" rel="nofollow noreferrer"><code>numpy.roll</code></a> as suggested by <a href="https://stackoverflow.com/a/13805310/2827555">this answer</a>, but it seems unclear how to apply this method to multiple dimensions.</p>
<p>Please point me in the right direction.</p> | 1 |
Why are prestashop Cart Rules (Vouchers) not showing in frontend? | <p>I successfully generated a test cart rule and assigned to my user.</p>
<p>I can see it both in backoffice and on the my-account page under 'my vouchers'. So we're sure it's recorderd and assigned.</p>
<p>What happens is that in shopping-cart page, even after loggin in with my user, I can't see any voucher field.</p>
<p>Digging deeper, I can say that the $discounts template var is not populated, or, simply it counts zero. So I took a look to the controller, and saw it assign it via <code>$order->getCartRules()</code>. And getCartRules simply reads a db table. And surprise?? The order_cart_rule table is empty. So it doesn't get populated. So what could be the problem here? Ever had same issue someone? It's a strange thing..</p>
<p>Probably the main question is: where/when exaclty do the cart and the rules get created/applied? I can see in FrontController the cart being created, but at that point it seems the cart rules are not setted yet.</p>
<p>By the way, I'm running on latest prestashop 1.6.1.4</p> | 1 |
ClassNotFoundException: org.glassfish.jersey.media.multipart.FormDataMultiPart | <p>I am building a project using maven and when I try to deploy on server getting below exception. Multipart jar is already present in the maven dependencies.</p>
<pre><code>java.lang.ClassNotFoundException: org.glassfish.jersey.media.multipart.FormDataMultiPart
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:501)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:421)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:412)
at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
</code></pre> | 1 |
Django-Haystack using Amazon Elasticsearch hosting with IAM credentials | <p>I am hoping to use Amazon's Elasticsearch server to power a search of longtext fields in a Django database. However, I also don't want to expose this search to those who don't have a log in and don't want to rely on security through obscurity or some IP restriction tactic (unless it would work well with an existing heroku app, where the Django app is deployed).</p>
<p>Haystack seems to go a long way toward this, but there doesn't seem to be an easy way to configure it to use Amazon's IAM credentials to access the Elasticsearch service. This functionality does exist in elasticsearch-py, whichi it uses.</p>
<p><a href="https://elasticsearch-py.readthedocs.org/en/master/#running-with-aws-elasticsearch-service" rel="noreferrer">https://elasticsearch-py.readthedocs.org/en/master/#running-with-aws-elasticsearch-service</a></p>
<pre><code>from elasticsearch import Elasticsearch, RequestsHttpConnection
from requests_aws4auth import AWS4Auth
host = 'YOURHOST.us-east-1.es.amazonaws.com'
awsauth = AWS4Auth(YOUR_ACCESS_KEY, YOUR_SECRET_KEY, REGION, 'es')
es = Elasticsearch(
hosts=[{'host': host, 'port': 443}],
http_auth=awsauth,
use_ssl=True,
verify_certs=True,
connection_class=RequestsHttpConnection
)
print(es.info())
</code></pre>
<p>Regarding using HTTP authorization, I found this under issues at <a href="https://github.com/django-haystack/django-haystack/issues/1046" rel="noreferrer">https://github.com/django-haystack/django-haystack/issues/1046</a></p>
<pre><code>from urlparse import urlparse
parsed = urlparse('https://user:pass@host:port')
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': parsed.hostname,
'INDEX_NAME': 'haystack',
'KWARGS': {
'port': parsed.port,
'http_auth': (parsed.username, parsed.password),
'use_ssl': True,
}
}
}
</code></pre>
<p>I am wondering if there is a way to combine these two, something like the following (which, as expected, gives an error since it's more than just a user name and password):</p>
<pre><code>from requests_aws4auth import AWS4Auth
awsauth = AWS4Auth([AACCESS_KEY],[SECRET_KEY],[REGION],'es')
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': [AWSHOST],
'INDEX_NAME': 'haystack',
'KWARGS': {
'port': 443,
'http_auth': awsauth,
'use_ssl': True,
'verify_certs': True
}
},
}
</code></pre>
<p>The error here:</p>
<pre><code>TypeError at /admin/
must be convertible to a buffer, not AWS4Auth
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/
Django Version: 1.7.7
Exception Type: TypeError
Exception Value:
must be convertible to a buffer, not AWS4Auth
Exception Location: /usr/lib/python2.7/base64.py in b64encode, line 53
</code></pre>
<p>Any ideas on how to accomplish this?</p> | 1 |
How to use current date in a sql query of Db2 | <p>I need a query to insert current date in a sql query. Below query works when in my DB2.</p>
<pre><code>select * from H1TI1.PS_CAL_DETP_TBL where END_DT='2000-02-25' with ur;
</code></pre>
<p>I need to put current date as following <code>END_DT = CURRENT_DATE</code> .</p>
<p>And also want to use <code>COUNT</code> function to count how many rows i get as a result.</p>
<p>Thanking you in advance.</p> | 1 |
Error installing Package in R Studio | <p>I am trying to install the SDSFoundations package into R studio in Mac but Its getting an error.</p>
<pre><code>install.packages("~/Downloads/SDSFoundations_1.3.tar", repos = NULL)
Error in install.packages : type == "both" cannot be used with 'repos = NULL'
</code></pre>
<p>also I tried the following:</p>
<pre><code>install.packages("~/Downloads/SDSFoundations_1.3.tar", repos = NULL, type ='binary')
tar: Failed to set default locale
</code></pre>
<p>Any ideas?</p>
<p>Thanks</p> | 1 |
Show default element while loading Image | <p>I have a component representing an user avatar that loads an image from my API.
I want it to display a default avatar (not another image) while the avatar is loading.</p>
<pre><code>constructor() {
super();
this.state = {
loaded: false,
};
}
render() {
if (!this.props.uri || !this.state.loaded) {
return (
<DefaultAvatar />
);
}
return <Image onLoad={this.onLoad.bind(this)} uri={this.props.uri} />;
}
onLoad() {
this.setState({loaded: true});
}
</code></pre>
<p>The problem I have is that with this current code, the <code>Image</code> will never be rendered, so the state will never change. I'm unable to find a solution that would satisfy React principles and my requirements (no ghost components to load the image before displaying it).</p> | 1 |
How do you reverse order in ruby | <p>How do you write a code snippet in Ruby that prints out, in reverse order, every multiple of 3 between 1 and 200?</p>
<p>This is the code I have so far:</p>
<pre><code>(1..200).each do | i | ##loop it then
if i % 3 == 0
</code></pre> | 1 |
Trouble installing Scrapy on Windows 64 bit | <p>I am attempting to install Scrapy on my Windows 7 64 bit machine. I started by following the instructions here on Scrapy's documentation.</p>
<p>I got up until the command <code>'pip install Scrapy'</code>. Everything works except that it cannot find 'libxml2':</p>
<pre><code>Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?
</code></pre>
<p>I then visited this website to get the binaries of <code>libxml2</code>:</p>
<p><a href="ftp://ftp.zlatkovic.com/libxml/64bit/" rel="nofollow">ftp://ftp.zlatkovic.com/libxml/64bit/</a></p>
<p>The instructions for installation of <code>libxml2</code> are here: <a href="https://www.zlatkovic.com/libxml.en.html" rel="nofollow">https://www.zlatkovic.com/libxml.en.html</a></p>
<p>They state that you should unzip the binaries and place the contents of the <code>BIN</code> folder in a path such as <code>C:\WINDOWS</code>. I did this. However, after attempting to install Scrapy again, I continue to receive the same error. Is there something I am missing?</p> | 1 |
Easy way to extract EXIF data in PowerShell? | <p>I've been looking at various methods that I can extract EXIF data using PowerShell, but I have so far seen that it is quite convoluted.
Some <a href="http://blog.cincura.net/233463-renaming-files-based-on-exif-data-in-powershell/" rel="nofollow">here</a> and <a href="https://chrisjwarwick.wordpress.com/2011/11/08/modify-date-taken-values-on-photos-with-powershell-the-update-exifdatetaken-script-cmdlet-2/" rel="nofollow">here</a>.</p>
<p>I am looking for a (relatively) simple method to extract basic EXIF data using powershell, so that I can use it natively.</p>
<p>In particular, I am particularly interested in the <strong>Date Taken</strong> property and I am trying to find a method I can run this through <strong>Get-Date</strong>, and customise the formatting for my own needs.
Something like:</p>
<pre><code>$exifdatetaken = $mypicture.'Date taken' | Get-Date -Format yyyyMMdd-HHmmss
</code></pre>
<p>Does anyone know if there is a way to do this natively in PowerShell?</p> | 1 |
PHP connect to MS SQL with SSL | <p>What I mean to achieve is very simple. I want to connect to an external MS SQL database from a PHP script over a secure connection. This has however proven problematic and, with three hours put in to research so far, I am at a loss.</p>
<p>The platform for the client is Ubuntu, which means I can not use SQLSRV.
The secure connection has been tested with different clients and it works fine.
I am currently using PDO and DBlib to connect to the database, which also works fine.</p>
<p>I was not able to find any method to force a secure connection. I have tried multiple other drivers, to no avail. </p>
<p>What are my options?</p>
<p>Edit: I am left with the following FreeTDS logs...</p>
<pre><code>config.c:543: Got a match.
config.c:565: host = 'XXXXXXXXXX'
config.c:595: Found host entry XXXXXXXXXX.
config.c:599: IP addr is XXXXXXXXXX.
config.c:565: port = '1433'
config.c:565: encryption = 'require'
config.c:565: check certificate hostname = 'no'
config.c:629: UNRECOGNIZED option 'check certificate hostname' ... ignoring.
config.c:565: ca file = 'XXXXXXXXXX.pem'
config.c:629: UNRECOGNIZED option 'ca file' ... ignoring.
</code></pre> | 1 |
Keep checkbox checked, after refresh and submit | <p>I'm trying to keep a checkbox checked, but after I refresh the page, if the checkbox is checked the database will get updated with 'yes', but the database automatic updates it to 'no' even if the checkbox is checked with local.store, I hope somebody can help me. This is my code.</p>
<pre><code> <form action="" method="POST">
<label for="option1">Waarschuwingsbericht inschakelen voordat het volgende pack wordt geopend als jou pack boven de 200.000 waard is?</label><input id='option1' type="checkbox" name="checkbox" value="yes"><br>
<input type="submit" value="Opslaan en nog een pack openen">
</form>
<?
if(isset($_POST['checkbox'])){
$sql = "UPDATE users SET puntenchecked = 'yes' WHERE username = '" . $usernamez . "'";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
}
else {
$sql = "UPDATE users SET puntenchecked = 'no' WHERE username = '" . $usernamez . "'";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
}
?>
<script>
$(function(){
var test = localStorage.input === 'true'? true: false;
$('input').prop('checked', test || false);
});
$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
</script>
</code></pre> | 1 |
Leaflet-Realtime plugin with GeoJson and multiple markers | <p>Hello guys i am trying to update my markers position but i don't manage to find out how to remove the old ones. All i get is a "history" of the marker. I didnt any examples that will help me. I hope someone will give me a clue to go on.
Many thanks to <a href="http://www.liedman.net/" rel="nofollow">Per Liedman</a> for the awesome job.</p>
<pre><code> var shipLayer = L.layerGroup();
var ships = L.icon({
iconUrl: '../icons/ship-icon.png',
iconSize: [30, 30]
});
var realtime = L.realtime({
url: 'jsonServlet/ships.json',
crossOrigin: true,
type: 'json'
}, {
interval: 5 * 1000,
pointToLayer: function (feature, latlng) {
marker = L.marker(latlng, {icon: ships});
marker.bindPopup('mmsi: ' + feature.properties.mmsi +
'<br/> course:' + feature.properties.hdg+
'<br/> speed:' + feature.properties.sog);
marker.addTo(shipLayer);
return marker;
}
});
controlLayers.addOverlay(geojson, 'Ships');
</code></pre> | 1 |
JasperException: Absolute uri cannot be resolved | <p>I have been getting the following JasperException when trying to use an XML schema for my web.xml, instead of the deprecated DOCTYPE declaration:</p>
<pre><code>HTTP Status 500 - The absolute uri: http://java.sun.com/jsp/jstl/core
cannot be resolved in either web.xml or the jar files deployed with this
application
</code></pre>
<p>If I use this web.xml, the application compiles:</p>
<pre><code><!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
</web-app>
</code></pre>
<p>However, if I use this web.xml, I get the JasperException:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>CourseManagementJDBC</display-name>\
</web-app>
</code></pre>
<p>Any idea why only a deprecated format would work?</p>
<p><strong>NOTE</strong>: This is for a Maven project, and the JSTL dependency has been correctly declared, as well as the tag library in the JSP:</p>
<p>pom.xml:</p>
<pre><code><dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</code></pre>
<p>JSP:</p>
<pre><code><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
</code></pre>
<p>They're all correct; what gives?</p> | 1 |
Creating internal functions (can't be called from console) in R | <p>I'm working on an R package where I have an overarching function that generates some files, we'll call it <code>main(...)</code> and it exists in its own file <code>main.R</code>. Now <code>main</code> calls other functions like <code>helper1(...)</code> and <code>helper2(...)</code> which are found in <code>helper1.R</code> and <code>helper2.R</code>. Is it possible to make it so that <code>main</code> can call the helper functions, but the user cannot call directly the helper functions? I have them spread out in different files due to the stark differences in their purpose. Is the solution to put them all under one file <code>main.R</code>?</p> | 1 |
Where to save python modules | <p>I'm just learning about modules in python 3.5. While I can usually install and import packages using sudo pip install {package}, I can't seem to figure out how to import my own files.</p>
<p>I made a test.py file with a single definition to test. I saved it to the site-packages folder. I can't seem to import from there. I need help understanding how to import files.</p>
<p>I read online about possibly using sys.path however, I don't know how that works.</p> | 1 |
Draw a custom shape in android using XML | <p>I am adding a custom marker to the android map view. here is the image I am using for it.It looks like as more markers are placed say about 100 the entire app is getting slow. Here is the image I am using for that.</p>
<p><a href="https://i.stack.imgur.com/79Qtw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/79Qtw.png" alt="enter image description here"></a></p>
<p>Instead of using this image, I am planning to draw this image as a shape in XML. How to do that? </p>
<p>Also I am following <a href="http://www.nasc.fr/android/android-using-layout-as-custom-marker-on-google-map-api/" rel="noreferrer">this tutorial</a> to display a custom marker. Is this custom drawing delaying the app? </p>
<p>Whats the best way to do it?</p> | 1 |
Sending HTTP GET request using urllib | <p>I am trying to send HTTP <strong>GET</strong> request using urllib/urllib2 with some data.</p>
<p>If we set some value of data param in urllib2.urlopen(url, data) the request object is changed to send POST request instead of GET. </p>
<p>Is there any way to achieve this? Standard or Hack?</p>
<p>Code snippet,</p>
<pre><code>import requests
import urllib
query = urllib.urlencode({'query':'["=", ["fact", "role"], "storage"]'})
# using request object
print 'Output 1.'
response = requests.get("http://localhost:8082/v3/nodes", data=query)
print response.json()
print
# using urllib object
print 'Output 2.'
resp = urllib.urlopen('http://localhost:8082/v3/nodes', data=query)
print resp.read()
</code></pre>
<p>Output:</p>
<pre><code>Output 1.
[{u'deactivated': None, u'facts_timestamp': u'2016-02-04T14:06:07.269Z', u'name': u'node_xx_11', u'report_timestamp': None, u'catalog_timestamp': u'2016-02-04T14:06:16.958Z'}, {u'deactivated': None, u'facts_timestamp': u'2016-02-04T14:06:05.865Z', u'name': u'node_xx_12', u'report_timestamp': None, u'catalog_timestamp': u'2016-02-04T14:06:13.614Z'}]
Output 2.
The POST method is not allowed for /v3/nodes
</code></pre>
<p>For the
References I have gone through,</p>
<p><a href="https://docs.python.org/2/library/urllib2.html#urllib2.urlopen" rel="nofollow">https://docs.python.org/2/library/urllib2.html#urllib2.urlopen</a></p>
<p><a href="https://docs.python.org/2/library/urllib2.html#urllib2.Request.add_data" rel="nofollow">https://docs.python.org/2/library/urllib2.html#urllib2.Request.add_data</a></p>
<p>This is not the road block for me, as I am able to use requests module for sending the data with <strong>GET</strong> request type. Curiosity is the reason of this post.</p> | 1 |
Exclude files from git svn clone | <p>I'm migrating an SVN repo to Git and I have 7000+ binary files I would like to exclude from being imported and becoming part of the Git history from the start, as opposed to cleaning them up after (ref this <a href="https://stackoverflow.com/questions/34777228/convert-git-rm-to-git-rm-cached">question</a>). The location of the files doesn't follow a very regular pattern so I'd have to supply a rather long list of locations to git, and I have ~8000 commits to take into consideration. </p>
<p><strong>If my goal is to avoid bloating the repo with unnecessary files, what is the best approach to do that ?</strong></p>
<p>Is there a way I can exclude these from the start, perhaps as a flag to git svn clone ? Would adding them to a <code>.gitignore</code> before clone prevent them from being added ? </p>
<p>The other option would be to import all, then rewrite the whole history with <code>git filter-branch</code> to remove all those files before sharing the repo with others.</p> | 1 |
How to send html email line by line using google apps script and google sheet data | <p>I have a script to send an email line-by-line. The problem I have is that I cannot use the data in the current line iteration in an email template. I know how to call functions from the template though in this case I cannot call the function that is being evaluated.</p>
<p>My solution was to create another function that would loop through the data again and send the line instance in an email then break. The problem is that now it takes to long to loop through the lines twice when im sure it can be done once.</p>
<p>I hope i made sense.</p>
<p><strong>Code.gs</strong></p>
<pre><code>function sendMail() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('EmailList');
// get the data as an array
var data = sheet.getDataRange().getValues();
// Loop over each line
for (var i = 1; i < data.length; i+=1) {
// Check the status of the email
if (data[i][4] != 'Sent') {
// get html file content
var html = HtmlService.createTemplateFromFile('Index').evaluate().getContent();
// send the email
MailApp.sendEmail({
to: data[i][2],
subject: 'Hi ' + data[i][0],
htmlBody: html
});
// Set the status to sent
sheet.getRange(i + 1,5).setValue('Sent');
}
} // end for
} // end function sendMail
function getData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('EmailList');
// get the data as an array
var data = sheet.getDataRange().getValues();
// Loop over each line
for (var i = 1; i < data.length; i+=1) {
// Check the status of the email
if (data[i][4] != 'Sent') {
var firstName = data[i][0];
var lastName = data[i][1];
var email = data[i][2];
var message = data[i][3];
break;
}
} // end for
var returnData = [firstName, lastName, email, message];
return returnData;
} // end function getData
</code></pre>
<p><strong>Index.html</strong></p>
<pre><code><!DOCTYPE html>
<html>
<head>
<base target="_top">
<? var data = getData(); ?>
</head>
<body>
Hi <?= data[0];?> <?= data[1];?> , with email address <?= data[2];?>
I have a message for you:
<?= data[3];?>
</body>
</html>
</code></pre> | 1 |
C Program - Shifting Elements in an array | <p>"Write a program that allows a user to input an integer for the size of an array. Using Malloc is recommended. Randomly generate an integer for each element of the array. Next, creating a funcion to rotate the array. Rotation of the array means that each element is shifted right or left by one index, and the last element of the array is also moved to the first place"</p>
<p>Example: 31 83 91</p>
<p>Which direction to shift and how many times?- Left</p>
<p>How many times would you like to shift? 2</p>
<p>End Result: 91 31 83</p>
<p>Currently my code. It's not shifting. </p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int main(){
int i, temp, swapped;
int SlotNumber;
int *ptr;
char direction;
int ShiftAmount;
printf("How many slots would you like in your array?\n");
scanf("%d", &SlotNumber);
for(i=0;i<SlotNumber;i++){
printf("%d \t", rand());
}
ptr = (int *)malloc(SlotNumber*sizeof(int));
printf("\nWhich direction would you like to shift it to? R/L?\n");
scanf(" %c", &direction);
printf("\nHow many times would you like to shift?\n");
scanf("%d", &ShiftAmount);
if((direction=='R')||(direction=='r')){
while(1){
swapped = 0;
for(i=0;i<ptr+1;i++){
if(ptr[1]>ptr[i+ShiftAmount]){
int temp = ptr[i];
ptr[i] = ptr[i+ShiftAmount];
ptr[i+ShiftAmount] =temp;
swapped = 1;
}
}
if(swapped == 0);
break;
}
}
printf("\nNewList\n");
for(i=0;i<ptr;i++){
printf("%d \t",ptr[i]);
}
return 0;
}
</code></pre> | 1 |
How to use JNDI DataSource provided by WebLogic 12.2.1 in Spring? | <p>I created a JNDI connection with the following Values:</p>
<p>i selected <code>Generic Data Source</code> option</p>
<p><strong>Name</strong>: jdbc/sampleDataSource</p>
<p><strong>JNDI Name</strong>: jdbc/sampleDataSource</p>
<p><strong>Spring Config File:</strong></p>
<p><code><jee:jndi-lookup id="dataSource" jndi-name="jdbc/sampleDataSource" /></code></p>
<p>I'm getting below error.</p>
<pre><code>Error An error occurred during activation of changes, please see the log for details.
Error javax.naming.NameNotFoundException: While trying to lookup 'jdbc.sampleDataSource' didn't find subcontext 'jdbc'. Resolved ''; remaining name 'jdbc/sampleDataSource'
Error While trying to lookup 'jdbc.sampleDataSource' didn't find subcontext 'jdbc'. Resolved ''; remaining name 'jdbc/sampleDataSource'
</code></pre>
<p>I was unable to resolve it.
How do i configure in Spring 4.
Any addition jar file is required. Please help on this.</p> | 1 |
Jackson. Deserialize missing properties as empty Optional<T> | <p>Let's say I have a class like this:</p>
<pre class="lang-java prettyprint-override"><code>public static class Test {
private Optional<String> something;
public Optional<String> getSomething() {
return something;
}
public void setSomething(Optional<String> something) {
this.something = something;
}
}
</code></pre>
<p>If I deserialize this JSON, I get an empty Optional:</p>
<pre class="lang-json prettyprint-override"><code>{"something":null}
</code></pre>
<p>But if property is missing (in this case just empty JSON), I get null instead of <code>Optional<T></code>. I could initialize fields by myself of course, but I think it would be better to have one mechanism for <code>null</code> and missing properties. So is there a way to make jackson deserialize missing properties as empty <code>Optional<T></code>?</p> | 1 |
ASP.NET CORE 1.0, AppSettings from another assembly | <p>I have an application splittet into two projects: a web application and a class library. The <code>Startup</code> is only in the web application:</p>
<pre><code>var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
</code></pre>
<p>I wanna have my appsettings.json in that class library and being loaded from there. Is that possible? How can I do that?</p> | 1 |
read unicode string from text file in UWP app | <p>in Windows 10 app I try to read string from .txt file and set the text to RichEditBox:</p>
<p>Code variant 1:</p>
<pre><code>var read = await FileIO.ReadTextAsync(file, Windows.Storage.Streams.UnicodeEncoding.Utf8);
txt.Document.SetText(Windows.UI.Text.TextSetOptions.None, read);
</code></pre>
<p>Code variant 2:</p>
<pre><code>var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
ulong size = stream.Size;
using (var inputStream = stream.GetInputStreamAt(0))
{
using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream))
{
dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
uint numBytesLoaded = await dataReader.LoadAsync((uint)size);
string text = dataReader.ReadString(numBytesLoaded);
txt.Document.SetText(Windows.UI.Text.TextSetOptions.FormatRtf, text);
}
}
</code></pre>
<p>On some files I have this error - "No mapping for the Unicode character exists in the target multi-byte code page"</p>
<p>I found one solution:</p>
<pre><code>IBuffer buffer = await FileIO.ReadBufferAsync(file);
DataReader reader = DataReader.FromBuffer(buffer);
byte[] fileContent = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(fileContent);
string text = Encoding.UTF8.GetString(fileContent, 0, fileContent.Length);
txt.Document.SetText(Windows.UI.Text.TextSetOptions.None, text);
</code></pre>
<p>But with this code the text looks like question marks in rhombus.</p>
<p>How I can read and display same text files in normal encoding?</p> | 1 |
Visual studio Code, open current file in External Application | <p>I am trying to write a simple extension in Visual Studio Code, the extension will simply take the current file and launch it in external application. How can we do that?</p> | 1 |
Save file with Russian letters in the file name | <p>I have this Python script that takes the info of a webpage and then saves this info to a text file. But the name of this text file changes from time to time and it can changes to Cyrillic letters sometimes, and some times Korean letters.</p>
<p>The problem is that say I'm trying to save the file with the name "бореиская" then the name will appear very weird when I'm viewing it in Windows.</p>
<p>I'm guessing I need to change some encoding at some places. But the name is being sent to the <code>open()</code> function:</p>
<pre><code>server = "бореиская"
file = open("eu_" + server + ".lua", "w")
</code></pre>
<p>I am, earlier on, taking the server variable from an array that already has all the names in it.</p>
<p>But as previously mentioned, in Windows, the names appear with some very weird characters.</p> | 1 |
How to create tabs inside Action Bar? | <p>As shown in the picture</p>
<p><a href="https://i.stack.imgur.com/xZkNe.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xZkNe.jpg" alt=""></a></p>
<p>Is it possible to create Tabs inside <code>ActionBar</code>? </p>
<p>I have managed only to create <code>TabHost</code> but it goes under the <code>ActionBar</code> and not inside it (I think that is obvious that tabs are inside cause there is a perfect flow from <code>ActionBar</code> title to tabs).</p> | 1 |
Assign module function to ActiveX command button DIRECTLY | <p>In VBA for Excel, how do I assign an existing function or sub, say myFun(), in a module to a newly added ActiveX click button directly? </p>
<p>I understand I can do the following on the worksheet code page where the ActiveX command (click) button is located.</p>
<pre><code>Private Sub myFun_Click()
myFun()
End Sub
</code></pre>
<p>By "directly" I mean naming the button "myFun" and point the button directly to the function myFun() with having to placing myFun() in another sub as shown above.</p> | 1 |
Howto focus bootstrap-select element via JavaScript | <p>I'm using a Bootstrap Select Dropdown in Spring:</p>
<pre><code><form:select name="participant-picker" multiple="false" path="participants" cssClass="selectpicker" data-live-search="true" title="Teilnehmer..." data-width="100%">
<form:options
items="${participants}"
itemValue="enrolmentNumber"
itemLabel="description" />
</form:select>
</code></pre>
<p>After execution:</p>
<pre><code><select class="selectpicker" title="Teilnehmer..." name="participant-picker" data-width="100%" data-live-search="true">
<option value="1234687">Nachname121, Vorname122 (1234687)</option>
<option value="1234688">Nachname122, Vorname123 (1234688)</option>
</select>
</code></pre>
<p>Please keep in mind, that Bootstrap dynamically adds multiple divs for the dropdown and other stuff.</p>
<p>Now i want to dynamically set the focus to this select element. This is not working:</p>
<pre><code>$('select[name=participant-picker]').focus()
</code></pre> | 1 |
Detecting Application class running on main process on a multiprocess app | <p>I have an Android app that extends the <code>Application</code> class and has many app components (services, activities and broadcast receivers) running along three different process.</p>
<p>Each process will instantiate the <code>Application</code> class as soon as it is started. So I've been looking for how can I check inside the <code>Application</code> class code, if the instance is owned by the main app process but I have not been able to find it anything.</p>
<p>My manifest looks like this:</p>
<pre><code><application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:name=".MyApplication"
android:theme="@style/AppTheme" >
<activity
android:name="...">
...
</activity>
<activity
android:name="...">
...
</activity>
<service android:name="..." >
</service>
<service android:name="..."
android:process=":SecondProcess" >
</service>
<service android:name="..."
android:process=":ThirdProcess" >
</service>
</code></pre>
<p>Next is my <code>Application</code> class implementation:</p>
<pre><code>public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
if (is this instance being ran on the main process?) {
// Do something
}
}
}
</code></pre>
<p>Does anyone know how to check if the instance is running on the main process?</p> | 1 |
How does one link NASM program to libc via ld? | <p>I have a following program for NASM (ArchLinux i686)</p>
<pre><code>SECTION .data
LC1: db "library call", 0
SECTION .text
extern exit
extern printf
;global main
;main:
global _start
_start:
push LC1
call printf
push 0
call exit
</code></pre>
<p>Which is assembled with command: </p>
<pre><code>nasm -f elf libcall.asm
</code></pre>
<p>If to comment two lines with <code>_start</code> and uncomment two lines with <code>main</code>, then assemble and link with the command:</p>
<pre><code>gcc libcall.o -o libcall
</code></pre>
<p>Then the program runs OK. But if to assemble the code with <code>_start</code> entry point and link with the command:</p>
<pre><code>ld libcall.o -o libcall -lc
</code></pre>
<p>Then after launching the program in bash (via the command <code>./libcall</code>) the following error message is returned:</p>
<pre><code>bash: ./libcall: No such file or directory
</code></pre>
<p>Although the <code>libcall</code> file does exist. <code>objdump</code> shows the following:</p>
<pre><code>[al libcall ]$ objdump -d libcall
libcall: file format elf32-i386
Disassembly of section .plt:
08048190 <printf@plt-0x10>:
8048190: ff 35 78 92 04 08 pushl 0x8049278
8048196: ff 25 7c 92 04 08 jmp *0x804927c
804819c: 00 00 add %al,(%eax)
...
080481a0 <printf@plt>:
80481a0: ff 25 80 92 04 08 jmp *0x8049280
80481a6: 68 00 00 00 00 push $0x0
80481ab: e9 e0 ff ff ff jmp 8048190 <printf@plt-0x10>
080481b0 <exit@plt>:
80481b0: ff 25 84 92 04 08 jmp *0x8049284
80481b6: 68 08 00 00 00 push $0x8
80481bb: e9 d0 ff ff ff jmp 8048190 <printf@plt-0x10>
Disassembly of section .text:
080481c0 <_start>:
80481c0: 68 88 92 04 08 push $0x8049288
80481c5: e8 d6 ff ff ff call 80481a0 <printf@plt>
80481ca: 6a 00 push $0x0
80481cc: e8 df ff ff ff call 80481b0 <exit@plt>
</code></pre>
<p>How the NASM assembly code should properly be linked with to <code>libc</code> via <code>ld</code>?</p> | 1 |
Scroll element to the top of an overflowed parent container | <p>For some reason, I feel that it should be easy, but I can't get it to work and I can't seem to find a solution online.</p>
<p>I have a container (#container) set to overflow: scroll. Inside are 3 divs, and they all have the same height (100%) as the parent container. Each one of these divs contains a link.</p>
<p>Let's say that you scroll down and get half way through the second div, you should then be able to click the link in the second div, which would trigger the parent div to scroll up to the top of the container.</p>
<p>This is my code:</p>
<p><strong>HTML</strong></p>
<pre><code><div id="container">
<div>
<a href="#">link 1</a>
</div>
<div>
<a href="#">link 2</a>
</div>
<div>
<a href="#">link 3</a>
</div>
</div>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>#container {
position: absolute;
height: 100%;
overflow: scroll;
}
div {
height: 100%;
width: 100%;
}
</code></pre>
<p><strong>jQuery</strong></p>
<pre><code>$("a").click(function() {
// triggers parent div to scroll up to the parent container
});
</code></pre>
<p>I managed to use scrollTop to scroll to the div, but not to line up the div with the parent container.</p>
<p>I hope this makes sense. Thank you for your help.</p>
<p><strong>EDIT:</strong></p>
<p>Based on pilar1347's answer below, here's a Fiddle with the code in action: <a href="https://jsfiddle.net/julienfrog/w2oqsqc8/2/" rel="nofollow">https://jsfiddle.net/julienfrog/w2oqsqc8/2/</a></p> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.