From the fine manual.
You must own the table to use ALTER TABLE.
Or be a database superuser.
ERROR: must be owner of relation contact
PostgreSQL error messages are usually spot on. This one is spot on.
Click the items in the list view. Add a button that will edit the selected items. Add the code
try
{
LSTDEDUCTION.SelectedItems[0].SubItems[1].Text = txtcarName.Text;
LSTDEDUCTION.SelectedItems[0].SubItems[0].Text = txtcarBrand.Text;
LSTDEDUCTION.SelectedItems[0].SubItems[2].Text = txtCarName.Text;
}
catch{}
Off the top of my head:
$('#content').height(
$(window).height() - $('#header').height() - $('#footer').height()
);
Is that what you mean?
You can specify the type of a variable before it to force its type. It's called (dynamic) casting (more information is here):
$string = "1654"
$integer = [int]$string
$string + 1
# Outputs 16541
$integer + 1
# Outputs 1655
As an example, the following snippet adds, to each object in $fileList
, an IntVal
property with the integer value of the Name
property, then sorts $fileList
on this new property (the default is ascending), takes the last (highest IntVal
) object's IntVal
value, increments it and finally creates a folder named after it:
# For testing purposes
#$fileList = @([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" })
# OR
#$fileList = New-Object -TypeName System.Collections.ArrayList
#$fileList.AddRange(@([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" })) | Out-Null
$highest = $fileList |
Select-Object *, @{ n = "IntVal"; e = { [int]($_.Name) } } |
Sort-Object IntVal |
Select-Object -Last 1
$newName = $highest.IntVal + 1
New-Item $newName -ItemType Directory
Sort-Object IntVal
is not needed so you can remove it if you prefer.
[int]::MaxValue = 2147483647
so you need to use the [long]
type beyond this value ([long]::MaxValue = 9223372036854775807
).
First of all, this line
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()
You're mixing HTML and JavaScript. It doesn't work like that. Get rid of the .click()
there.
If you read the JavaScript you've got there, document.getElementById('foo')
it's looking for an HTML element with an ID of foo
. You don't have one. Give your image that ID:
<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
Alternatively, you could throw the JS in a function and put an onclick in your HTML:
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" onclick="myfunction()" />
I suggest you do some reading up on JavaScript and HTML though.
The others are right about needing to move the <img>
above the JS click binding too.
Simple (one-liner, no error checking, no wait for response) solution I've found so far:
(new WebClient()).UploadStringAsync(new Uri(Address), dataString);?
Use with caution!
queNumMin = 23;
queNumMax= 26;
result = 0;
for (let index = this.queNumMin; index <= this.queNumMax; index++) {
this.result = index
console.log( this.result);
}
Range min and max number
import {DomSanitizationService} from '@angular/platform-browser';
@Component({
templateUrl: 'build/pages/veeu/veeu.html'
})
export class VeeUPage {
trustedURL:any;
static get parameters() {
return [NavController, App, MenuController,
DomSanitizationService];
}
constructor(nav, app, menu, sanitizer) {
this.app = app;
this.nav = nav;
this.menu = menu;
this.sanitizer = sanitizer;
this.trustedURL = sanitizer.bypassSecurityTrustUrl(this.mediaItems[1].url);
}
}
<iframe [src]='trustedURL' width="640" height="360" frameborder="0"
webkitallowfullscreen mozallowfullscreen allowfullscreen>
</iframe>
User property binding instead of function.
I think this would work
moment().weekday(); //if today is thursday it will return 4
For those using Telerik as mentioned by Ovar, make sure you wrap your javascript in
<telerik:RadScriptBlock ID="radSript1" runat="server">
<script type="text/javascript">
//Your javascript
</script>
</telerik>
Since Telerik doesn't recognize <%# %> when looking for an element and <%= %> will give you an error if your javascript code isn't wrapped.
DECLARE @TABLE TABLE
(RowNo INT,ScripName VARCHAR(10),ScripCode VARCHAR(10)
,Price VARCHAR(10))
INSERT INTO @TABLE VALUES
(1,'20 MICRONS ','533022','39')
SELECT ColumnName,ColumnValue from @Table
Unpivot(ColumnValue For ColumnName IN (ScripName,ScripCode,Price)) AS H
Here is an example of correct usage of $this and self for non-static and static member variables:
<?php
class X {
private $non_static_member = 1;
private static $static_member = 2;
function __construct() {
echo $this->non_static_member . ' '
. self::$static_member;
}
}
new X();
?>
I had a similar situation with the 'An error occurred while executing the command definition' error. I had some views which were grabbing from another db which used current user security. The second db did not allow the login for the user of the first db causing this issue to occur. I added the db login to the server it was trying to get to from the original server and this fixed the issue. Check your views and see if there are any linked dbs which have different security than the db you are logging onto originally.
I believe that what you want is
int[] k = new int[3];
if (k != null) { // Note, != and not == as above
System.out.println(k.length);
}
You newed it up so it was never going to be null.
Finally I imported my Gradle project. These are the steps:
JAVA_HOME
to JDK 8 (it was 7th previously) as I had
figured out by experiments that Gradle Wrapper could process the
project with JDK 8 only. org.gradle.java.home
variable) in windows user .gradle directory
as, I guessed, it didn't bring any additional value to Gradle.Cleanest and fastest way (ES6)
const apps = [
{id:1, name:'Jon'},
{id:2, name:'Dave'},
{id:3, name:'Joe'}
]
//remove item with id=2
const itemToBeRemoved = {id:2, name:'Dave'}
apps.splice(apps.findIndex(a => a.id === itemToBeRemoved.id) , 1)
//print result
console.log(apps)
_x000D_
Update: if any chance item doesn't exist in the look up array please use below solution, updated based on MaxZoom's comment
const apps = [
{id:1, name:'Jon'},
{id:3, name:'Joe'}
]
//remove item with id=2
const itemToBeRemoved = {id:2, name:'Dave'}
const findIndex = apps.findIndex(a => a.id === itemToBeRemoved.id)
findIndex !== -1 && apps.splice(findIndex , 1)
//print result
console.log(apps)
_x000D_
here's non-paste methods
awk
awk 'BEGIN {OFS=" "}{
getline line < "file2"
print $0,line
} ' file1
Bash
exec 6<"file2"
while read -r line
do
read -r f2line <&6
echo "${line}${f2line}"
done <"file1"
exec 6<&-
<?php if($condition) : ?>
<a href="http://yahoo.com">This will only display if $condition is true</a>
<?php endif; ?>
By request, here's elseif and else (which you can also find in the docs)
<?php if($condition) : ?>
<a href="http://yahoo.com">This will only display if $condition is true</a>
<?php elseif($anotherCondition) : ?>
more html
<?php else : ?>
even more html
<?php endif; ?>
It's that simple.
The HTML will only be displayed if the condition is satisfied.
According to @Enno Gröper 's post, I've tried the SSLContext constructor and it works well on my machine. code as below:
import ssl
ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
urllib2.urlopen("https://your-test-server.local", context=ctx)
if you need opener, just added this context like:
opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx))
NOTE: all above test environment is python 2.7.12. I use PROTOCOL_SSLv23 here since the doc says so, other protocol might also works but depends on your machine and remote server, please check the doc for detail.
I've not tried to run below, though. I think this's a tricky way.
map{print $_;} @array;
Normally you'd just stick the code in Page_Load
in your .aspx
page's code-behind.
if (someVar) {
Item1.Visible = true;
Item2.Visible = false;
} else {
Item1.Visible = false;
Item2.Visible = true;
}
This assumes you've got Item1
and Item2
laid out on the page already.
You could do this with an INSTEAD OF INSERT
trigger on the table, that checks for the existance of the row and then updates/inserts depending on whether it exists already. There is an example of how to do this for SQL Server 2000+ on MSDN here:
CREATE TRIGGER IO_Trig_INS_Employee ON Employee
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON
-- Check for duplicate Person. If no duplicate, do an insert.
IF (NOT EXISTS (SELECT P.SSN
FROM Person P, inserted I
WHERE P.SSN = I.SSN))
INSERT INTO Person
SELECT SSN,Name,Address,Birthdate
FROM inserted
ELSE
-- Log attempt to insert duplicate Person row in PersonDuplicates table.
INSERT INTO PersonDuplicates
SELECT SSN,Name,Address,Birthdate,SUSER_SNAME(),GETDATE()
FROM inserted
-- Check for duplicate Employee. If no duplicate, do an insert.
IF (NOT EXISTS (SELECT E.SSN
FROM EmployeeTable E, inserted
WHERE E.SSN = inserted.SSN))
INSERT INTO EmployeeTable
SELECT EmployeeID,SSN, Department, Salary
FROM inserted
ELSE
--If duplicate, change to UPDATE so that there will not
--be a duplicate key violation error.
UPDATE EmployeeTable
SET EmployeeID = I.EmployeeID,
Department = I.Department,
Salary = I.Salary
FROM EmployeeTable E, inserted I
WHERE E.SSN = I.SSN
END
use this filter:
(dns.flags.response == 0) and (ip.src == 159.25.78.7)
what this query does is it only gives dns queries
originated from your ip
you can use this command by getting your data. this will extract your data...
select * from employees where to_char(es_date,'dd/mon/yyyy')='17/jun/2003';
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same timeJust use string methods .replace()
if they occur throughout, or .strip()
if they only occur at the start and/or finish:
a = '"sajdkasjdsak" "asdasdasds"'
a = a.replace('"', '')
'sajdkasjdsak asdasdasds'
# or, if they only occur at start and end...
a = a.strip('\"')
'sajdkasjdsak" "asdasdasds'
# or, if they only occur at start...
a = a.lstrip('\"')
# or, if they only occur at end...
a = a.rstrip('\"')
$(document).ready(function () {
$(".trigger").click(function () {
$("#sidebar").toggle("fast");
$("#sidebar").toggleClass("active");
return false;
});
});
<div>
<a class="trigger" href="#">
<img id="icon-menu" alt='menu' height='50' src="Images/Push Pin.png" width='50' />
</a>
</div>
<div id="sidebar">
</div>
Instead #sidebar give the id of ur div.
The vertical-align css attribute doesn't do what you expect unfortunately. This article explains 2 ways to vertically align an element using css.
Simplest answer could be this one :
UIPanGestureRecognizer * pan1 = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(moveObject:)];
pan1.minimumNumberOfTouches = 1;
[image1 addGestureRecognizer:pan1];
-(void)moveObject:(UIPanGestureRecognizer *)pan;
{
image1.center = [pan locationInView:image1.superview];
}
DateFormatSymbols class provides methods for our ease use.
To get short month strings. For example: "Jan", "Feb", etc.
getShortMonths()
To get month strings. For example: "January", "February", etc.
getMonths()
Sample code to return month string in mmm format,
private static String getShortMonthFromNumber(int month){
if(month<0 || month>11){
return "";
}
return new DateFormatSymbols().getShortMonths()[month];
}
Use the apache commons cli if you plan on extending that past a single arg.
"The Apache Commons CLI library provides an API for parsing command line options passed to programs. It's also able to print help messages detailing the options available for a command line tool."
Commons CLI supports different types of options:
As per the documentation on the return
statement, return
may only occur syntactically nested in a function definition. The same is true for yield
.
If You want to use only sed to extract IP address:
ifconfig eth0 2>/dev/null sed -n 's/.*[[:space:]]\([[:digit:]][[:digit:]]*\.[[:digit:]][[:digit:]]*\.[[:digit:]][[:digit:]]*\.[[:digit:]][[:digit:]]*\).*/\1/p'
Building on the previous answer, this bash one-liner should give you what you're looking for. It displays the git blame history for a particular line of a particular file, through the last 5 revisions:
LINE=10 FILE=src/options.cpp REVS=5; for commit in $(git rev-list -n $REVS HEAD $FILE); do git blame -n -L$LINE,+1 $commit -- $FILE; done
In the output of this command, you might see the content of the line change, or the line number displayed might even change, for a particular commit.
This often indicates that the line was added for the first time, after that particular commit. It could also indicate the line was moved from another part of the file.
Comments work fine in any of the usual Java/Groovy forms, but you can't currently use groovydoc
to process your Jenkinsfile
(s).
First, groovydoc
chokes on files without extensions with the wonderful error
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:498)
at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109)
at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1967)
at org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDocAssembler.<init>(SimpleGroovyClassDocAssembler.java:67)
at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.parseGroovy(GroovyRootDocBuilder.java:131)
at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.getClassDocsFromSingleSource(GroovyRootDocBuilder.java:83)
at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.processFile(GroovyRootDocBuilder.java:213)
at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.buildTree(GroovyRootDocBuilder.java:168)
at org.codehaus.groovy.tools.groovydoc.GroovyDocTool.add(GroovyDocTool.java:82)
at org.codehaus.groovy.tools.groovydoc.GroovyDocTool$add.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at org.codehaus.groovy.tools.groovydoc.Main.execute(Main.groovy:214)
at org.codehaus.groovy.tools.groovydoc.Main.main(Main.groovy:180)
... 6 more
... and second, as far as I can tell Javadoc-style commments at the start of a groovy
script are ignored. So even if you copy/rename your Jenkinsfile
to Jenkinsfile.groovy
, you won't get much useful output.
I want to be able to use a
/**
* Document my Jenkinsfile's overall purpose here
*/
comment at the start of my Jenkinsfile. No such luck (yet).
groovydoc
will process classes and methods defined in your Jenkinsfile
if you pass -private
to the command, though.
A simple solution is:
if (newStr4.startsWith("Mon") || newStr4.startsWith("Tue") || newStr4.startsWith("Wed"))
// ... you get the idea ...
A fancier solution would be:
List<String> days = Arrays.asList("SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT");
String day = newStr4.substring(0, 3).toUpperCase();
if (days.contains(day)) {
// ...
}
Replace this line:
count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, 0)) AS comments
With this one:
coalesce(sum(ccc_news_comments.id = 'approved'), 0) comments
Recursively remove null, undefined, empty objects and empty arrays, returning a copy (ES6 version)
export function skipEmpties(dirty) {
let item;
if (Array.isArray(dirty)) {
item = dirty.map(x => skipEmpties(x)).filter(value => value !== undefined);
return item.length ? item : undefined;
} else if (dirty && typeof dirty === 'object') {
item = {};
Object.keys(dirty).forEach(key => {
const value = skipEmpties(dirty[key]);
if (value !== undefined) {
item[key] = value;
}
});
return Object.keys(item).length ? item : undefined;
} else {
return dirty === null ? undefined : dirty;
}
}
Actually, VisualVM can process application core dump.
Just invoke "File/Add VM Coredump" and will add a new application in the application explorer. You can then take thread dump or heap dump of that JVM.
Scripts are raw java embedded in the page code, and if you declare variables in your scripts, then they become local variables embedded in the page.
In contrast, JSTL works entirely with scoped attributes, either at page
, request
or session
scope. You need to rework your scriptlet to fish test
out as an attribute:
<c:set var="test" value="test1"/>
<%
String resp = "abc";
String test = pageContext.getAttribute("test");
resp = resp + test;
pageContext.setAttribute("resp", resp);
%>
<c:out value="${resp}"/>
If you look at the docs for <c:set>
, you'll see you can specify scope
as page
, request
or session
, and it defaults to page
.
Better yet, don't use scriptlets at all: they make the baby jesus cry.
I always initialise them as NULL
.
I always use string.IsNullOrEmpty(someString)
to check it's value.
Simple.
You enter the
if (!(cin >> input_var))
statement if an error occurs when taking the input from cin. If an error occurs then an error flag is set and future attempts to get input will fail. That's why you need
cin.clear();
to get rid of the error flag. Also, the input which failed will be sitting in what I assume is some sort of buffer. When you try to get input again, it will read the same input in the buffer and it will fail again. That's why you need
cin.ignore(10000,'\n');
It takes out 10000 characters from the buffer but stops if it encounters a newline (\n). The 10000 is just a generic large value.
You could also use a URI template. If you structured your request into a restful URL Spring could parse the provided value from the url.
HTML
<li>
<a id="byParameter"
class="textLink" href="<c:url value="/mapping/parameter/bar />">By path, method,and
presence of parameter</a>
</li>
Controller
@RequestMapping(value="/mapping/parameter/{foo}", method=RequestMethod.GET)
public @ResponseBody String byParameter(@PathVariable String foo) {
//Perform logic with foo
return "Mapped by path + method + presence of query parameter! (MappingController)";
}
Just add 360° if the answer from atan2 is less than 0°.
With visibility:hidden
the object still takes up vertical height on the page. With display:none
it is completely removed. If you have text beneath an image and you do display:none
, that text will shift up to fill the space where the image was. If you do visibility:hidden the text will remain in the same location.
As a general rule use encodeURIComponent
. Don't be scared of the long name thinking it's more specific in it's use, to me it's the more commonly used method. Also don't be suckered into using encodeURI because you tested it and it appears to be encoding properly, it's probably not what you meant to use and even though your simple test using "Fred" in a first name field worked, you'll find later when you use more advanced text like adding an ampersand or a hashtag it will fail. You can look at the other answers for the reasons why this is.
You can use Recordmp3js from GitHub to achieve your requirements. You can record from user's microphone and then get the file as an mp3. Finally upload it to your server.
I used this in my demo. There is a already a sample available with the source code by the author in this location : https://github.com/Audior/Recordmp3js
The demo is here: http://audior.ec/recordmp3js/
But currently works only on Chrome and Firefox.
Seems to work fine and pretty simple. Hope this helps.
You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:
([0-9]+)\s+((\bseconds\b)|(\bminutes\b))
Without those you were either matching a number followed by seconds OR just the word minutes
In this scenario, the outer <div>
has a width and height of 90%. The inner div>
has a width of 100% of its parent. Both scale when re-sizing the window.
HTML
<div>
<div>Hello there</div>
</div>
CSS
html, body {
width: 100%;
height: 100%;
}
body > div {
width: 90%;
height: 100%;
background: green;
}
body > div > div {
width: 100%;
background: red;
}
Demo
.clearfix
is defined in less/mixins.less
. Right above its definition is a comment with a link to this article:
The article explains how it all works.
UPDATE: Yes, link-only answers are bad. I knew this even at the time that I posted this answer, but I didn't feel like copying and pasting was OK due to copyright, plagiarism, and what have you. However, I now feel like it's OK since I have linked to the original article. I should also mention the author's name, though, for credit: Nicolas Gallagher. Here is the meat of the article (note that "Thierry’s method" is referring to Thierry Koblentz’s “clearfix reloaded”):
This “micro clearfix” generates pseudo-elements and sets their
display
totable
. This creates an anonymous table-cell and a new block formatting context that means the:before
pseudo-element prevents top-margin collapse. The:after
pseudo-element is used to clear the floats. As a result, there is no need to hide any generated content and the total amount of code needed is reduced.Including the
:before
selector is not necessary to clear the floats, but it prevents top-margins from collapsing in modern browsers. This has two benefits:
It ensures visual consistency with other float containment techniques that create a new block formatting context, e.g.,
overflow:hidden
It ensures visual consistency with IE 6/7 when
zoom:1
is applied.N.B.: There are circumstances in which IE 6/7 will not contain the bottom margins of floats within a new block formatting context. Further details can be found here: Better float containment in IE using CSS expressions.
The use of
content:" "
(note the space in the content string) avoids an Opera bug that creates space around clearfixed elements if thecontenteditable
attribute is also present somewhere in the HTML. Thanks to Sergio Cerrutti for spotting this fix. An alternative fix is to usefont:0/0 a
.Legacy Firefox
Firefox < 3.5 will benefit from using Thierry’s method with the addition of
visibility:hidden
to hide the inserted character. This is because legacy versions of Firefox needcontent:"."
to avoid extra space appearing between thebody
and its first child element, in certain circumstances (e.g., jsfiddle.net/necolas/K538S/.)Alternative float-containment methods that create a new block formatting context, such as applying
overflow:hidden
ordisplay:inline-block
to the container element, will also avoid this behaviour in legacy versions of Firefox.
For the android dev minimalists: Log.getStackTraceString(exception)
You get this error if you have constrained T
to being a class
instead of writing listb.pop[0]
write
listb.pop()[0]
^
|
As far as I know, can't you just make it abstract?
class parent {
public:
virtual void handle_event(int something) const = 0 {
// boring default code
}
};
I thought I read on www.parashift.com that you can actually implement an abstract method. Which makes sense to me personally, the only thing it does is force subclasses to implement it, no one said anything about it not being allowed to have an implementation itself.
Your error looks like you are duplicating an already existing Primary Key in your DB. You should modify your sql code to implement its own primary key by using something like the IDENTITY keyword.
CREATE TABLE [DB] (
[DBId] bigint NOT NULL IDENTITY,
...
CONSTRAINT [DB_PK] PRIMARY KEY ([DB] ASC),
);
I have tried all methods mentioned in this page, but only below method worked well for me.
Cursor c=db.rawQuery("SELECT * FROM user WHERE idno='"+txtID.getText()+"'", null);
if(c.moveToFirst())
{
showMessage("Error", "Record exist");
}
else
{
// Inserting record
}
try {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
System.out.println("okay1");
FileInputStream fileInputStream = new FileInputStream("C:/Users/Kushan/eclipse-workspace/sureson.lk/src/main/webapp/js/back_end_response.js");
System.out.println("okay2");
if (fileInputStream != null){
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
engine.eval(reader);
System.out.println("okay3");
// Invocable javascriptEngine = null;
System.out.println("okay4");
Invocable invocableEngine = (Invocable)engine;
System.out.println("okay5");
int x=0;
System.out.println("invocableEngine is : "+invocableEngine);
Object object = invocableEngine.invokeFunction("backend_message",x);
System.out.println("okay6");
}
}catch(Exception e) {
System.out.println("erroe when calling js function"+ e);
}
Check it here :
https://stackoverflow.com/a/53644664/1084987
You can create something like if condition afterwards, like
if(!contains(array, obj)) add();
If you installed the SquashFS image you can run the script firstboot
. That will return OpenWrt to the defaults of when you flashed the router.
With your serial access just run firstboot and then power cycle the device.
If You have jar file then create bat file with:
java -jar NameOfJar.jar
Yes, you will have to implement the constructors that make sense for each derivation and then use the base
keyword to direct that constructor to the appropriate base class or the this
keyword to direct a constructor to another constructor in the same class.
If the compiler made assumptions about inheriting constructors, we wouldn't be able to properly determine how our objects were instantiated. In the most part, you should consider why you have so many constructors and consider reducing them to only one or two in the base class. The derived classes can then mask out some of them using constant values like null
and only expose the necessary ones through their constructors.
In C#4 you could specify default parameter values and use named parameters to make a single constructor support multiple argument configurations rather than having one constructor per configuration.
From SQL database get enum like:
SqlDataReader dr = selectCmd.ExecuteReader();
while (dr.Read()) {
EnumType et = (EnumType)Enum.Parse(typeof(EnumType), dr.GetString(0));
....
}
Thank you Phil for your solution; in case someone ever gets in the same situation as me, here is a (more complex) variant:
---
# this is just to avoid a call to |default on each iteration
- set_fact:
postconf_d: {}
- name: 'get postfix default configuration'
command: 'postconf -d'
register: command
# the answer of the command give a list of lines such as:
# "key = value" or "key =" when the value is null
- name: 'set postfix default configuration as fact'
set_fact:
postconf_d: >
{{
postconf_d |
combine(
dict([ item.partition('=')[::2]|map('trim') ])
)
with_items: command.stdout_lines
This will give the following output (stripped for the example):
"postconf_d": {
"alias_database": "hash:/etc/aliases",
"alias_maps": "hash:/etc/aliases, nis:mail.aliases",
"allow_min_user": "no",
"allow_percent_hack": "yes"
}
Going even further, parse the lists in the 'value':
- name: 'set postfix default configuration as fact'
set_fact:
postconf_d: >-
{% set key, val = item.partition('=')[::2]|map('trim') -%}
{% if ',' in val -%}
{% set val = val.split(',')|map('trim')|list -%}
{% endif -%}
{{ postfix_default_main_cf | combine({key: val}) }}
with_items: command.stdout_lines
...
"postconf_d": {
"alias_database": "hash:/etc/aliases",
"alias_maps": [
"hash:/etc/aliases",
"nis:mail.aliases"
],
"allow_min_user": "no",
"allow_percent_hack": "yes"
}
A few things to notice:
in this case it's needed to "trim" everything (using the >-
in YAML and -%}
in Jinja), otherwise you'll get an error like:
FAILED! => {"failed": true, "msg": "|combine expects dictionaries, got u\" {u'...
obviously the {% if ..
is far from bullet-proof
in the postfix case, val.split(',')|map('trim')|list
could have been simplified to val.split(', ')
, but I wanted to point out the fact you will need to |list
otherwise you'll get an error like:
"|combine expects dictionaries, got u\"{u'...': <generator object do_map at ...
Hope this can help.
A modern and simple approach: pg-promise:
const pgp = require('pg-promise')(/* initialization options */);
const cn = {
host: 'localhost', // server name or IP address;
port: 5432,
database: 'myDatabase',
user: 'myUser',
password: 'myPassword'
};
// alternative:
// var cn = 'postgres://username:password@host:port/database';
const db = pgp(cn); // database instance;
// select and return a single user name from id:
db.one('SELECT name FROM users WHERE id = $1', [123])
.then(user => {
console.log(user.name); // print user name;
})
.catch(error => {
console.log(error); // print the error;
});
// alternative - new ES7 syntax with 'await':
// await db.one('SELECT name FROM users WHERE id = $1', [123]);
Using Google Play app signing feature & Google APIs integration in your app?
If you use Google Play app signing, Google re-signs your app. Thats how your signing-certificate fingerprint is given by Google Play App Signing as shown below:
Read more How to get Release SHA-1 (Signing-certificate fingerprint) if using 'Google Play app signing'
I was able to Do it using the U (Underline Tag)
u {
text-decoration: none;
position: relative;
}
u:after {
content: '';
width: 100%;
position: absolute;
left: 0;
bottom: 1px;
border-width: 0 0 1px;
border-style: solid;
}
<a href="" style="text-decoration:none">
<div style="text-align: right; color: Red;">
<u> Shop Now</u>
</div>
</a>
I found I had the same error. I was compiling a code with both lapack and blas. When I switched the order that the two libraries were called the error went away.
"LAPACK_LIB = -llapack -lblas" worked where "LAPACK_LIB = -lblas -llapack" gave the error described above.
Another option would be to use case_when
require(dplyr)
mutate(df, est = case_when(
b == 0 ~ (a - 5)/2.53,
TRUE ~ est
))
This solution becomes even more handy if more than 2 cases need to be distinguished, as it allows to avoid nested if_else
constructs.
you can probably ping the server via ajax inside javascript. The php file might look something like:
<?php
session_start();
$id = session_id();
echo $id;
?>
This will return you the current session id. Was this what you were looking for.
No. It is not possible to share the same port at a particular instant. But you can make your application such a way that it will make the port access at different instant.
You could do this
<div style="text-align:center;">
<div style="border:1px solid #000; display:inline-block;">Div 1</div>
<div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>
http://jsfiddle.net/jasongennaro/MZrym/
div
with text-align:center;
div
s a display:inline-block;
instead of a float
Best also to put that css in a stylesheet.
If this issue with HTTP error 407 happened to selected packages only then the problem is not in the proxy setting and internet connection. You even may expose your PC to the internet through NAT and still will face this problem. Typically at the same time you can download desired packages in browser. The only solution I find: delete the .gradle folder in your profile (not in the project). After that sync the project, it will take a long time but restore everything.
If you're using Bash, you can also do the following if, let's say, you want to remove the directory /home/wrong/dir/
from your PATH
variable:
PATH=`echo $PATH | sed -e 's/:\/home\/wrong\/dir\/$//'`
This can also happen if you don't declare a route component in your feature module. So for example:
feature.routing.module.ts:
...
{
path: '',
component: ViewComponent,
}
...
feature.module.ts:
imports: [ FeatureRoutingModule ],
declarations: [],
Notice the ViewComponent is not in the declarations array, whereas it should be.
In Angular you can define event listeners
like in the example below:
<!-- Here you can call public methods from parental component -->
<input (change)="method_name()">
When an array is passed to a method or function in PHP, it is passed by value unless you explicitly pass it by reference, like so:
function test(&$array) {
$array['new'] = 'hey';
}
$a = $array(1,2,3);
// prints [0=>1,1=>2,2=>3]
var_dump($a);
test($a);
// prints [0=>1,1=>2,2=>3,'new'=>'hey']
var_dump($a);
In your second question, $b
is not a reference to $a
, but a copy of $a
.
Much like the first example, you can reference $a
by doing the following:
$a = array(1,2,3);
$b = &$a;
// prints [0=>1,1=>2,2=>3]
var_dump($b);
$b['new'] = 'hey';
// prints [0=>1,1=>2,2=>3,'new'=>'hey']
var_dump($a);
There're two kind of Django "projects" that I have in my ~/projects/
directory, both have a bit different structure.:
Mostly private projects, but doesn't have to be. It usually looks like this:
~/projects/project_name/
docs/ # documentation
scripts/
manage.py # installed to PATH via setup.py
project_name/ # project dir (the one which django-admin.py creates)
apps/ # project-specific applications
accounts/ # most frequent app, with custom user model
__init__.py
...
settings/ # settings for different environments, see below
__init__.py
production.py
development.py
...
__init__.py # contains project version
urls.py
wsgi.py
static/ # site-specific static files
templates/ # site-specific templates
tests/ # site-specific tests (mostly in-browser ones)
tmp/ # excluded from git
setup.py
requirements.txt
requirements_dev.txt
pytest.ini
...
The main settings are production ones. Other files (eg. staging.py
,
development.py
) simply import everything from production.py
and override only necessary variables.
For each environment, there are separate settings files, eg. production, development. I some projects I have also testing (for test runner), staging (as a check before final deploy) and heroku (for deploying to heroku) settings.
I rather specify requirements in setup.py directly. Only those required for
development/test environment I have in requirements_dev.txt
.
Some services (eg. heroku) requires to have requirements.txt
in root directory.
setup.py
Useful when deploying project using setuptools
. It adds manage.py
to PATH
, so I can run manage.py
directly (anywhere).
I used to put these apps into project_name/apps/
directory and import them
using relative imports.
I put these templates and static files into global templates/static directory, not inside each app. These files are usually edited by people, who doesn't care about project code structure or python at all. If you are full-stack developer working alone or in a small team, you can create per-app templates/static directory. It's really just a matter of taste.
The same applies for locale, although sometimes it's convenient to create separate locale directory.
Tests are usually better to place inside each app, but usually there is many integration/functional tests which tests more apps working together, so global tests directory does make sense.
There is temporary directory in project root, excluded from VCS. It's used to store media/static files and sqlite database during development. Everything in tmp could be deleted anytime without any problems.
I prefer virtualenvwrapper
and place all venvs into ~/.venvs
directory,
but you could place it inside tmp/
to keep it together.
I've created project template for this setup, django-start-template
Deployment of this project is following:
source $VENV/bin/activate
export DJANGO_SETTINGS_MODULE=project_name.settings.production
git pull
pip install -r requirements.txt
# Update database, static files, locales
manage.py syncdb --noinput
manage.py migrate
manage.py collectstatic --noinput
manage.py makemessages -a
manage.py compilemessages
# restart wsgi
touch project_name/wsgi.py
You can use rsync
instead of git
, but still you need to run batch of commands to update your environment.
Recently, I made django-deploy
app, which allows me to run single management command to update environment, but I've used it for one project only and I'm still experimenting with it.
Draft of templates I place inside global templates/
directory. I guess one can create folder sketches/
in project root, but haven't used it yet.
These apps are usually prepared to publish as open-source. I've taken example below from django-forme
~/projects/django-app/
docs/
app/
tests/
example_project/
LICENCE
MANIFEST.in
README.md
setup.py
pytest.ini
tox.ini
.travis.yml
...
Name of directories is clear (I hope). I put test files outside app directory,
but it really doesn't matter. It is important to provide README
and setup.py
, so package is easily installed through pip
.
I found more accurate way to adding views like linear layouts in kotlin (Pass parent layout in inflate() and false)
val parentLayout = view.findViewById<LinearLayout>(R.id.llRecipientParent)
val childView = layoutInflater.inflate(R.layout.layout_recipient, parentLayout, false)
parentLayout.addView(childView)
An example:
log4j.rootLogger=ERROR, logfile
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.datePattern='-'dd'.log'
log4j.appender.logfile.File=log/radius-prod.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n
log4j.logger.foo.bar.Baz=DEBUG, myappender
log4j.additivity.foo.bar.Baz=false
log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myappender.datePattern='-'dd'.log'
log4j.appender.myappender.File=log/access-ext-dmz-prod.log
log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n
Ruby FTW:
ls | ruby -e 'puts STDIN.readlines.shuffle'
For someone having the same problem -
import name 'path' from 'django.urls'
(C:\Python38\lib\site-packages\django\urls\__init__.py)
You can also try installing django-urls by
pipenv install django-urls
yes, using *arg passing args to a function will make python unpack the values in arg and pass it to the function.
so:
>>> def printer(*args):
print args
>>> printer(2,3,4)
(2, 3, 4)
>>> printer(*range(2, 5))
(2, 3, 4)
>>> printer(range(2, 5))
([2, 3, 4],)
>>>
Set decoding to true
Your decoding is not set to true. If you don't have access to set the source to true. The code below will fix it for you.
$WorkingArray = json_decode(json_encode($data),true);
For some reason, this was not working
<p:column headerText="" width="25px" sortBy="#{row.key}">
But this worked:
<p:column headerText="" width="25" sortBy="#{row.key}">
Use this code in your service:
return this.getReports(accessToken)
.then(reports => reports.filter(report => report.id === id)[0]);
Here are two more ways to write a pure PowerShell function to join an arbitrary number of components into a path.
This first function uses a single array to store all of the components and then a foreach loop to combine them:
function Join-Paths {
Param(
[Parameter(mandatory)]
[String[]]
$Paths
)
$output = $Paths[0]
foreach($path in $Paths[1..$Paths.Count]) {
$output = Join-Path $output -ChildPath $path
}
$output
}
Because the path components are elements in an array and all part of a single argument, they must be separated by commas. Usage is as follows:
PS C:\> Join-Paths 'C:', 'Program Files', 'Microsoft Office' C:\Program Files\Microsoft Office
A more minimalist way to write this function is to use the built-in $args
variable, and then collapse the foreach loop into a single line using Mike Fair's method.
function Join-Paths2 {
$path = $args[0]
$args[1..$args.Count] | %{ $path = Join-Path $path $_ }
$path
}
Unlike the previous version of the function, each path component is a separate argument, so only a space is necessary to separate the arguments:
PS C:\> Join-Paths2 'C:' 'Program Files' 'Microsoft Office' C:\Program Files\Microsoft Office
is called a generic type. You can instantiate an object Pool like this:
PoolFactory<Integer> pool = new Pool<Integer>();
The generic parameter can only be a reference type. So you can't use primitive types like int or double or char or other primitive types.
An extension method for this which makes use of SemaphoreSlim and also allows to set maximum degree of parallelism
/// <summary>
/// Concurrently Executes async actions for each item of <see cref="IEnumerable<typeparamref name="T"/>
/// </summary>
/// <typeparam name="T">Type of IEnumerable</typeparam>
/// <param name="enumerable">instance of <see cref="IEnumerable<typeparamref name="T"/>"/></param>
/// <param name="action">an async <see cref="Action" /> to execute</param>
/// <param name="maxDegreeOfParallelism">Optional, An integer that represents the maximum degree of parallelism,
/// Must be grater than 0</param>
/// <returns>A Task representing an async operation</returns>
/// <exception cref="ArgumentOutOfRangeException">If the maxActionsToRunInParallel is less than 1</exception>
public static async Task ForEachAsyncConcurrent<T>(
this IEnumerable<T> enumerable,
Func<T, Task> action,
int? maxDegreeOfParallelism = null)
{
if (maxDegreeOfParallelism.HasValue)
{
using (var semaphoreSlim = new SemaphoreSlim(
maxDegreeOfParallelism.Value, maxDegreeOfParallelism.Value))
{
var tasksWithThrottler = new List<Task>();
foreach (var item in enumerable)
{
// Increment the number of currently running tasks and wait if they are more than limit.
await semaphoreSlim.WaitAsync();
tasksWithThrottler.Add(Task.Run(async () =>
{
await action(item).ContinueWith(res =>
{
// action is completed, so decrement the number of currently running tasks
semaphoreSlim.Release();
});
}));
}
// Wait for all tasks to complete.
await Task.WhenAll(tasksWithThrottler.ToArray());
}
}
else
{
await Task.WhenAll(enumerable.Select(item => action(item)));
}
}
Sample Usage:
await enumerable.ForEachAsyncConcurrent(
async item =>
{
await SomeAsyncMethod(item);
},
5);
It should be,
*/15 * * * * your_command_or_whatever
There's no need to write a custom directive. Angular's documentation is good but not complete. In fact, there is a directive called ngRequired
, that takes an Angular expression.
<input type='email'
name='email'
ng-model='contact.email'
placeholder='[email protected]'
ng-required='!contact.phone' />
<input type='text'
ng-model='contact.phone'
placeholder='(xxx) xxx-xxxx'
ng-required='!contact.email' />
Here's a more complete example: http://jsfiddle.net/uptnx/1/
Below Code is Set cursor to Starting in EditText
:
EditText editText = (EditText)findViewById(R.id.edittext_id);
editText.setSelection(0);
Below Code is Set cursor to end of the EditText
:
EditText editText = (EditText)findViewById(R.id.edittext_id);
editText.setSelection(editText.getText().length());
Below Code is Set cursor after some 2th Character position :
EditText editText = (EditText)findViewById(R.id.edittext_id);
editText.setSelection(2);
CREATE PROCEDURE AddBrand
@BrandName nvarchar(50) = null,
@CategoryID int = null
AS
BEGIN
DECLARE @BrandID int = null
SELECT @BrandID = BrandID FROM tblBrand
WHERE BrandName = @BrandName
INSERT INTO tblBrandinCategory (CategoryID, BrandID)
VALUES (@CategoryID, @BrandID)
END
EXEC AddBrand @BrandName = 'BMW', @CategoryId = 1
The error is telling you that x
doesn’t even exist! It hasn’t been declared, which is different than being assigned a value.
var x; // declaration
x = 2; // assignment
If you declared x
, you wouldn’t get an error. You would get an alert that says undefined
because x
exists/has been declared but hasn’t been assigned a value.
To check if the variable has been declared, you can use typeof
, any other method of checking if a variable exists will raise the same error you got initially.
if(typeof x !== "undefined") {
alert(x);
}
This is checking the type of the value stored in x
. It will only return undefined
when x
hasn’t been declared OR if it has been declared and was not yet assigned.
Yes:
<input required title="Enter something OR ELSE." />
The title
attribute will be used to notify the user of a problem.
Another dplyr
possibility could be:
df %>%
group_by(cat) %>%
mutate(num = 1:n())
cat val num
<fct> <dbl> <int>
1 aaa 0.0564 1
2 aaa 0.258 2
3 aaa 0.308 3
4 aaa 0.469 4
5 aaa 0.552 5
6 bbb 0.170 1
7 bbb 0.370 2
8 bbb 0.484 3
9 bbb 0.547 4
10 bbb 0.812 5
11 ccc 0.280 1
12 ccc 0.398 2
13 ccc 0.625 3
14 ccc 0.763 4
15 ccc 0.882 5
For anyone where none of these solutions are working, make sure that your request origin equals your request target, see this github issue.
I short, if you visit your website on 127.0.0.1:8000, then make sure that the requests you send are targeting your server on 127.0.0.1:8001 and not localhost:8001, although it might be the same target theoretically.
import java.util.*;
public class matrixcecil {
public static void main(String args[]){
List<Integer> k1=new ArrayList<Integer>(10);
k1.add(23);
k1.add(10);
k1.add(20);
k1.add(24);
int i=0;
while(k1.size()<10){
if(i==(k1.get(k1.size()-1))){
}
i=k1.get(k1.size()-1);
k1.add(30);
i++;
break;
}
System.out.println(k1);
}
}
I think this example will help you for better solution.
To list all local groups which have users assigned to them, use this command:
cut -d: -f1 /etc/group | sort
For more info- > Unix groups, Cut command, sort command
public class Main {
enum Vehical{
Car,
Bus,
Van
}
public static void main(String[] args){
String vehicalType = "CAR";
if(vehicalType.equals(Vehical.Car.name())){
System.out.println("The provider is Car");
}
String vehical_Type = "BUS";
if(vehical_Type.equals(Vehical.Bus.toString())){
System.out.println("The provider is Bus");
}
}
}
IETF has suggested jose libs on it's wiki: http://trac.tools.ietf.org/wg/jose/trac/wiki
I would highly recommend using them for signing. I am not a Java guy, but seems like jose4j seems like a good option. Has nice examples as well: https://bitbucket.org/b_c/jose4j/wiki/JWS%20Examples
Update: jwt.io provides a neat comparison of several jwt related libraries, and their features. A must check!
I would love to hear about what other java devs prefer.
After Uri.TryCreate
you can check Uri.Scheme
to see if it HTTP(s).
print "Matched!\n" if ($str1 eq $str2)
Perl has seperate string comparison and numeric comparison operators to help with the loose typing in the language. You should read perlop for all the different operators.
Much longer solution, but accounts for the following scenarios:
Is the image taller than the bounding box
private Image ResizePhoto(FileInfo sourceImage, int desiredWidth, int desiredHeight)
{
//throw error if bouning box is to small
if (desiredWidth < 4 || desiredHeight < 4)
throw new InvalidOperationException("Bounding Box of Resize Photo must be larger than 4X4 pixels.");
var original = Bitmap.FromFile(sourceImage.FullName);
//store image widths in variable for easier use
var oW = (decimal)original.Width;
var oH = (decimal)original.Height;
var dW = (decimal)desiredWidth;
var dH = (decimal)desiredHeight;
//check if image already fits
if (oW < dW && oH < dH)
return original; //image fits in bounding box, keep size (center with css) If we made it bigger it would stretch the image resulting in loss of quality.
//check for double squares
if (oW == oH && dW == dH)
{
//image and bounding box are square, no need to calculate aspects, just downsize it with the bounding box
Bitmap square = new Bitmap(original, (int)dW, (int)dH);
original.Dispose();
return square;
}
//check original image is square
if (oW == oH)
{
//image is square, bounding box isn't. Get smallest side of bounding box and resize to a square of that center the image vertically and horizontally with Css there will be space on one side.
int smallSide = (int)Math.Min(dW, dH);
Bitmap square = new Bitmap(original, smallSide, smallSide);
original.Dispose();
return square;
}
//not dealing with squares, figure out resizing within aspect ratios
if (oW > dW && oH > dH) //image is wider and taller than bounding box
{
var r = Math.Min(dW, dH) / Math.Min(oW, oH); //two dimensions so figure out which bounding box dimension is the smallest and which original image dimension is the smallest, already know original image is larger than bounding box
var nH = oH * r; //will downscale the original image by an aspect ratio to fit in the bounding box at the maximum size within aspect ratio.
var nW = oW * r;
var resized = new Bitmap(original, (int)nW, (int)nH);
original.Dispose();
return resized;
}
else
{
if (oW > dW) //image is wider than bounding box
{
var r = dW / oW; //one dimension (width) so calculate the aspect ratio between the bounding box width and original image width
var nW = oW * r; //downscale image by r to fit in the bounding box...
var nH = oH * r;
var resized = new Bitmap(original, (int)nW, (int)nH);
original.Dispose();
return resized;
}
else
{
//original image is taller than bounding box
var r = dH / oH;
var nH = oH * r;
var nW = oW * r;
var resized = new Bitmap(original, (int)nW, (int)nH);
original.Dispose();
return resized;
}
}
}
Built off of prc322's awesome answer.
function hideContainerOnMouseClickOut(selector, callback) {
var args = Array.prototype.slice.call(arguments); // Save/convert arguments to array since we won't be able to access these within .on()
$(document).on("mouseup.clickOFF touchend.clickOFF", function (e) {
var container = $(selector);
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
$(document).off("mouseup.clickOFF touchend.clickOFF");
if (callback) callback.apply(this, args);
}
});
}
This adds a couple things...
I hope this helps someone!
copy your certificates inside
/etc/pki/ca-trust/source/anchors/
then run the following command
update-ca-trust
I found this method: Matcher.replaceAll(String replacement); In java.util.regex.Matcher.java you can see more:
/**
* Replaces every subsequence of the input sequence that matches the
* pattern with the given replacement string.
*
* <p> This method first resets this matcher. It then scans the input
* sequence looking for matches of the pattern. Characters that are not
* part of any match are appended directly to the result string; each match
* is replaced in the result by the replacement string. The replacement
* string may contain references to captured subsequences as in the {@link
* #appendReplacement appendReplacement} method.
*
* <p> Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in
* the replacement string may cause the results to be different than if it
* were being treated as a literal replacement string. Dollar signs may be
* treated as references to captured subsequences as described above, and
* backslashes are used to escape literal characters in the replacement
* string.
*
* <p> Given the regular expression <tt>a*b</tt>, the input
* <tt>"aabfooaabfooabfoob"</tt>, and the replacement string
* <tt>"-"</tt>, an invocation of this method on a matcher for that
* expression would yield the string <tt>"-foo-foo-foo-"</tt>.
*
* <p> Invoking this method changes this matcher's state. If the matcher
* is to be used in further matching operations then it should first be
* reset. </p>
*
* @param replacement
* The replacement string
*
* @return The string constructed by replacing each matching subsequence
* by the replacement string, substituting captured subsequences
* as needed
*/
public String replaceAll(String replacement) {
reset();
StringBuffer buffer = new StringBuffer(input.length());
while (find()) {
appendReplacement(buffer, replacement);
}
return appendTail(buffer).toString();
}
Another answer here also mentions since 2012 you can remove Remove cached login via How to remove cached server names from the Connect to Server dialog?. Just confirmed this delete in MRU list works fine in 2016 and 2017.
SQL Server Management Studio 2017 delete the file
C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\14.0\SqlStudio.bin
SQL Server Management Studio 2016 delete the file
C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\13.0\SqlStudio.bin
SQL Server Management Studio 2014 delete the file
C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\12.0\SqlStudio.bin
SQL Server Management Studio 2012 delete the file
C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\11.0\SqlStudio.bin
SQL Server Management Studio 2008 delete the file C:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin
SQL Server Management Studio 2005 delete the file – same as above answer but the Vista path.
C:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat
These are profile paths for Vista / 7 / 8.
EDIT:
Note, AppData
is a hidden folder. You need to show hidden folders in explorer.
EDIT: You can simply press delete from the Server / User name drop down (confirmed to be working for SSMS v18.0). Original source from https://blog.sqlauthority.com/2013/04/17/sql-server-remove-cached-login-from-ssms-connect-dialog-sql-in-sixty-seconds-049/ which mentioned that this feature is available since 2012!
yum uses RPM, so the following command will list the contents of the installed package:
$ rpm -ql package-name
You should use return as in:
function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
if (exit) {
return;
}
Swift 5.1 Example for three view
Step:1 -> Add storyboard view and add outlet viewController UIView
@IBOutlet var firstView: UIView!
@IBOutlet var secondView: UIView!
@IBOutlet var thirdView: UIView!
Step:2 -> Add storyBoard view Tag
Step:3 -> Add gesture
override func viewDidLoad() {
super.viewDidLoad()
firstView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tap(_:))))
firstView.isUserInteractionEnabled = true
secondView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tap(_:))))
secondView.isUserInteractionEnabled = true
thirdView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tap(_:))))
thirdView.isUserInteractionEnabled = true
}
Step:4 -> select view
@objc func tap(_ gestureRecognizer: UITapGestureRecognizer) {
let tag = gestureRecognizer.view?.tag
switch tag! {
case 1 :
print("select first view")
case 2 :
print("select second view")
case 3 :
print("select third view")
default:
print("default")
}
}
This question touches a very stinking part of the "famous" and "obvious" Python syntax - what takes precedence, the lambda, or the for of list comprehension.
I don't think the purpose of the OP was to generate a list of squares from 0 to 9. If that was the case, we could give even more solutions:
squares = []
for x in range(10): squares.append(x*x)
But it's not the point. The point is W(hy)TF is this ambiguous expression so counter-intuitive? And I have an idiotic case for you at the end, so don't dismiss my answer too early (I had it on a job interview).
So, the OP's comprehension returned a list of lambdas:
[(lambda x: x*x) for x in range(10)]
This is of course just 10 different copies of the squaring function, see:
>>> [lambda x: x*x for _ in range(3)]
[<function <lambda> at 0x00000000023AD438>, <function <lambda> at 0x00000000023AD4A8>, <function <lambda> at 0x00000000023AD3C8>]
Note the memory addresses of the lambdas - they are all different!
You could of course have a more "optimal" (haha) version of this expression:
>>> [lambda x: x*x] * 3
[<function <lambda> at 0x00000000023AD2E8>, <function <lambda> at 0x00000000023AD2E8>, <function <lambda> at 0x00000000023AD2E8>]
See? 3 time the same lambda.
Please note, that I used _
as the for
variable. It has nothing to do with the x
in the lambda
(it is overshadowed lexically!). Get it?
I'm leaving out the discussion, why the syntax precedence is not so, that it all meant:
[lambda x: (x*x for x in range(10))]
which could be: [[0, 1, 4, ..., 81]]
, or [(0, 1, 4, ..., 81)]
, or which I find most logical, this would be a list
of 1 element - a generator
returning the values. It is just not the case, the language doesn't work this way.
BUT What, If...
What if you DON'T overshadow the for
variable, AND use it in your lambda
s???
Well, then crap happens. Look at this:
[lambda x: x * i for i in range(4)]
this means of course:
[(lambda x: x * i) for i in range(4)]
BUT it DOESN'T mean:
[(lambda x: x * 0), (lambda x: x * 1), ... (lambda x: x * 3)]
This is just crazy!
The lambdas in the list comprehension are a closure over the scope of this comprehension. A lexical closure, so they refer to the i
via reference, and not its value when they were evaluated!
So, this expression:
[(lambda x: x * i) for i in range(4)]
IS roughly EQUIVALENT to:
[(lambda x: x * 3), (lambda x: x * 3), ... (lambda x: x * 3)]
I'm sure we could see more here using a python decompiler (by which I mean e.g. the dis
module), but for Python-VM-agnostic discussion this is enough.
So much for the job interview question.
Now, how to make a list
of multiplier lambdas, which really multiply by consecutive integers? Well, similarly to the accepted answer, we need to break the direct tie to i
by wrapping it in another lambda
, which is getting called inside the list comprehension expression:
Before:
>>> a = [(lambda x: x * i) for i in (1, 2)]
>>> a[1](1)
2
>>> a[0](1)
2
After:
>>> a = [(lambda y: (lambda x: y * x))(i) for i in (1, 2)]
>>> a[1](1)
2
>>> a[0](1)
1
(I had the outer lambda variable also = i
, but I decided this is the clearer solution - I introduced y
so that we can all see which witch is which).
Edit 2019-08-30:
Following a suggestion by @josoler, which is also present in an answer by @sheridp - the value of the list comprehension "loop variable" can be "embedded" inside an object - the key is for it to be accessed at the right time. The section "After" above does it by wrapping it in another lambda
and calling it immediately with the current value of i
. Another way (a little bit easier to read - it produces no 'WAT' effect) is to store the value of i
inside a partial
object, and have the "inner" (original) lambda
take it as an argument (passed supplied by the partial
object at the time of the call), i.e.:
After 2:
>>> from functools import partial
>>> a = [partial(lambda y, x: y * x, i) for i in (1, 2)]
>>> a[0](2), a[1](2)
(2, 4)
Great, but there is still a little twist for you! Let's say we wan't to make it easier on the code reader, and pass the factor by name (as a keyword argument to partial
). Let's do some renaming:
After 2.5:
>>> a = [partial(lambda coef, x: coef * x, coef=i) for i in (1, 2)]
>>> a[0](1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() got multiple values for argument 'coef'
WAT?
>>> a[0]()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() missing 1 required positional argument: 'x'
Wait... We're changing the number of arguments by 1, and going from "too many" to "too few"?
Well, it's not a real WAT, when we pass coef
to partial
in this way, it becomes a keyword argument, so it must come after the positional x
argument, like so:
After 3:
>>> a = [partial(lambda x, coef: coef * x, coef=i) for i in (1, 2)]
>>> a[0](2), a[1](2)
(2, 4)
I would prefer the last version over the nested lambda, but to each their own...
Edit 2020-08-18:
Thanks to commenter dasWesen, I found out that this stuff is covered in the Python documentation: https://docs.python.org/3.4/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result - it deals with loops instead of list comprehensions, but the idea is the same - global or nonlocal variable access in the lambda function. There's even a solution - using default argument values (like for any function):
>>> a = [lambda x, coef=i: coef * x for i in (1, 2)]
>>> a[0](2), a[1](2)
(2, 4)
This way the coef value is bound to the value of i at the time of function definition (see James Powell's talk "Top To Down, Left To Right", which also explains why mutable default values are shunned).
See if this example provides any clarification. Basically you configure a set of routes and include partial templates based on the route. Setting ng-view in your main index.html allows you to inject those partial views.
The config portion looks like this:
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {controller:'ListCtrl', templateUrl:'list.html'})
.otherwise({redirectTo:'/'});
}])
The point of entry for injecting the partial view into your main template is:
<div class="container" ng-view=""></div>
echo Running from `dirname $0`
let expressions = [ '/something/', '/something_else/', '/and_something_else/'];
let str = 'else';
here will be the check for following expressions:
if( expressions.find(expression => expression.includes(str) ) ) {
}
using Array .find() method to traverse array and .include to check substring
Java and JavaScript are a fairly bad example to demonstrate this difference, because both are interpreted languages. Java (interpreted) and C (or C++) (compiled) might have been a better example.
Why the striked-through text? As this answer correctly points out, interpreted/compiled is about a concrete implementation of a language, not about the language per se. While statements like "C is a compiled language" are generally true, there's nothing to stop someone from writing a C language interpreter. In fact, interpreters for C do exist.
Basically, compiled code can be executed directly by the computer's CPU. That is, the executable code is specified in the CPU's "native" language (assembly language).
The code of interpreted languages however must be translated at run-time from any format to CPU machine instructions. This translation is done by an interpreter.
Another way of putting it is that interpreted languages are code is translated to machine instructions step-by-step while the program is being executed, while compiled languages have code has been translated before program execution.
Inspired by Steve answer, I wrote simple function that toggles between vertical and horizontal splits for all windows in current tab. You can bind it to mapping like in the last line below.
function! ToggleWindowHorizontalVerticalSplit()
if !exists('t:splitType')
let t:splitType = 'vertical'
endif
if t:splitType == 'vertical' " is vertical switch to horizontal
windo wincmd K
let t:splitType = 'horizontal'
else " is horizontal switch to vertical
windo wincmd H
let t:splitType = 'vertical'
endif
endfunction
nnoremap <silent> <leader>wt :call ToggleWindowHorizontalVerticalSplit()<cr>
These are all great solutions, but they all rely on Path.GetInvalidFileNameChars
, which may not be as reliable as you'd think. Notice the following remark in the MSDN documentation on Path.GetInvalidFileNameChars
:
The array returned from this method is not guaranteed to contain the complete set of characters that are invalid in file and directory names. The full set of invalid characters can vary by file system. For example, on Windows-based desktop platforms, invalid path characters might include ASCII/Unicode characters 1 through 31, as well as quote ("), less than (<), greater than (>), pipe (|), backspace (\b), null (\0) and tab (\t).
It's not any better with Path.GetInvalidPathChars
method. It contains the exact same remark.
iText has more than one way of doing this. The PdfStamper
class is one option. But I find the easiest method is to create a new PDF document then import individual pages from the existing document into the new PDF.
// Create output PDF
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();
// Load existing PDF
PdfReader reader = new PdfReader(templateInputStream);
PdfImportedPage page = writer.getImportedPage(reader, 1);
// Copy first page of existing PDF into output PDF
document.newPage();
cb.addTemplate(page, 0, 0);
// Add your new data / text here
// for example...
document.add(new Paragraph("my timestamp"));
document.close();
This will read in a PDF from templateInputStream
and write it out to outputStream
. These might be file streams or memory streams or whatever suits your application.
This worked for me.
formula
in the first cell.Enter
.Ctrl + Shift + down_arrow
. This will select the last cell in the column used on the worksheet.Ctrl + D
. This will fill copy the formula in the remaining cells.Short and clear answer
Make your life easy when working with dates, timestamps and durations. Use HalDateTime from
http://sourceforge.net/projects/haldatetime/?source=directory
For example you can just use it to parse your input like this:
HalDateTime mydate = HalDateTime.valueOf( "25.12.1988" );
System.out.println( mydate ); // will print in ISO format: 1988-12-25
You can also specify patterns for parsing and printing.
Sub DeleteEmptyRows()
Worksheets("YourSheetName").Activate
On Error Resume Next
Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub
The following code will delete all rows on a sheet(YourSheetName) where the content of Column A is blank.
EDIT: User Defined Type Not Defined is caused by "oTable As Table" and "oRow As Row". Replace Table and Row with Object to resolve the error and make it compile.
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
Intent shareIntent = Intent.createChooser(sendIntent, null);
startActivity(shareIntent);
This is working fine for me using jquery
<style>
@media print { @page { margin: 0; }
body { margin: 1.6cm; } }
</style>
Well, apparently I had to change my PUT calling function updateUser
. I removed the @Consumes
, the @RequestMapping
and also added a @ResponseBody
to the function. So my method looked like this:
@RequestMapping(value="/{id}",method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public void updateUser(@PathVariable int id, @RequestBody User temp){
Set<User> set1= obj2.getUsers();
for(User a:set1)
{
if(id==a.getId())
{
set1.remove(a);
a.setId(temp.getId());
a.setName(temp.getName());
set1.add(a);
}
}
Userlist obj3=new Userlist(set1);
obj2=obj3;
}
And it worked!!! Thank you all for the response.
Holdover from C.
The WM_CONCAT
function (if included in your database, pre Oracle 11.2) or LISTAGG
(starting Oracle 11.2) should do the trick nicely. For example, this gets a comma-delimited list of the table names in your schema:
select listagg(table_name, ', ') within group (order by table_name)
from user_tables;
or
select wm_concat(table_name)
from user_tables;
a very common try_files line which can be applied on your condition is
location / {
try_files $uri $uri/ /test/index.html;
}
you probably understand the first part, location /
matches all locations, unless it's matched by a more specific location, like location /test
for example
The second part ( the try_files
) means when you receive a URI that's matched by this block try $uri
first, for example http://example.com/images/image.jpg
nginx will try to check if there's a file inside /images
called image.jpg
if found it will serve it first.
Second condition is $uri/
which means if you didn't find the first condition $uri
try the URI as a directory, for example http://example.com/images/
, ngixn will first check if a file called images
exists then it wont find it, then goes to second check $uri/
and see if there's a directory called images
exists then it will try serving it.
Side note: if you don't have autoindex on
you'll probably get a 403 forbidden error, because directory listing is forbidden by default.
EDIT: I forgot to mention that if you have
index
defined, nginx will try to check if the index exists inside this folder before trying directory listing.
Third condition /test/index.html
is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html
inside the folder test
and serve it if it exists.
If the third condition fails too, then nginx will serve the 404 error page.
Also there's something called named locations, like this
location @error {
}
You can call it with try_files
like this
try_files $uri $uri/ @error;
TIP: If you only have 1 condition you want to serve, like for example inside folder images
you only want to either serve the image or go to 404 error, you can write a line like this
location /images {
try_files $uri =404;
}
which means either serve the file or serve a 404 error, you can't use only $uri
by it self without =404
because you need to have a fallback option.
You can also choose which ever error code you want, like for example:
location /images {
try_files $uri =403;
}
This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..
min-width
and max-width
properties do not work the way you expect for table cells. From spec:
In CSS 2.1, the effect of 'min-width' and 'max-width' on tables, inline tables, table cells, table columns, and column groups is undefined.
This hasn't changed in CSS3.
As you mentioned in a comment, you're using log4j. I discovered (inadvertently) a place where I had written
LOG.error(exc);
instead of the typical
LOG.error("Some informative message", e);
through laziness or perhaps just not thinking about it. The unfortunate part of this is that it doesn't behave as you expect. The logger API actually takes Object as the first argument, not a string - and then it calls toString() on the argument. So instead of getting the nice pretty stack trace, it just prints out the toString - which in the case of NPE is pretty useless.
Perhaps this is what you're experiencing?
additionally to sangam
code
if (chNode["innerNode"]["innermostNode"]==null)
return true; //node *parentNode*/innerNode/innermostNode exists
Aaaand another answer here. :) Since I couldn't make the others quite work.
My solution both handles escaped quotes (double occurrences), and it does not include delimiters in the match.
Note that I have been matching against '
instead of "
as that was my scenario, but simply replace them in the pattern for the same effect.
Here goes (remember to use the "ignore whitespace" flag /x
if you use the commented version below) :
# Only include if previous char was start of string or delimiter
(?<=^|,)
(?:
# 1st option: empty quoted string (,'',)
'{2}
|
# 2nd option: nothing (,,)
(?:)
|
# 3rd option: all but quoted strings (,123,)
# (included linebreaks to allow multiline matching)
[^,'\r\n]+
|
# 4th option: quoted strings (,'123''321',)
# start pling
'
(?:
# double quote
'{2}
|
# or anything but quotes
[^']+
# at least one occurance - greedy
)+
# end pling
'
)
# Only include if next char is delimiter or end of string
(?=,|$)
Single line version:
(?<=^|,)(?:'{2}|(?:)|[^,'\r\n]+|'(?:'{2}|[^']+)+')(?=,|$)
If it isn't I could see things heading that way.
I'm working on redoing the website for the company I work for and the designer they hired used a 960px width layout. There is also a 960px grid system that seems to be getting quite popular (http://960.gs/).
I've been out of web stuff for a few years but from what I've read catching up on things it seems 960/980 is about right. For mobile ~320px sticks in my mind, by which 960 is divisible. 960 is also evenly divisible by 2, 3, 4, 5, and 6.
In case someone else stumbles upon this question and wants it here is the SASS mixin I use.
@mixin rotate($deg: 90){
$sDeg: #{$deg}deg;
-webkit-transform: rotate($sDeg);
-moz-transform: rotate($sDeg);
-ms-transform: rotate($sDeg);
-o-transform: rotate($sDeg);
transform: rotate($sDeg);
}
i achieved this by:
import { ImageBackground } from 'react-native';
<ImageBackground style={ styles.imgBackground }
resizeMode='cover'
source={require('./Your/Path.png')}>
//place your now nested component JSX code here
</ImageBackground>
And then the Styles:
imgBackground: {
width: '100%',
height: '100%',
flex: 1
},
In my case, I had simply changed the way I created a table and inadvertently changed the field name I tried to query. Make sure the field names you reference in the query actually exist in the table/query you are querying.
You just need this:
$(".hidden").attr("placeholder", "Type here to search");
classList
is used for manipulating classes and not attributes.
Just to expand on $http
(shortcut methods) here: http://docs.angularjs.org/api/ng.$http
//Snippet from the page
$http.get('/someUrl').success(successCallback);
$http.post('/someUrl', data).success(successCallback);
//available shortcut methods
$http.get
$http.head
$http.post
$http.put
$http.delete
$http.jsonp
Recently faced a problem with fetching 'Origin' request header, then I found this question. But pretty confused with the results, req.get('host')
is deprecated, that's why giving Undefined
.
Use,
req.header('Origin');
req.header('Host');
// this method can be used to access other request headers like, 'Referer', 'User-Agent' etc.
Angular - equal width button group
Assuming you have an array of 'things' in your scope...
<div class="btn-group"
style="width: 100%;">
<button ng-repeat="thing in things"
class="btn btn-default"
ng-style="{width: (100/things.length)+'%'}">
{{thing}}
</button>
</div>
When you are dumping all database. Obviously it is having large data. So you can prefer below for better:
Creating Backup:
mysqldump -u [user] -p[password]--single-transaction --quick --all-databases | gzip > alldb.sql.gz
If error
-- Warning: Skipping the data of table mysql.event. Specify the --events option explicitly.
Use:
mysqldump -u [user] -p --events --single-transaction --quick --all-databases | gzip > alldb.sql.gz
Restoring Backup:
gunzip < alldb.sql.gz | mysql -u [user] -p[password]
Hope it will help :)
bool containsCharacter = test.IndexOf("s", StringComparison.OrdinalIgnoreCase) >= 0;
Use this, but it's a complete solution:
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
This work for me
I set style's font before and make rowheader normally then i set in loop for the style with font bolded on each cell of rowhead. Et voilà first row is bolded.
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("FirstSheet");
HSSFRow rowhead = sheet.createRow(0);
HSSFCellStyle style = wb.createCellStyle();
HSSFFont font = wb.createFont();
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short)10);
font.setBold(true);
style.setFont(font);
rowhead.createCell(0).setCellValue("ID");
rowhead.createCell(1).setCellValue("First");
rowhead.createCell(2).setCellValue("Second");
rowhead.createCell(3).setCellValue("Third");
for(int j = 0; j<=3; j++)
rowhead.getCell(j).setCellStyle(style);
Best , Easiest and Generic Answer :).
string originalString = "1111222233334444";
List<string> test = new List<string>();
int chunkSize = 4; // change 4 with the size of strings you want.
for (int i = 0; i < originalString.Length; i = i + chunkSize)
{
if (originalString.Length - i >= chunkSize)
test.Add(originalString.Substring(i, chunkSize));
else
test.Add(originalString.Substring(i,((originalString.Length - i))));
}
I Hope this Help:
<?php
// The code below creates the class
class Person {
// Creating some properties (variables tied to an object)
public $isAlive = true;
public $firstname;
public $lastname;
public $age;
// Assigning the values
public function __construct($firstname, $lastname, $age) {
$this->firstname = $firstname;
$this->lastname = $lastname;
$this->age = $age;
}
// Creating a method (function tied to an object)
public function greet() {
return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)";
}
}
// Creating a new person called "boring 12345", who is 12345 years old ;-)
$me = new Person('boring', '12345', 12345);
// Printing out, what the greet method returns
echo $me->greet();
?>
For More Information You need to Go to codecademy.com
git checkout HEAD -- client/src/pp_web/index.cljs
With iOS 8, Apple introduced a helper method to retrieve the hour
, minute
, second
and nanosecond
from an NSDate object.
Objective-C
NSDate *date = [NSDate currentDate];
NSInteger hour = 0;
NSInteger minute = 0;
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
[currentCalendar getHour:&hour minute:&minute second:NULL nanosecond:NULL fromDate:date];
NSLog(@"the hour is %ld and minute is %ld", (long)hour, (long)minute);
Swift
let date = NSDate()
var hour = 0
var minute = 0
let calendar = NSCalendar.currentCalendar()
if #available(iOS 8.0, *) {
calendar.getHour(&hour, minute: &minute, second: nil, nanosecond: nil, fromDate: date)
print("the hour is \(hour) and minute is \(minute)")
}
You might have to use another batch file first to launch the second with admin rights.
In the first use
runas /noprofile /user:mymachine\administrator yourbatchfile.bat
Upon further reading, you must be able to type in the password at the prompt. You cannot pipe the password as this feature was locked down for security reasons.
You may have more luck with psexec.
Use the STL
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<int> userInput;
// Read until end of input.
// Hit control D
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(userInput)
);
// Print in Normal order
std::copy(userInput.begin(),
userInput.end(),
std::ostream_iterator<int>(std::cout,",")
);
std::cout << "\n";
// Print in reverse order:
std::copy(userInput.rbegin(),
userInput.rend(),
std::ostream_iterator<int>(std::cout,",")
);
std::cout << "\n";
// Update for C++11
// Range based for is now a good alternative.
for(auto const& value: userInput)
{
std::cout << value << ",";
}
std::cout << "\n";
}
dplyr
solution:Idea:
Code:
DF = data.frame(V1=c(2,8,1),V2=c(7,3,5),V3=c(9,6,4))
DF %>%
rownames_to_column() %>%
gather(column, value, -rowname) %>%
group_by(rowname) %>%
filter(rank(-value) == 1)
Result:
# A tibble: 3 x 3
# Groups: rowname [3]
rowname column value
<chr> <chr> <dbl>
1 2 V1 8
2 3 V2 5
3 1 V3 9
This approach can be easily extended to get the top n
columns.
Example for n=2
:
DF %>%
rownames_to_column() %>%
gather(column, value, -rowname) %>%
group_by(rowname) %>%
mutate(rk = rank(-value)) %>%
filter(rk <= 2) %>%
arrange(rowname, rk)
Result:
# A tibble: 6 x 4
# Groups: rowname [3]
rowname column value rk
<chr> <chr> <dbl> <dbl>
1 1 V3 9 1
2 1 V2 7 2
3 2 V1 8 1
4 2 V3 6 2
5 3 V2 5 1
6 3 V3 4 2
foo="$(tr '[:lower:]' '[:upper:]' <<< ${foo:0:1})${foo:1}"
Apparently the correct form is without the ""
As in
set JAVA_OPTS=-Xms512M -Xmx1024M
! [rejected] master -> master (non-fast-forward)
Don’t panic, this is extremely easy to fix. All you have to do is issue a pull and your branch will be fast-forward:
$ git pull myrepo master
Then retry your push and everything should be fine:
$ git push github master
It is not recommended to use DataReader
and Command.ExecuteReader
to get just one value from the database. Instead, you should use Command.ExecuteScalar
as following:
String sql = "SELECT ColumnNumber FROM learer WHERE learer.id = " + index;
SqlCommand cmd = new SqlCommand(sql,conn);
learerLabel.Text = (String) cmd.ExecuteScalar();
Here is more information about Connecting to database and managing data.
For Converting a List into Pandas Core Data Frame, we need to use DataFrame Method from pandas Package.
There are Different Ways to Perform the Above Operation.
import pandas as pd
Data = pd.DataFrame(Column_Data)
Data.columns = ['Column_Name']
So, for the above mentioned issue, the code snippet is
import pandas as pd
Content = ['Thanks You',
'Its fine no problem',
'Are you sure']
Data = pd.DataFrame({'Text': Content})
import org.apache.commons.lang.WordUtils;
public class CapitalizeFirstLetterInString {
public static void main(String[] args) {
// only the first letter of each word is capitalized.
String wordStr = WordUtils.capitalize("this is first WORD capital test.");
//Capitalize method capitalizes only first character of a String
System.out.println("wordStr= " + wordStr);
wordStr = WordUtils.capitalizeFully("this is first WORD capital test.");
// This method capitalizes first character of a String and make rest of the characters lowercase
System.out.println("wordStr = " + wordStr );
}
}
Output :
This Is First WORD Capital Test.
This Is First Word Capital Test.
There is no string
type in C
. You have to use char arrays.
By the way your code will not work ,because the size of the array should allow for the whole array to fit in plus one additional zero terminating character.
Intel released recommended installation instructions for the ICS emulator on May 15, 2012. This worked for me. The emulator is now fast and the UI is smooth.
The first half of the instructions are detailed enough, so I will assume you were able to install the Intel x86 Atom System Image(s) using the Android SDK manager, as well as Intel HAXM.
Now to ensure that everything else is set up so you can enjoy a highly performing emulator:
And start it:
sudo kextload -b com.intel.kext.intelhaxm (mac)
If HAXM is working properly, you may see this message when launching the emulator:
HAX is working and emulator runs in fast virtual mode
Otherwise, you may see this error:
HAX is not working and the emulator runs in emulation mode emulator:
Failed to open the hax module
Use GPU emulation. You cannot use the Snapshot option when using GPU emulation as of this writing. Ensure that GPU emulation is set to "yes".
Set the device memory to 1024 MB or more, but not more than the Intel HAXM setting. I use 1024 MB per device and 2048 for HAXM.
Always double-check the settings after saving! The emulator is very picky about what it allows you to set, and it will revert configurations without telling you.
With these settings the software keyboard no longer appears, nor do the on-screen back, menu, and recent keys. This appears to be a limitation of the current ICS Intel x86 system image. You will need to use the keyboard shortcuts.
On Mac OS you will need to hold fn + control for the F1 - F12 keys to work. Page up/down/left/right can be performed using control + arrow keys.
If you need to get all td's inside tr without defining id for them, you can use the code below :
var items = new Array();
$('#TABLE_ID td:nth-child(1)').each(function () {
items.push($(this).html());
});
The code above will add all first cells inside the Table into an Array variable.
you can change nth-child(1) which means the first cell to any cell number you need.
hope this code helps you.
bash:
for f in *.xls ; do xls2csv "$f" "${f%.xls}.csv" ; done
Can you consider using Nix http://nixos.org/nix/ ?
Nix supports multi-user package management: multiple users can share a common Nix store securely, don’t need to have root privileges to install software, and can install and use different versions of a package.
For those who came here looking for the answer and didnt type 3306 wrong...If like myself, you have wasted hours with no luck searching for this answer, then possibly this may help.
If you are seeing this: (HY000/2002): No connection could be made because the target machine actively refused it
Then my understanding is that it cant connect for one of the following below. Now which..
1) is your wamp, mamp, etc icon GREEN? Either way, right-click the icon --> click tools --> test both the port used for Apache (typically 80) and for Mariadb (3307?). Should say 'It is correct' for both.
2) Error comes from a .php file. So, check your dbconnect.php.
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_pw";
$dbname = "your_dbname";
$port = "3307";
?>
Is your setup correct? Does your user exist? Do they have rights? Does port match the tested port in 1)? Doesn't have to be 3307 and user can be root. You can also left click the green icon --> click MariaDB and view used port as shown in the image below. All good? Positive? ok!
3) Error comes when you login to phpmyadmin. So, check your my.ini.
Open my.ini by left clicking the green icon --> click MariaDB -->
; The following options will be passed to all MariaDB clients
[client]
;password = your_password
port = 3307
socket = /tmp/mariadb.sock
; Here follows entries for some specific programs
; The MariaDB server
[wampmariadb64]
;skip-grant-tables
port = 3307
socket = /tmp/mariadb.sock
Make sure the ports match the port MariaDB is being testing on. Then finally..
[mysqld]
port = 3307
At the bottom of my.ini, make sure this port matches as well.
4) 1-3 done? restart your WAMP and cross your fingers!
This is the function that I generally use in my code to prepend zeros to a number or string.
The inputs are the string or number (str), and the desired length of the output (len).
var PrependZeros = function (str, len) {
if(typeof str === 'number' || Number(str)){
str = str.toString();
return (len - str.length > 0) ? new Array(len + 1 - str.length).join('0') + str: str;
}
else{
for(var i = 0,spl = str.split(' '); i < spl.length; spl[i] = (Number(spl[i])&& spl[i].length < len)?PrependZeros(spl[i],len):spl[i],str = (i == spl.length -1)?spl.join(' '):str,i++);
return str;
}
};
Examples:
PrependZeros('MR 3',3); // MR 003
PrependZeros('MR 23',3); // MR 023
PrependZeros('MR 123',3); // MR 123
PrependZeros('foo bar 23',3); // foo bar 023
extension UIApplication {
static var appVersion: String {
if let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") {
return "\(appVersion)"
} else {
return ""
}
}
static var build: String {
if let buildVersion = NSBundle.mainBundle().objectForInfoDictionaryKey(kCFBundleVersionKey as String) {
return "\(buildVersion)"
} else {
return ""
}
}
static var versionBuild: String {
let version = UIApplication.appVersion
let build = UIApplication.build
var versionAndBuild = "v\(version)"
if version != build {
versionAndBuild = "v\(version)(\(build))"
}
return versionAndBuild
}
}
Attention: You should use if let here in case that the app version or build is not set which will lead to crash if you try to use ! to unwrap.
It's work for me
SELECT CONCAT(column1, ' ' ,column2) AS newColumn;
I was getting an "authenticationrequired" (407) error when clicking the [Sync] button (using the MS Git Provider), and this worked for me (VS 2013):
..\Program Files\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe.config
<system.net>
<defaultProxy useDefaultCredentials="true" enabled="true">
<proxy proxyaddress="http://username:password@proxyip:port" />
</defaultProxy>
<settings>
<ipv6 enabled="false"/>
<servicePointManager expect100Continue="false"/>
</settings>
</system.net>
I think the magic for me was setting 'ipv6' to 'false' - not sure why (perhaps only IPv4 is supported in my case). I tried other ways as shown above, but I move the "settings" section AFTER "defaultProxy", and changed "ipv6", and it worked perfectly with my login added (every other way I tried in all other answers posted just failed for me).
Edit: Just found another work around (without changing the config file). For some reason, if I disable the windows proxy (it's a URL to a PAC file in my case), try again (it will fail), and re-enable the proxy, it works. Seems to cache something internally that gets reset when I do this (at least in my case).
In case anyone needed the above in swift :
SWIFT 3.0 and above :
this will capitalize your string, make the first letter capital :
viewNoteDateMonth.text = yourString.capitalized
this will uppercase your string, make all the string upper case :
viewNoteDateMonth.text = yourString.uppercased()
You have to go to the "Pricing" menu. Even if the availability date is in the past, sometimes you have to set it again for today's date. Apple doesn't tell you to do this, but I found that the app goes live after resetting the dates again, especially if there's been app rejections in the past. I guess it messes up with the dates. Looks like sometimes if you do nothing and just follow the instructions, the app will never go live.
I would go with the file system approach, primarily due to its better flexibility. Consider that if the number of images gets huge, one database may not be able to handle it. With file system, you can simple add more file servers, assuming that you're using NFS or kind.
Another advantage the file system approach has is to be able to do some fancy stuffs, such as you can use Amazon S3 as the primary storage (save the url in the database instead of file path). In case of outages happen to S3, you fall back to your file server (may be another database entry containing the file path). Some voodoo to apply to Apache or whatever web server you're using.
MonthRepository monthRepository = new MonthRepository();
IQueryable<MonthEntity> entities = monthRepository.GetAllMonth();
List<MonthEntity> monthEntities = new List<MonthEntity>();
foreach(var r in entities)
{
monthEntities.Add(r);
}
ViewData["Month"] = new SelectList(monthEntities, "MonthID", "Month", "Mars");
The solution from the comments deserves it's own answer:
redis-cli --bigkeys
I've decided to give an answer to this question because I think it can be solved using a simpler syntax than the convoluted try-catch block. The Laravel documentation is pretty brief on this subject.
Instead of using try-catch, you can just use the DB::transaction(){...}
wrapper like this:
// MyController.php
public function store(Request $request) {
return DB::transaction(function() use ($request) {
$user = User::create([
'username' => $request->post('username')
]);
// Add some sort of "log" record for the sake of transaction:
$log = Log::create([
'message' => 'User Foobar created'
]);
// Lets add some custom validation that will prohibit the transaction:
if($user->id > 1) {
throw AnyException('Please rollback this transaction');
}
return response()->json(['message' => 'User saved!']);
});
};
You should then see that the User and the Log record cannot exist without eachother.
Some notes on the implementation above:
return
the transaction, so that you can use the response()
you return within its callback.throw
an exception if you want the transaction to be rollbacked (or have a nested function that throws the exception for you automatically, like an SQL exception from within Eloquent).id
, updated_at
, created_at
and any other fields are AVAILABLE AFTER CREATION for the $user
object (for the duration of this transaction). The transaction will run through any of the creation logic you have. HOWEVER, the whole record is discarded when the AnyException
is thrown. This means that for instance an auto-increment column for id
does get incremented on failed transactions.Tested on Laravel 5.8
here is an example on how ellipsize works without using deprecated android:singleLine="true"
in a ConstraintLayout:
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="13sp"
android:ellipsize="end"
android:maxLines="2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:text="long long long long long long text text text" />
remember if you have a text that is supposed to be in a single line, then change the maxLines to 1.
That looks correct to me. If I were to change anything, I would stop using the Collections.synchronizedMap() and synchronize everything the same way, just to make it clearer.
Also, I'd replace
if (synchronizedMap.containsKey(key)) {
synchronizedMap.get(key).add(value);
}
else {
List<String> valuesList = new ArrayList<String>();
valuesList.add(value);
synchronizedMap.put(key, valuesList);
}
with
List<String> valuesList = synchronziedMap.get(key);
if (valuesList == null)
{
valuesList = new ArrayList<String>();
synchronziedMap.put(key, valuesList);
}
valuesList.add(value);
In order to assign a variable safely you have to use the SET-SELECT statement:
SET @PrimaryContactKey = (SELECT c.PrimaryCntctKey
FROM tarcustomer c, tarinvoice i
WHERE i.custkey = c.custkey
AND i.invckey = @tmp_key)
Make sure you have both a starting and an ending parenthesis!
The reason the SET-SELECT version is the safest way to set a variable is twofold.
1. The SELECT returns several posts
What happens if the following select results in several posts?
SELECT @PrimaryContactKey = c.PrimaryCntctKey
FROM tarcustomer c, tarinvoice i
WHERE i.custkey = c.custkey
AND i.invckey = @tmp_key
@PrimaryContactKey
will be assigned the value from the last post in the result.
In fact @PrimaryContactKey
will be assigned one value per post in the result, so it will consequently contain the value of the last post the SELECT-command was processing.
Which post is "last" is determined by any clustered indexes or, if no clustered index is used or the primary key is clustered, the "last" post will be the most recently added post. This behavior could, in a worst case scenario, be altered every time the indexing of the table is changed.
With a SET-SELECT statement your variable will be set to null
.
2. The SELECT returns no posts
What happens, when using the second version of the code, if your select does not return a result at all?
In a contrary to what you may believe the value of the variable will not be null - it will retain it's previous value!
This is because, as stated above, SQL will assign a value to the variable once per post - meaning it won't do anything with the variable if the result contains no posts. So, the variable will still have the value it had before you ran the statement.
With the SET-SELECT statement the value will be null
.
if your wanting to use jQuery for this, try the following code.
$('select option[value="1"]').attr("selected",true);
Updated:
Following a comment from Vivek, correctly pointed out steven spielberg wanted to select the option via its Text value.
Here below is the updated code.
$('select option:contains("it\'s me")').prop('selected',true);
You need to use the :contains(text)
selector to find via the containing text.
Also jQuery prop offeres better support for Internet Explorer when getting and setting attributes.
This query should identify columns that are potential problems...
SELECT *
FROM [source].INFORMATION_SCHEMA.COLUMNS src
INNER JOIN [dest].INFORMATION_SCHEMA.COLUMNS dst
ON dst.COLUMN_NAME = src.COLUMN_NAME
WHERE dst.CHARACTER_MAXIMUM_LENGTH < src.CHARACTER_MAXIMUM_LENGTH
You can use .toString
method to convert Uri to String in java
Uri uri = Uri.parse("Http://www.google.com");
String url = uri.toString();
This method convert Uri to String easily
You will not be able to find out the password he chose. However, you may create a new user or set a new password to the existing user.
Usually, you can login as the postgres user:
Open a Terminal and do sudo su postgres
.
Now, after entering your admin password, you are able to launch psql
and do
CREATE USER yourname WITH SUPERUSER PASSWORD 'yourpassword';
This creates a new admin user. If you want to list the existing users, you could also do
\du
to list all users and then
ALTER USER yourusername WITH PASSWORD 'yournewpass';
You just need to add this line to the window there:
exec (your stored proc name) (and possibly add parameters)
What is your stored proc called, and what parameters does it expect?
You can achieve this by controlling the formatting of the old/new/unchanged lines in GNU diff
output:
diff --new-line-format="" --unchanged-line-format="" file1 file2
The input files should be sorted for this to work. With bash
(and zsh
) you can sort in-place with process substitution <( )
:
diff --new-line-format="" --unchanged-line-format="" <(sort file1) <(sort file2)
In the above new and unchanged lines are suppressed, so only changed (i.e. removed lines in your case) are output. You may also use a few diff
options that other solutions don't offer, such as -i
to ignore case, or various whitespace options (-E
, -b
, -v
etc) for less strict matching.
Explanation
The options --new-line-format
, --old-line-format
and --unchanged-line-format
let you control the way diff
formats the differences, similar to printf
format specifiers. These options format new (added), old (removed) and unchanged lines respectively. Setting one to empty "" prevents output of that kind of line.
If you are familiar with unified diff format, you can partly recreate it with:
diff --old-line-format="-%L" --unchanged-line-format=" %L" \
--new-line-format="+%L" file1 file2
The %L
specifier is the line in question, and we prefix each with "+" "-" or " ", like diff -u
(note that it only outputs differences, it lacks the ---
+++
and @@
lines at the top of each grouped change).
You can also use this to do other useful things like number each line with %dn
.
The diff
method (along with other suggestions comm
and join
) only produce the expected output with sorted input, though you can use <(sort ...)
to sort in place. Here's a simple awk
(nawk) script (inspired by the scripts linked-to in Konsolebox's answer) which accepts arbitrarily ordered input files, and outputs the missing lines in the order they occur in file1.
# output lines in file1 that are not in file2
BEGIN { FS="" } # preserve whitespace
(NR==FNR) { ll1[FNR]=$0; nl1=FNR; } # file1, index by lineno
(NR!=FNR) { ss2[$0]++; } # file2, index by string
END {
for (ll=1; ll<=nl1; ll++) if (!(ll1[ll] in ss2)) print ll1[ll]
}
This stores the entire contents of file1 line by line in a line-number indexed array ll1[]
, and the entire contents of file2 line by line in a line-content indexed associative array ss2[]
. After both files are read, iterate over ll1
and use the in
operator to determine if the line in file1 is present in file2. (This will have have different output to the diff
method if there are duplicates.)
In the event that the files are sufficiently large that storing them both causes a memory problem, you can trade CPU for memory by storing only file1 and deleting matches along the way as file2 is read.
BEGIN { FS="" }
(NR==FNR) { # file1, index by lineno and string
ll1[FNR]=$0; ss1[$0]=FNR; nl1=FNR;
}
(NR!=FNR) { # file2
if ($0 in ss1) { delete ll1[ss1[$0]]; delete ss1[$0]; }
}
END {
for (ll=1; ll<=nl1; ll++) if (ll in ll1) print ll1[ll]
}
The above stores the entire contents of file1 in two arrays, one indexed by line number ll1[]
, one indexed by line content ss1[]
. Then as file2 is read, each matching line is deleted from ll1[]
and ss1[]
. At the end the remaining lines from file1 are output, preserving the original order.
In this case, with the problem as stated, you can also divide and conquer using GNU split
(filtering is a GNU extension), repeated runs with chunks of file1 and reading file2 completely each time:
split -l 20000 --filter='gawk -f linesnotin.awk - file2' < file1
Note the use and placement of -
meaning stdin
on the gawk
command line. This is provided by split
from file1 in chunks of 20000 line per-invocation.
For users on non-GNU systems, there is almost certainly a GNU coreutils package you can obtain, including on OSX as part of the Apple Xcode tools which provides GNU diff
, awk
, though only a POSIX/BSD split
rather than a GNU version.
Sample query
SET @runtot:=0;
SELECT
q1.d,
q1.c,
(@runtot := @runtot + q1.c) AS rt
FROM
(SELECT
DAYOFYEAR(date) AS d,
COUNT(*) AS c
FROM orders
WHERE hasPaid > 0
GROUP BY d
ORDER BY d) AS q1
Caucho Quercus can run PHP code on the jvm.
Something like this:
STARTUPINFO info={sizeof(info)};
PROCESS_INFORMATION processInfo;
if (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
WaitForSingleObject(processInfo.hProcess, INFINITE);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}
Check on yourCheckBox.Value
?
Inspired by the answers to this question, I made a simple counter batch script that keeps printing the progress value (0-100%) on the same line (overwritting the previous one). Maybe this will also be valuable to others looking for a similar solution.
Remark: The *
are non-printable characters, these should be entered using [Alt
+ Numpad 0
+ Numpad 8
] key combination, which is the backspace
character.
@ECHO OFF
FOR /L %%A in (0, 10, 100) DO (
ECHO|SET /P="****%%A%%"
CALL:Wait 1
)
GOTO:EOF
:Wait
SET /A "delay=%~1+1"
CALL PING 127.0.0.1 -n %delay% > NUL
GOTO:EOF
SetTimeout is used to make your set of code to execute after a specified time period so for your requirements its better to use setInterval because that will call your function every time at a specified time interval.
You've returned a pointer to a local variable. That's bad even if threads aren't involved.
The usual way to do this, when the thread that starts is the same thread that joins, would be to pass a pointer to an int, in a location managed by the caller, as the 4th parameter of pthread_create. This then becomes the (only) parameter to the thread's entry-point. You can (if you like) use the thread exit value to indicate success:
#include <pthread.h>
#include <stdio.h>
int something_worked(void) {
/* thread operation might fail, so here's a silly example */
void *p = malloc(10);
free(p);
return p ? 1 : 0;
}
void *myThread(void *result)
{
if (something_worked()) {
*((int*)result) = 42;
pthread_exit(result);
} else {
pthread_exit(0);
}
}
int main()
{
pthread_t tid;
void *status = 0;
int result;
pthread_create(&tid, NULL, myThread, &result);
pthread_join(tid, &status);
if (status != 0) {
printf("%d\n",result);
} else {
printf("thread failed\n");
}
return 0;
}
If you absolutely have to use the thread exit value for a structure, then you'll have to dynamically allocate it (and make sure that whoever joins the thread frees it). That's not ideal, though.
As another option, you can do look ups like:
class UserAdmin(admin.ModelAdmin):
list_display = (..., 'get_author')
def get_author(self, obj):
return obj.book.author
get_author.short_description = 'Author'
get_author.admin_order_field = 'book__author'
IF OBJECT_ID('master..test') is not null Drop table test
CREATE TABLE test (ID INTEGER, NAME VARCHAR (50), VALUE INTEGER );
INSERT INTO test VALUES (1, 'A', 4);
INSERT INTO test VALUES (1, 'A', 5);
INSERT INTO test VALUES (1, 'B', 8);
INSERT INTO test VALUES (2, 'C', 9);
select distinct NAME , LIST = Replace(Replace(Stuff((select ',', +Value from test where name = _a.name for xml path('')), 1,1,''),'<Value>', ''),'</Value>','') from test _a order by 1 desc
My table name is test , and for concatination I use the For XML Path('') syntax. The stuff function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.
STUFF functions looks like this : STUFF (character_expression , start , length ,character_expression )
character_expression Is an expression of character data. character_expression can be a constant, variable, or column of either character or binary data.
start Is an integer value that specifies the location to start deletion and insertion. If start or length is negative, a null string is returned. If start is longer than the first character_expression, a null string is returned. start can be of type bigint.
length Is an integer that specifies the number of characters to delete. If length is longer than the first character_expression, deletion occurs up to the last character in the last character_expression. length can be of type bigint.
Was looking for a way to do this using simple xml
, but couldn't find any helpful answers, so came up with this.
This works on pre-lollipop versions too, and is pretty close to the material design progress bar. You just need to use this drawable
as the indeterminate drawable
in the ProgressBar
layout.
<?xml version="1.0" encoding="utf-8"?><!--<layer-list>-->
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360">
<layer-list>
<item>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="-90"
android:toDegrees="-90">
<shape
android:innerRadiusRatio="2.5"
android:shape="ring"
android:thickness="2dp"
android:useLevel="true"><!-- this line fixes the issue for lollipop api 21 -->
<gradient
android:angle="0"
android:endColor="#007DD6"
android:startColor="#007DD6"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
</item>
<item>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="270">
<shape
android:innerRadiusRatio="2.6"
android:shape="ring"
android:thickness="4dp"
android:useLevel="true"><!-- this line fixes the issue for lollipop api 21 -->
<gradient
android:angle="0"
android:centerColor="#FFF"
android:endColor="#FFF"
android:startColor="#FFF"
android:useLevel="false" />
</shape>
</rotate>
</item>
</layer-list>
</rotate>
set the above drawable in ProgressBar as follows:
android:indeterminatedrawable="@drawable/above_drawable"
Maybe use in between better. It worked for me to get range then filter it
If you need locale-aware number formatting, use QLocale::toString instead.
My first suggestion is to use Designer to create your GUIs. Typing them out yourself sucks, takes more time, and you will definitely make more mistakes than Designer.
Here are some PyQt tutorials to help get you on the right track. The first one in the list is where you should start.
A good guide for figuring out what methods are available for specific classes is the PyQt4 Class Reference. In this case you would look up QLineEdit
and see the there is a text
method.
To answer your specific question:
To make your GUI elements available to the rest of the object, preface them with self.
import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QDialog, QApplication, QPushButton, QLineEdit, QFormLayout
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.le = QLineEdit()
self.le.setObjectName("host")
self.le.setText("Host")
self.pb = QPushButton()
self.pb.setObjectName("connect")
self.pb.setText("Connect")
layout = QFormLayout()
layout.addWidget(self.le)
layout.addWidget(self.pb)
self.setLayout(layout)
self.connect(self.pb, SIGNAL("clicked()"),self.button_click)
self.setWindowTitle("Learning")
def button_click(self):
# shost is a QString object
shost = self.le.text()
print shost
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
If using @FeignClient, add e.g.
produces = "application/json"
to the @RequestMapping annotation
You could try this to dynamically remove an object from an array without looping through it? Where e and t are just random objects.
>>> e = {'b':1, 'w': 2}
>>> t = {'b':1, 'w': 3}
>>> p = [e,t]
>>> p
[{'b': 1, 'w': 2}, {'b': 1, 'w': 3}]
>>>
>>> p.pop(p.index({'b':1, 'w': 3}))
{'b': 1, 'w': 3}
>>> p
[{'b': 1, 'w': 2}]
>>>
While you can use a virtualenv
, you don't need to. The trick is passing the PEP370 --user
argument to the setup.py
script. With the latest version of pip
, one way to do it is:
pip install --user mercurial
This should result in the hg
script being installed in $HOME/.local/bin/hg
and the rest of the hg package in $HOME/.local/lib/pythonx.y/site-packages/
.
Note, that the above is true for Python 2.6. There has been a bit of controversy among the Python core developers about what is the appropriate directory location on Mac OS X for PEP370-style user
installations. In Python 2.7 and 3.2, the location on Mac OS X was changed from $HOME/.local
to $HOME/Library/Python
. This might change in a future release. But, for now, on 2.7 (and 3.2, if hg
were supported on Python 3), the above locations will be $HOME/Library/Python/x.y/bin/hg
and $HOME/Library/Python/x.y/lib/python/site-packages
.