You should be injecting NameService inside providers array of your AppModule's NgModule metadata.
@NgModule({
providers: [MyService]
})
and be sure import in your component by same name (case sensitive),becouse SystemJs is case sensitive (by design). If you use different path name in your project files like this:
main.module.ts
import { MyService } from './MyService';
your-component.ts
import { MyService } from './Myservice';
then System js will make double imports
I encountered the same need and make a universal solution (node+browser) that works with the Next.js framework, for instance.
It even works with circular dependencies (thanks to json-stringify-safe
).
Although, I also built a serializer on top of it to remove unnecessary data (because it's not recommended to use a url longer than 2k chars, see What is the maximum length of a URL in different browsers?)
import StringifySafe from 'json-stringify-safe';
export const encodeQueryParameter = (data: object): string => {
return encodeURIComponent(StringifySafe(data)); // Use StringifySafe to avoid crash on circular dependencies
};
export const decodeQueryParameter = (query: string): object => {
return JSON.parse(decodeURIComponent(query));
};
And the unit tests (jest):
import { decodeQueryParameter, encodeQueryParameter } from './url';
export const data = {
'organisation': {
'logo': {
'id': 'ck2xjm2oj9lr60b32c6l465vx',
'linkUrl': null,
'linkTarget': '_blank',
'classes': null,
'style': null,
'defaultTransformations': { 'width': 200, 'height': 200, '__typename': 'AssetTransformations' },
'mimeType': 'image/png',
'__typename': 'Asset',
},
'theme': {
'primaryColor': '#1134e6',
'primaryAltColor': '#203a51',
'secondaryColor': 'white',
'font': 'neuzeit-grotesk',
'__typename': 'Theme',
'primaryColorG1': '#ffffff',
},
},
};
export const encodedData = '%7B%22organisation%22%3A%7B%22logo%22%3A%7B%22id%22%3A%22ck2xjm2oj9lr60b32c6l465vx%22%2C%22linkUrl%22%3Anull%2C%22linkTarget%22%3A%22_blank%22%2C%22classes%22%3Anull%2C%22style%22%3Anull%2C%22defaultTransformations%22%3A%7B%22width%22%3A200%2C%22height%22%3A200%2C%22__typename%22%3A%22AssetTransformations%22%7D%2C%22mimeType%22%3A%22image%2Fpng%22%2C%22__typename%22%3A%22Asset%22%7D%2C%22theme%22%3A%7B%22primaryColor%22%3A%22%231134e6%22%2C%22primaryAltColor%22%3A%22%23203a51%22%2C%22secondaryColor%22%3A%22white%22%2C%22font%22%3A%22neuzeit-grotesk%22%2C%22__typename%22%3A%22Theme%22%2C%22primaryColorG1%22%3A%22%23ffffff%22%7D%7D%7D';
describe(`utils/url.ts`, () => {
describe(`encodeQueryParameter`, () => {
test(`should encode a JS object into a url-compatible string`, async () => {
expect(encodeQueryParameter(data)).toEqual(encodedData);
});
});
describe(`decodeQueryParameter`, () => {
test(`should decode a url-compatible string into a JS object`, async () => {
expect(decodeQueryParameter(encodedData)).toEqual(data);
});
});
describe(`encodeQueryParameter <> decodeQueryParameter <> encodeQueryParameter`, () => {
test(`should encode and decode multiple times without altering data`, async () => {
const _decodedData: object = decodeQueryParameter(encodedData);
expect(_decodedData).toEqual(data);
const _encodedData: string = encodeQueryParameter(_decodedData);
expect(_encodedData).toEqual(encodedData);
const _decodedDataAgain: object = decodeQueryParameter(_encodedData);
expect(_decodedDataAgain).toEqual(data);
});
});
});
I had the same problem. my problem was that the version of the dependency had conflict with the elasticsearch version. check the version in ip:9200 and use the dependency version that match it
You can try to use TCPView utility.
Try to find in the localport column is there any process worked on "busy" port. Right click and end the process. Then try to start the Tomcat.
Its really works for me.
var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }" var fStr = str .replace(/([A-z]*)(:)/g, '"$1":') .replace(/'/g, "\"")
console.log(JSON.parse(fStr))
Sorry I am on my phone, here is a pic.
The above answers are fine but I would add to be sure the div is defined in the designer.cs file. This doesn't always happen when adding a div to the .aspx file. Not sure why but there are threads concerning this issue in this forum. Eg:
protected global::System.Web.UI.HtmlControls.HtmlGenericControl theDiv;
In my case I used sudo mkdir projectFolder
to create folder. It was owned by root user and I was logged in using non root user.
So I changed the folder permission using command sudo chown mynonrootuser:mynonrootuser projectFolder
and then it worked fine.
There are already a few good answers to this question, but for the sake of completeness I wanted to point out that the applicable section of the C standard is 5.1.2.2.3/15 (which is the same as section 1.9/9 in the C++11 standard). This section states that operators can only be regrouped if they are really associative or commutative.
/**
* Method that checks if all tables exist
* If a table doesnt exist it creates the table
*/
public void checkTables() {
try {
startConn();// method that connects with mysql database
String useDatabase = "USE " + getDatabase() + ";";
stmt.executeUpdate(useDatabase);
String[] tables = {"Patients", "Procedures", "Payments", "Procedurables"};//thats table names that I need to create if not exists
DatabaseMetaData metadata = conn.getMetaData();
for(int i=0; i< tables.length; i++) {
ResultSet rs = metadata.getTables(null, null, tables[i], null);
if(!rs.next()) {
createTable(tables[i]);
System.out.println("Table " + tables[i] + " created");
}
}
} catch(SQLException e) {
System.out.println("checkTables() " + e.getMessage());
}
closeConn();// Close connection with mysql database
}
A really easy way to do it is to create an ODBC link in EXCEL and run SP_WHO2 from there.
You can Refresh whenever you like and because it's EXCEL everything can be manipulated easily!
I think you need to use Expr
with ->set()
(However THIS IS NOT SAFE and you shouldn't do it):
$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
->set('u.username', $qb->expr()->literal($username))
->set('u.email', $qb->expr()->literal($email))
->where('u.id = ?1')
->setParameter(1, $editId)
->getQuery();
$p = $q->execute();
It's much safer to make all your values parameters instead:
$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
->set('u.username', '?1')
->set('u.email', '?2')
->where('u.id = ?3')
->setParameter(1, $username)
->setParameter(2, $email)
->setParameter(3, $editId)
->getQuery();
$p = $q->execute();
Extra Tips:
Multiple "nots", input that is NOT hidden and NOT disabled:
:not([type="hidden"]):not([disabled])
Also did you know you can do this:
node.parentNode.querySelectorAll('div');
This is equivelent to jQuery's:
$(node).parent().find('div');
Which will effectively find all divs in "node" and below recursively, HOT DAMN!
Less no longer evaluates expression inside calc
by default since v3.00
.
Original answer (Less v1.x...2.x
):
Do this:
body { width: calc(~"100% - 250px - 1.5em"); }
In Less 1.4.0 we will have a strictMaths
option which requires all Less calculations to be within brackets, so the calc
will work "out-of-the-box". This is an option since it is a major breaking change. Early betas of 1.4.0 had this option on by default. The release version has it off by default.
The proposed standard file is /etc/os-release
. See http://www.freedesktop.org/software/systemd/man/os-release.html
You can execute something like:
$ source /etc/os-release
$ echo $ID
fedora
$ echo $VERSION_ID
17
$ echo $VERSION
17 (Beefy Miracle)
BigDecimal obj = new BigDecimal("100");
if(obj.intValue()>0)
System.out.println("yes");
When you write a lambda expression, the argument list to the left of ->
can be either a parenthesized argument list (possibly empty), or a single identifier without any parentheses. But in the second form, the identifier cannot be declared with a type name. Thus:
this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name));
is incorrect syntax; but
this.stops.stream().filter((Stop s)-> s.getStation().getName().equals(name));
is correct. Or:
this.stops.stream().filter(s -> s.getStation().getName().equals(name));
is also correct if the compiler has enough information to figure out the types.
<b>request.META</b><br>
{% for k_meta, v_meta in request.META.items %}
<code>{{ k_meta }}</code> : {{ v_meta }} <br>
{% endfor %}
Typically you use String.StartsWith
/EndsWith
/Contains
. For example:
var portCode = Database.DischargePorts
.Where(p => p.PortName.Contains("BALTIMORE"))
.Single()
.PortCode;
I don't know if there's a way of doing proper regular expressions via LINQ to SQL though. (Note that it really does depend on which provider you're using - it would be fine in LINQ to Objects; it's a matter of whether the provider can convert the call into its native query format, e.g. SQL.)
EDIT: As BitKFu says, Single
should be used when you expect exactly one result - when it's an error for that not to be the case. Options of SingleOrDefault
, FirstOrDefault
or First
should be used depending on exactly what's expected.
@Ahmad's answer is working but if you just want to git ignore 1 specific file or few files do as @Nicolas suggests
add filename to .gitignore file
[remove filename (file path) from git cache
git rm --cached filename
commit changes
git add filename
git commit -m "add filename to .gitignore"
git rm -r --cached .
and add back all and commit them it will pollute your git history (it will show that you add a lot of files at one commit) not sure am I expressing my thought right but hope you get the pointJust pass var2 as an extra argument to one of the apply functions.
mylist <- list(a=1,b=2,c=3)
myfxn <- function(var1,var2){
var1*var2
}
var2 <- 2
sapply(mylist,myfxn,var2=var2)
This passes the same var2
to every call of myfxn
. If instead you want each call of myfxn
to get the 1st/2nd/3rd/etc. element of both mylist
and var2
, then you're in mapply
's domain.
Why can't operator<<
function for streaming objects to std::cout
or to a file be a member function?
Let's say you have:
struct Foo
{
int a;
double b;
std::ostream& operator<<(std::ostream& out) const
{
return out << a << " " << b;
}
};
Given that, you cannot use:
Foo f = {10, 20.0};
std::cout << f;
Since operator<<
is overloaded as a member function of Foo
, the LHS of the operator must be a Foo
object. Which means, you will be required to use:
Foo f = {10, 20.0};
f << std::cout
which is very non-intuitive.
If you define it as a non-member function,
struct Foo
{
int a;
double b;
};
std::ostream& operator<<(std::ostream& out, Foo const& f)
{
return out << f.a << " " << f.b;
}
You will be able to use:
Foo f = {10, 20.0};
std::cout << f;
which is very intuitive.
Once you have cloned the repo, you have everything: you can then hg up branchname
or hg up tagname
to update your working copy.
UP: hg up
is a shortcut of hg update
, which also has hg checkout
alias for people with git
habits.
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
I am not sure, but might be what you want:
var c = 0;
function setBgPosition()
{
var numbers = [0, -120, -240, -360, -480, -600, -720];
function run()
{
Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
if (c<=numbers.length)
{
setTimeout(run, 200);
}
else
{
Ext.get('common-spinner').setStyle('background-position', numbers[0] + 'px 0px');
}
}
setTimeout(run, 200);
}
setBgPosition();
Some control-flow tricks, finally
around a return
statement:
int getCount() {
try { return 1; }
finally { System.out.println("Bye!"); }
}
The rules for definite assignment will check that a final variable is always assigned through a simple control-flow analysis:
final int foo;
if(...)
foo = 1;
else
throw new Exception();
foo+1;
What I did is first check what are the running processes by
SELECT * FROM pg_stat_activity WHERE state = 'active';
Find the process you want to kill, then type:
SELECT pg_cancel_backend(<pid of the process>)
This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.
If the process cannot be killed, try:
SELECT pg_terminate_backend(<pid of the process>)
add_header
works as well with proxy_pass
as without. I just today set up a configuration where I've used exactly that directive. I have to admit though that I've struggled as well setting this up without exactly recalling the reason, though.
Right now I have a working configuration and it contains the following (among others):
server {
server_name .myserver.com
location / {
proxy_pass http://mybackend;
add_header X-Upstream $upstream_addr;
}
}
Before nginx 1.7.5
add_header worked only on successful responses, in contrast to the HttpHeadersMoreModule mentioned by Sebastian Goodman in his answer.
Since nginx 1.7.5
you can use the keyword always
to include custom headers even in error responses. For example:
add_header X-Upstream $upstream_addr always;
Limitation: You cannot override the server
header value using add_header
.
You can simply write
string time = dateTimeObect.ToString("HH:mm");
Here is a SUMMARY of all the major answers above (or maybe below later :)
For modern browsers, put css wherever you like it. They would analyze your html file (which they call speculative parsing) and start downloading css in parallel with html parsing.
For old browsers keep putting css on top (if you don't want to show a naked but interactive page first).
For all browsers, put javascript as farther down on the page as possible, since it will halt parsing of your html. Preferably, download it asynchronously (i.e., ajax call)
There are also, some experimental results for a particular case which claims putting javascript first (as opposed to traditional wisdom of putting CSS first) gives better performance but there is no logical reasoning given for it, and lacks validation regarding widespread applicability, so you can ignore it for now.
So, to answer the question: Yes. The recommendation to include the CSS before JS is invalid for the modern browsers. Put CSS wherever you like, and put JS towards the end, as possible.
Add a DoEvents function inside the loop, see below.
You may also want to ensure that the Status bar is visible to the user and reset it when your code completes.
Sub ProgressMeter()
Dim booStatusBarState As Boolean
Dim iMax As Integer
Dim i As Integer
iMax = 10000
Application.ScreenUpdating = False
''//Turn off screen updating
booStatusBarState = Application.DisplayStatusBar
''//Get the statusbar display setting
Application.DisplayStatusBar = True
''//Make sure that the statusbar is visible
For i = 1 To iMax ''// imax is usually 30 or so
fractionDone = CDbl(i) / CDbl(iMax)
Application.StatusBar = Format(fractionDone, "0%") & " done..."
''// or, alternatively:
''// statusRange.value = Format(fractionDone, "0%") & " done..."
''// Some code.......
DoEvents
''//Yield Control
Next i
Application.DisplayStatusBar = booStatusBarState
''//Reset Status bar display setting
Application.StatusBar = False
''//Return control of the Status bar to Excel
Application.ScreenUpdating = True
''//Turn on screen updating
End Sub
I had the similar issue. its resolved for me with a simple command.
lsnrctl start
The Network Adapter exception is caused because:
lsnrctl
utility.Try to start the listener using the command prompt:
cmd
in the search field, and when cmd
shows up in the list of options, right click it and select ‘Run as Administrator’.lsnrctl start
without the quotes and press Enter.Exit
and press Enter.Hope it helps.
You can use figure
to create a new plot, for example, or use close
after the first plot.
routes.MapRoute(
"Area",
"{area}/",
new { area = "AreaZ", controller = "ControlerX ", action = "ActionY " }
);
Have you tried that ?
For a horizontally centered DIV:
#outer {
width: 100%;
text-align: center;
}
#inner {
display: inline-block;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Yes. The casts are redundant. In your expression:
true == 1
Integral promotion applies and the bool value will be promoted to an int
and this promotion must yield 1.
Reference: 4.7 [conv.integral] / 4: If the source type is bool
... true
is converted to one.
elementFormDefault="qualified" is used to control the usage of namespaces in XML instance documents (.xml file), rather than namespaces in the schema document itself (.xsd file).
By specifying elementFormDefault="qualified" we enforce namespace declaration to be used in documents validated with this schema.
It is common practice to specify this value to declare that the elements should be qualified rather than unqualified. However, since attributeFormDefault="unqualified" is the default value, it doesn't need to be specified in the schema document, if one does not want to qualify the namespaces.
Try this.
ALTER PROCEDURE [dbo].[sp_ClientNotes_update]
@id uniqueidentifier,
@ordering smallint = NULL,
@title nvarchar(20) = NULL,
@content text = NULL
AS
BEGIN
SET NOCOUNT ON;
UPDATE tbl_ClientNotes
SET ordering=ISNULL(@ordering,ordering),
title=ISNULL(@title,title),
content=ISNULL(@content, content)
WHERE id=@id
END
It might also be worth adding an extra part to the WHERE
clause, if you use transactional replication then it will send another update to the subscriber if all are NULL, to prevent this.
WHERE id=@id AND (@ordering IS NOT NULL OR
@title IS NOT NULL OR
@content IS NOT NULL)
Go to Synaptic package manager. Reload -> Search for python -> select the python package you want -> Submit -> Install Works for me ;)
Exactly, the package you need to install is python-dev.
The MOUSEBUTTONDOWN
event occurs once when you click the mouse button and the MOUSEBUTTONUP
event occurs once when the mouse button is released. The pygame.event.Event()
object has two attributes that provide information about the mouse event. pos
is a tuple that stores the position that was clicked. button
stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event
.
Use the rect
attribute of the pygame.sprite.Sprite
object and the collidepoint
method to see if the Sprite was clicked.
Pass the list of events to the update
method of the pygame.sprite.Group
so that you can process the events in the Sprite class:
class SpriteObject(pygame.sprite.Sprite):
# [...]
def update(self, event_list):
for event in event_list:
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
# [...]
my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)
# [...]
run = True
while run:
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
group.update(event_list)
# [...]
Minimal example: repl.it/@Rabbid76/PyGame-MouseClick
import pygame
class SpriteObject(pygame.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.original_image, color, (25, 25), 25)
self.click_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.click_image, color, (25, 25), 25)
pygame.draw.circle(self.click_image, (255, 255, 255), (25, 25), 25, 4)
self.image = self.original_image
self.rect = self.image.get_rect(center = (x, y))
self.clicked = False
def update(self, event_list):
for event in event_list:
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
self.clicked = not self.clicked
self.image = self.click_image if self.clicked else self.original_image
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])
run = True
while run:
clock.tick(60)
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
group.update(event_list)
window.fill(0)
group.draw(window)
pygame.display.flip()
pygame.quit()
exit()
See further Creating multiple sprites with different update()'s from the same sprite class in Pygame
The current position of the mouse can be determined via pygame.mouse.get_pos()
. The return value is a tuple that represents the x and y coordinates of the mouse cursor. pygame.mouse.get_pressed()
returns a list of Boolean values ??that represent the state (True
or False
) of all mouse buttons. The state of a button is True
as long as a button is held down. When multiple buttons are pressed, multiple items in the list are True
. The 1st, 2nd and 3rd elements in the list represent the left, middle and right mouse buttons.
Detect evaluate the mouse states in the Update
method of the pygame.sprite.Sprite
object:
class SpriteObject(pygame.sprite.Sprite):
# [...]
def update(self, event_list):
mouse_pos = pygame.mouse.get_pos()
mouse_buttons = pygame.mouse.get_pressed()
if self.rect.collidepoint(mouse_pos) and any(mouse_buttons):
# [...]
my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)
# [...]
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
group.update(event_list)
# [...]
Minimal example: repl.it/@Rabbid76/PyGame-MouseHover
import pygame
class SpriteObject(pygame.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.original_image, color, (25, 25), 25)
self.hover_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.hover_image, color, (25, 25), 25)
pygame.draw.circle(self.hover_image, (255, 255, 255), (25, 25), 25, 4)
self.image = self.original_image
self.rect = self.image.get_rect(center = (x, y))
self.hover = False
def update(self):
mouse_pos = pygame.mouse.get_pos()
mouse_buttons = pygame.mouse.get_pressed()
#self.hover = self.rect.collidepoint(mouse_pos)
self.hover = self.rect.collidepoint(mouse_pos) and any(mouse_buttons)
self.image = self.hover_image if self.hover else self.original_image
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
group.update()
window.fill(0)
group.draw(window)
pygame.display.flip()
pygame.quit()
exit()
@echo off
set startbuild=%TIME%
C:\WINDOWS\Microsoft.NET\Framework\v3.5\msbuild.exe c:\link.xml /flp1:logfile=c:\link\errors.log;errorsonly /flp2:logfile=c:\link\warnings.log;warningsonly || goto :error
copy c:\app_offline.htm "\\lawpccnweb01\d$\websites\OperationsLinkWeb\app_offline.htm"
del \\lawpccnweb01\d$\websites\OperationsLinkWeb\bin\ /Q
echo Start Copy: %TIME%
set copystart=%TIME%
xcopy C:\link\_PublishedWebsites\OperationsLink \\lawpccnweb01\d$\websites\OperationsLinkWeb\ /s /y /d
del \\lawpccnweb01\d$\websites\OperationsLinkWeb\app_offline.htm
echo Started Build: %startbuild%
echo Started Copy: %copystart%
echo Finished Copy: %TIME%
c:\link\warnings.log
:error
c:\link\errors.log
" To solve this problem You need set ServerName.
1: $ vim /etc/apache2/conf.d/name
For example set add ServerName localhost or any other name:
2: ServerName localhost Restart Apache 2
3: $ service apache restart
For this example I use Ubuntu 11.10.1.125"
It you can live with a fixed size, arrays will will be faster and need less memory.
If you need the flexibility of the List interface with adding and removing elements, the question remains which implementation you should choose. Often ArrayList is recommended and used for any case, but also ArrayList has its performance problems if elements at the beginning or in the middle of the list must be removed or inserted.
You therefore may want to have a look at http://java.dzone.com/articles/gaplist-%E2%80%93-lightning-fast-list which introduces GapList. This new list implementation combines the strengths of both ArrayList and LinkedList resulting in very good performance for nearly all operations.
Instead of having the android:actionMenuTextAppearance
item under your action bar style, move it under your app theme.
In newer versions of CMake you can set compiler and linker flags for a single target with target_compile_options
and target_link_libraries
respectively (yes, the latter sets linker options too):
target_compile_options(first-test PRIVATE -fexceptions)
The advantage of this method is that you can control propagation of options to other targets that depend on this one via PUBLIC
and PRIVATE
.
As of CMake 3.13 you can also use target_link_options
to add linker options which makes the intent more clear.
Change control panel Java's option about proxy to "direct", change window's internet option to not use proxy and reboot. It worked for me.
By typing 'jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10'
in Anaconda
PowerShell
or prompt, the Jupyter notebook will open with the new configuration. Try now to run your query.
Similar to C# casting to (int)
with just using standard lib:
Math.trunc(1.6) // 1
Math.trunc(-1.6) // -1
With Python 3 I had this problem:
self.path = 'T:\PythonScripts\Projects\Utilities'
produced this error:
self.path = 'T:\PythonScripts\Projects\Utilities'
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
position 25-26: truncated \UXXXXXXXX escape
the fix that worked is:
self.path = r'T:\PythonScripts\Projects\Utilities'
It seems the '\U' was producing an error and the 'r' preceding the string turns off the eight-character Unicode escape (for a raw string) which was failing. (This is a bit of an over-simplification, but it works if you don't care about unicode)
Hope this helps someone
I found the solution below on this page:
x="test\ me"
eval cd $x
A combination of \
in a double-quoted text constant and an eval
before cd
makes it work like a charm!
With the newer versions of angularjs the correct answer to this question is to use ng-if
:
<ul>
<li ng-if="list.length === 0">( No items in this list yet! )</li>
<li ng-repeat="item in list">{{ item }}</li>
</ul>
This solution will not flicker when the list is about to download either because the list has to be defined and with a length of 0 for the message to display.
Here is a plunker to show it in use: http://plnkr.co/edit/in7ha1wTlpuVgamiOblS?p=preview
Tip: You can also show a loading text or spinner:
<li ng-if="!list">( Loading... )</li>
Usage:
sftp("file:/C:/home/file.txt", "ssh://user:pass@host/home");
sftp("ssh://user:pass@host/home/file.txt", "file:/C:/home");
Refer: http://www.wellho.net/mouth/754_tar-jar-war-ear-sar-files.html
tar (tape archives) - Format used is file written in serial units of fileName, fileSize, fileData - no compression. can be huge
Jar (java archive) - compression techniques used - generally contains java information like class/java files. But can contain any files and directory structure
war (web application archives) - similar like jar files only have specific directory structure as per JSP/Servlet spec for deployment purposes
ear (enterprise archives) - similar like jar files. have directory structure following J2EE requirements so that it can be deployed on J2EE application servers. - can contain multiple JAR and WAR files
You can use glut libraries like this:
for a sphere:
glutWireSphere(radius,20,20);
for a Cylinder:
GLUquadric *quadratic = gluNewQuadric();
gluQuadricDrawStyle(quadratic,GLU_LINE);
gluCylinder(quadratic,1,1,1,12,1);
for a Cube:
glutWireCube(1.5);
As written in the documentation, the way to trigger form validation programmatically is to invoke validator.form()
var validator = $( "#myform" ).validate();
validator.form();
The problem is where you are executing:
rankings[kvp.Key] = rankings[kvp.Key] + 4;
You cannot modify the collection you are iterating through in a foreach loop. A foreach loop requires the loop to be immutable during iteration.
Instead, use a standard 'for' loop or create a new loop that is a copy and iterate through that while updating your original.
Here's a very simple, compact solution. str contains the variable of whatever you want to do the upper case on.
StringBuilder b = new StringBuilder(str);
int i = 0;
do {
b.replace(i, i + 1, b.substring(i,i + 1).toUpperCase());
i = b.indexOf(" ", i) + 1;
} while (i > 0 && i < b.length());
System.out.println(b.toString());
It's best to work with StringBuilder because String is immutable and it's inefficient to generate new strings for each word.
Sometimes using row.getLastCellNum()
gives you a higher value than what is actually filled in the file.
I used the method below to get the last column index that contains an actual value.
private int getLastFilledCellPosition(Row row) {
int columnIndex = -1;
for (int i = row.getLastCellNum() - 1; i >= 0; i--) {
Cell cell = row.getCell(i);
if (cell == null || CellType.BLANK.equals(cell.getCellType()) || StringUtils.isBlank(cell.getStringCellValue())) {
continue;
} else {
columnIndex = cell.getColumnIndex();
break;
}
}
return columnIndex;
}
You can add the image into a comment.
Right-click cell > Insert Comment > right-click on shaded (grey area) on outside of comment box > Format Comment > Colors and Lines > Fill > Color > Fill Effects > Picture > (Browse to picture) > Click OK
Image will appear on hover over.
Microsoft Office 365 (2019) introduced new things called comments and renamed the old comments as "notes". Therefore in the steps above do New Note
instead of Insert Comment
. All other steps remain the same and the functionality still exists.
There is also a $20 product for Windows - Excel Image Assistant...
I know its quite late to answer this, but I guess it will help anyone ahead.
Well using CSS3 FlexBox. It can be acheived.
Make you header as display:flex
and divide its entire width into 3 parts. In the first part I have placed the logo, the searchbar in second part and buttons container in last part.
apply justify-content: between
to the header container and flex-grow:1
to the searchbar.
That's it. The sample code is below.
#header {_x000D_
background-color: #323C3E;_x000D_
justify-content: space-between;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
#searchBar, img{_x000D_
align-self: center;_x000D_
}_x000D_
_x000D_
#searchBar{_x000D_
flex-grow:1;_x000D_
background-color: orange;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
#searchBar input {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.button {_x000D_
padding: 22px;_x000D_
}_x000D_
_x000D_
.buttonsHolder{_x000D_
display:flex;_x000D_
}
_x000D_
<div id="header" class="d-flex justify-content-between">_x000D_
<img src="img/logo.png" />_x000D_
<div id="searchBar">_x000D_
<input type="text" />_x000D_
</div>_x000D_
<div class="buttonsHolder">_x000D_
<div class="button orange inline" id="myAccount">_x000D_
My Account_x000D_
</div>_x000D_
<div class="button red inline" id="basket">_x000D_
Basket (2)_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
The destructor of A will run when its lifetime is over. If you want its memory to be freed and the destructor run, you have to delete it if it was allocated on the heap. If it was allocated on the stack this happens automatically (i.e. when it goes out of scope; see RAII). If it is a member of a class (not a pointer, but a full member), then this will happen when the containing object is destroyed.
class A
{
char *someHeapMemory;
public:
A() : someHeapMemory(new char[1000]) {}
~A() { delete[] someHeapMemory; }
};
class B
{
A* APtr;
public:
B() : APtr(new A()) {}
~B() { delete APtr; }
};
class C
{
A Amember;
public:
C() : Amember() {}
~C() {} // A is freed / destructed automatically.
};
int main()
{
B* BPtr = new B();
delete BPtr; // Calls ~B() which calls ~A()
C *CPtr = new C();
delete CPtr;
B b;
C c;
} // b and c are freed/destructed automatically
In the above example, every delete and delete[] is needed. And no delete is needed (or indeed able to be used) where I did not use it.
auto_ptr
, unique_ptr
and shared_ptr
etc... are great for making this lifetime management much easier:
class A
{
shared_array<char> someHeapMemory;
public:
A() : someHeapMemory(new char[1000]) {}
~A() { } // someHeapMemory is delete[]d automatically
};
class B
{
shared_ptr<A> APtr;
public:
B() : APtr(new A()) {}
~B() { } // APtr is deleted automatically
};
int main()
{
shared_ptr<B> BPtr = new B();
} // BPtr is deleted automatically
Here's a simple test to see if you have browser support when working with local storage:
if(typeof(Storage)!=="undefined") {
console.log("localStorage and sessionStorage support!");
console.log("About to save:");
console.log(localStorage);
localStorage["somekey"] = 'hello';
console.log("Key saved:");
console.log(localStorage);
localStorage.removeItem("somekey"); //<--- key deleted here
console.log("key deleted:");
console.log(localStorage);
console.log("DONE ===");
} else {
console.log("Sorry! No web storage support..");
}
It worked for me as expected (I use Google Chrome). Adapted from: http://www.w3schools.com/html/html5_webstorage.asp.
Nothing works in my case using the scripts above but I was able to close these figures from eclipse console bar by clicking on Terminate ALL (two red nested squares icon).
I did it using below steps:
git reset --hard <commit key of the pull request>
git add
git commit --amend
git push -f origin <name of the remote branch of pull request>
Another option is to apply flex styling at the table row, and add the col-classes
to the table header / table data elements:
<table>
<thead>
<tr class="d-flex">
<th class="col-3">3 columns wide header</th>
<th class="col-sm-5">5 columns wide header</th>
<th class="col-sm-4">4 columns wide header</th>
</tr>
</thead>
<tbody>
<tr class="d-flex">
<td class="col-3">3 columns wide content</th>
<td class="col-sm-5">5 columns wide content</th>
<td class="col-sm-4">4 columns wide content</th>
</tr>
</tbody>
</table>
In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using
<encoder>
<pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern>
</encoder>
the %ex in pattern is what makes the difference
Maybe you cannot use manifest class from generated code in your project. So, you can use manifest class from android sdk "android.Manifest.permission.WRITE_EXTERNAL_STORAGE". But in Marsmallow version have 2 permission must grant are WRITE and READ EXTERNAL STORAGE in storage category. See my program, my program will request permission until user choose yes and do something after permissions is granted.
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(LoginActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(LoginActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(LoginActivity.this,
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE},
1);
} else {
//do something
}
} else {
//do something
}
Just add two lines of code to make orientation of recyclerview as horizontal. So add these lines when Initializing Recyclerview.
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
my_recycler.setLayoutManager(linearLayoutManager);
Why not make use of the meaningful data already there, instead of adding arbitrary data?
i.e. use <a href="/articles/5/page-title" class="article-link">
, and then you can programmatically get all article links on the page (via the classname) and the article ID (matching the regex /articles\/(\d+)/
against this.href
).
That error is caused by your Eclipse configuration. You can reduce it to a warning. Better still, use a Base64 encoder that isn't part of a non-public API. Apache Commons has one, or when you're already on Java 1.8, then use java.util.Base64
.
If you add:
<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>
in the head of the document it will start working as expected:
<script type="text/javascript">
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
Here's an example if you need to join more than 2 tables:
from d in context.dc_tpatient_bookingd
join bookingm in context.dc_tpatient_bookingm
on d.bookingid equals bookingm.bookingid into bookingmGroup
from m in bookingmGroup.DefaultIfEmpty()
join patient in dc_tpatient
on m.prid equals patient.prid into patientGroup
from p in patientGroup.DefaultIfEmpty()
Handling key events consistently is not at all easy.
Firstly, there are two different types of codes: keyboard codes (a number representing the key on the keyboard the user pressed) and character codes (a number representing a Unicode character). You can only reliably get character codes in the keypress
event. Do not try to get character codes for keyup
and keydown
events.
Secondly, you get different sets of values in a keypress
event to what you get in a keyup
or keydown
event.
I recommend this page as a useful resource. As a summary:
If you're interested in detecting a user typing a character, use the keypress
event. IE bizarrely only stores the character code in keyCode
while all other browsers store it in which
. Some (but not all) browsers also store it in charCode
and/or keyCode
. An example keypress handler:
function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
alert(charStr);
}
If you're interested in detecting a non-printable key (such as a cursor key), use the keydown
event. Here keyCode
is always the property to use. Note that keyup
events have the same properties.
function(evt) {
evt = evt || window.event;
var keyCode = evt.keyCode;
// Check for left arrow key
if (keyCode == 37) {
alert("Left arrow");
}
}
This helped and it supports a BLOB/TEXT columns.
CREATE TEMPORARY TABLE temp_table
AS
SELECT * FROM source_table WHERE id=2;
UPDATE temp_table SET id=NULL WHERE id=2;
INSERT INTO source_table SELECT * FROM temp_table;
DROP TEMPORARY TABLE temp_table;
USE source_table;
This worked for me while using mathtools
package.
\documentclass{article}
\usepackage{mathtools}
\begin{document}
\begin{equation}
\begin{multlined}
first term \\
second term
\end{multlined}
\end{equation}
\end{document}
I know this is an old post but I got the same error recently so for what it's worth, here's another solution:
This is usually a connection string error, please check the format of your connection string, you can look up 'entity framework connectionstring' or follow the suggestions above.
However, in my case my connection string was fine and the error was caused by something completely different so I hope this helps someone:
First I had an EDMX error: there was a new database table in the EDMX and the table did not exist in my database (funny thing is the error the error was not very obvious because it was not shown in my EDMX or output window, instead it was tucked away in visual studio in the 'Error List' window under the 'Warnings'). I resolved this error by adding the missing table to my database. But, I was actually busy trying to add a stored procedure and still getting the 'datasource' error so see below how i resolved it:
Stored procedure error: I was trying to add a stored procedure and everytime I added it via the EDMX design window I got a 'datasource' error. The solution was to add the stored procedure as blank (I kept the stored proc name and declaration but deleted the contents of the stored proc and replaced it with 'select 1' and retried adding it to the EDMX). It worked! Presumably EF didn't like something inside my stored proc. Once I'd added the proc to EF I was then able to update the contents of the proc on my database to what I wanted it to be and it works, 'datasource' error resolved.
weirdness
In fact when you open the pom.xml, you should see 5 tabs in the bottom. Click the pom.xml, and you can type whatever dependencies you want.
There seem to be a lot of issues related to the same error. For me it was the applications which I've installed from another iMac whose files where not present on my MacBook so Xcode was not able to find the files making the debugger to wait forever!
Solution: Deleting all the application which I've installed from the iMac helped me solve the problem.
If you don't want to lose the columns you shift past the end of your dataframe, simply append the required number first:
offset = 5
DF = DF.append([np.nan for x in range(offset)])
DF = DF.shift(periods=offset)
DF = DF.reset_index() #Only works if sequential index
All answers posted so far are giving the right solutions, however no one answer was able to properly explain the underlying cause of the concrete problem.
Facelets is a XML based view technology which uses XHTML+XML to generate HTML output. XML has five special characters which has special treatment by the XML parser:
<
the start of a tag.>
the end of a tag."
the start and end of an attribute value.'
the alternative start and end of an attribute value.&
the start of an entity (which ends with ;
).In case of &
which is not followed by #
(e.g.  
,  
, etc), the XML parser is implicitly looking for one of the five predefined entity names lt
, gt
, amp
, quot
and apos
, or any manually defined entity name. However, in your particular case, you was using &
as a JavaScript operator, not as an XML entity. This totally explains the XML parsing error you got:
The entity name must immediately follow the '&' in the entity reference
In essence, you're writing JavaScript code in the wrong place, a XML document instead of a JS file, so you should be escaping all XML special characters accordingly. The &
must be escaped as &
.
So, in your particular case, the
if (Modernizr.canvas && Modernizr.localstorage &&
must become
if (Modernizr.canvas && Modernizr.localstorage &&
to make it XML-valid.
However, this makes the JavaScript code harder to read and maintain. As stated in Mozilla Developer Network's excellent document Writing JavaScript for XHTML, you should be placing the JavaScript code in a character data (CDATA) block. Thus, in JSF terms, that would be:
<h:outputScript>
<![CDATA[
// ...
]]>
</h:outputScript>
The XML parser will interpret the block's contents as "plain vanilla" character data and not as XML and hence interpret the XML special characters "as-is".
But, much better is to just put the JS code in its own JS file which you include by <script src>
, or in JSF terms, the <h:outputScript>
.
<h:outputScript name="onload.js" target="body" />
(note the target="body"
; this way JSF will automatically render the <script>
at the very end of <body>
, regardless of where <h:outputScript>
itself is located, hereby achieving the same effect as with window.onload
and $(document).ready()
; so you don't need to use those anymore in that script)
This way you don't need to worry about XML-special characters in your JS code. As an additional bonus, this gives you the opportunity to let the browser cache the JS file so that total response size is smaller.
I just used :before with the input and passed $ as the content
input{
margin-left: 20px;
}
input:before {
content: "$";
position: absolute;
}
And if you'd like to extract the differences between the two strings, you can use String::Diff.
curl -iv https://your.domain.io
That will give you cert and header output if you do not wish to use openssl command.
You can try this: In my case i am loading menu from database based on role based access, Write the code on your every view which menu your want to active based on your view.
<script type="text/javascript">
$(document).ready(function () {
$('li.active active-menu').removeClass('active active-menu');
$('a[href="/MgtCustomer/Index"]').closest('li').addClass('active active-menu');
});
</script>
In JSONLib you can use this:
String jsonTxt = JSONUtils.valueToString(json, 8, 4);
From the Javadoc:
You can write the where
clause as:
where (case when (:stateCode = '') then (1)
when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
else 0)
end) = 1;
Alternatively, remove the case
entirely:
where (:stateCode = '') or
((:stateCode != '') and vw.state_cd in (:stateCode));
Or, even better:
where (:stateCode = '') or vw.state_cd in (:stateCode)
If you're using ASP.NET MVC and Web API chances are you have the Newtonsoft.Json NuGet package installed.This library has a class called JObject which allows you to pass through multiple parameters:
Api Controller:
public class ProductController : ApiController
{
[HttpPost]
public void Post(Newtonsoft.Json.Linq.JObject data)
{
System.Diagnostics.Debugger.Break();
Product product = data["product"].ToObject<Product>();
Product product2 = data["product2"].ToObject<Product>();
int someRandomNumber = data["randomNumber"].ToObject<int>();
string productName = product.ProductName;
string product2Name = product2.ProductName;
}
}
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
}
View:
<script src="~/Scripts/angular.js"></script>
<script type="text/javascript">
var myApp = angular.module("app", []);
myApp.controller('controller', function ($scope, $http) {
$scope.AddProducts = function () {
var product = {
ProductID: 0,
ProductName: "Orange",
}
var product2 = {
ProductID: 1,
ProductName: "Mango",
}
var data = {
product: product,
product2: product2,
randomNumber:12345
};
$http.post("/api/Product", data).
success(function (data, status, headers, config) {
}).
error(function (data, status, headers, config) {
alert("An error occurred during the AJAX request");
});
}
});
</script>
<div ng-app="app" ng-controller="controller">
<input type="button" ng-click="AddProducts()" value="Get Full Name" />
</div>
update YourTable
set YourColumn = replace(YourColumn, '@domain2', '@domain1')
where charindex('@domain2', YourColumn) <> 0
ALTER TABLE *table_name*
MODIFY *column_name* DEFAULT *value*;
worked in Oracle
e.g:
ALTER TABLE MY_TABLE
MODIFY MY_COLUMN DEFAULT 1;
It can be done now with HTML5
See this post here HTML select form with option to enter custom value
<input type="text" list="cars" />
<datalist id="cars">
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</datalist>
When I used policy before I set the default authentication scheme into it as well. I had modified the DefaultPolicy
so it was slightly different. However the same should work for add policy as well.
services.AddAuthorization(options =>
{
options.AddPolicy(DefaultAuthorizedPolicy, policy =>
{
policy.Requirements.Add(new TokenAuthRequirement());
policy.AuthenticationSchemes = new List<string>()
{
CookieAuthenticationDefaults.AuthenticationScheme
}
});
});
Do take into consideration that by Default AuthenticationSchemes
property uses a read only list. I think it would be better to implement that instead of List as well.
So why is td default set to vertical-align: top;? I really don't know that yet. I would not dare to touch it. Instead add this to your stylesheet. It alters the buttons in the tables.
table .btn{
vertical-align: top;
}
In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.
However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.
In that case, you can use
jekyll serve --host 0.0.0.0
This binds your application to the host & next use following to connect to it from some other host
http://host's IP adress/4000
An elegant recursive solution that corresponds to the best answer explanation above. The core vector operation is only 4 lines. credit to "Guide to Competitive Programming" book from Laaksonen, Antti.
// #include <iostream>
#include <vector>
using namespace std;
vector<int> subset;
void search(int k, int n) {
if (k == n+1) {
// process subset - put any of your own application logic
// for (auto i : subset) cout<< i << " ";
// cout << endl;
}
else {
// include k in the subset
subset.push_back(k);
search(k+1, n);
subset.pop_back();
// don't include k in the subset
search(k+1,n);
}
}
int main() {
// find all subset between [1,3]
search(1, 3);
}
Here's a very simple way to do it;
int main()
{
int s=7,l=1;
vector <bool> v;
v.clear();
while (l <= 4)
{
v.push_back(s%2);
s /= 2;
l++;
}
for (l=(v.size()-1); l >= 0; l--)
{
cout<<v[l]<<" ";
}
return 0;
}
Based off of Asaf Katz's answer, here's a typescript version:
export function union<T> (...iterables: Array<Set<T>>): Set<T> {
const set = new Set<T>()
iterables.forEach(iterable => {
iterable.forEach(item => set.add(item))
})
return set
}
Most folders should be normal "755" and files, "644"
Laravel requires some folders to be writable for the web server user. You can use this command on unix based OSs.
sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache
I ran into the same problem and here's how I was able to fix it
keytool -list -alias androiddebugkey -keystore <project_file\android\app\debug.keystore>
I wrote a small helper method to read Paths
from your class resources. It is quite handy to use as it only needs a reference of the class you have stored your resources as well as the name of the resource itself.
public static Path getResourcePath(Class<?> resourceClass, String resourceName) throws URISyntaxException {
URL url = resourceClass.getResource(resourceName);
return Paths.get(url.toURI());
}
You'll need to order by the same field you're ordering by now, but descending.
As an example, if you have a time stamp when the upload was done called upload_time
, you'd do something like this;
For Pre-Laravel 4
return DB::table('files')->order_by('upload_time', 'desc')->first();
For Laravel 4 and onwards
return DB::table('files')->orderBy('upload_time', 'desc')->first();
For Laravel 5.7 and onwards
return DB::table('files')->latest('upload_time')->first();
This will order the rows in the files table by upload time, descending order, and take the first one. This will be the latest uploaded file.
I was fumbling for answers today, and think this would work...
=IF(C5=0, B5/1, IF(C5<0, (B5+ABS(C5)/1), IF(C5>0, (B5/C5)-1)))
C5 = Last Year, B5 = This Year
We have 3 IF statements in the cell.
IF Last Year is 0, then This Year divided by 1
IF Last Year is less than 0, then This Year + ABSolute value of Last Year divided by 1
IF Last Year is greater than 0, then This Year divided by Last Year minus 1
Using bootstrap with a little bit of customization, the following seems to work for me:
I need 3 partitions in my container and I tried this:
CSS:
.row.content {height: 100%; width:100%; position: fixed; }
.sidenav {
padding-top: 20px;
border: 1px solid #cecece;
height: 100%;
}
.midnav {
padding: 0px;
}
HTML:
<div class="container-fluid text-center">
<div class="row content">
<div class="col-md-2 sidenav text-left">Some content 1</div>
<div class="col-md-9 midnav text-left">Some content 2</div>
<div class="col-md-1 sidenav text-center">Some content 3</div>
</div>
</div>
Maybe a more Laravel way to solve this problem is to use a collection and loop it inserting with the model taking advantage of the timestamps.
<?php
use App\Continent;
use Illuminate\Database\Seeder;
class InitialSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
collect([
['name' => 'América'],
['name' => 'África'],
['name' => 'Europa'],
['name' => 'Asia'],
['name' => 'Oceanía'],
])->each(function ($item, $key) {
Continent::forceCreate($item);
});
}
}
EDIT:
Sorry for my misunderstanding. For bulk inserting this could help and maybe with this you can make good seeders and optimize them a bit.
<?php
use App\Continent;
use Carbon\Carbon;
use Illuminate\Database\Seeder;
class InitialSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$timestamp = Carbon::now();
$password = bcrypt('secret');
$continents = [
[
'name' => 'América'
'password' => $password,
'created_at' => $timestamp,
'updated_at' => $timestamp,
],
[
'name' => 'África'
'password' => $password,
'created_at' => $timestamp,
'updated_at' => $timestamp,
],
[
'name' => 'Europa'
'password' => $password,
'created_at' => $timestamp,
'updated_at' => $timestamp,
],
[
'name' => 'Asia'
'password' => $password,
'created_at' => $timestamp,
'updated_at' => $timestamp,
],
[
'name' => 'Oceanía'
'password' => $password,
'created_at' => $timestamp,
'updated_at' => $timestamp,
],
];
Continent::insert($continents);
}
}
To invert a boolean Series, use ~s
:
In [7]: s = pd.Series([True, True, False, True])
In [8]: ~s
Out[8]:
0 False
1 False
2 True
3 False
dtype: bool
Using Python2.7, NumPy 1.8.0, Pandas 0.13.1:
In [119]: s = pd.Series([True, True, False, True]*10000)
In [10]: %timeit np.invert(s)
10000 loops, best of 3: 91.8 µs per loop
In [11]: %timeit ~s
10000 loops, best of 3: 73.5 µs per loop
In [12]: %timeit (-s)
10000 loops, best of 3: 73.5 µs per loop
As of Pandas 0.13.0, Series are no longer subclasses of numpy.ndarray
; they are now subclasses of pd.NDFrame
. This might have something to do with why np.invert(s)
is no longer as fast as ~s
or -s
.
Caveat: timeit
results may vary depending on many factors including hardware, compiler, OS, Python, NumPy and Pandas versions.
Since PikkuKatja and glallen asked for a more general solution and I cannot comment yet, I'll write an answer. You can combine statements as in:
> df[df=="" | df==12] <- NA
> df
A B
1 <NA> <NA>
2 xyz <NA>
3 jkl 100
For factors, zxzak's code already yields factors:
> df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)))
> str(df)
'data.frame': 3 obs. of 2 variables:
$ A: Factor w/ 3 levels "","jkl","xyz": 1 3 2
$ B: Factor w/ 3 levels "","100","12": 3 1 2
If in trouble, I'd suggest to temporarily drop the factors.
df[] <- lapply(df, as.character)
5 years later-version:
Today, there are JS libraries for you, if you don't want to get into the nitty gritty of the different methods described on this page.
On of these is https://github.com/hubspot/offline. It checks for the connectivity of a pre-defined URI, by default your favicon. It automatically detects when the user's connectivity has been reestablished and provides neat events like up
and down
, which you can bind to in order to update your UI.
You're going to have to either use JS or write a function/method in whatever non-markup language you're using to do this. For instance you could write something that will save the status to a cookie or session variable then check for it on page load. If you want to do it without reloading the page then JS is going to be your only option.
I am late here but I resolved same kind of problem in this way that is simple and easy.
<select ng-model="blisterPackTemplateSelected" ng-change="selectedBlisterPack(blisterPackTemplateSelected)">
<option value="">Select Account</option>
<option ng-repeat="blisterPacks in blisterPackTemplates" value="{{blisterPacks.id}}">{{blisterPacks.name}}</option>
and the function for ng-change is as follows;
$scope.selectedBlisterPack= function (value) {
console.log($scope.blisterPackTemplateSelected);
};
Another option would be to add engine='python'
to the command pandas.read_csv(filename, sep='\t', engine='python')
In the ASP.NET world, I've tended to use the built-in BrowserCaps feature to write out a set of classes onto the body tag that enable you to target any combination of browser and platform.
So in pre-render, I would run something like this code (assuming you give your tag an ID and make it runat the server):
HtmlGenericControl _body = (HtmlGenericControl)this.FindControl("pageBody");
_body.Attributes.Add("class", Request.Browser.Platform + " " + Request.Browser.Browser + Request.Browser.MajorVersion);
This code enables you to then target a specific browser in your CSS like this:
.IE8 #nav ul li { .... }
.IE7 #nav ul li { .... }
.MacPPC.Firefox #nav ul li { .... }
We create a sub-class of System.Web.UI.MasterPage and make sure all of our master pages inherit from our specialised MasterPage so that every page gets these classes added on for free.
If you're not in an ASP.NET environment, you could use jQuery which has a browser plugin that dynamically adds similar class names on page-load.
This method has the benefit of removing conditional comments from your markup, and also of keeping both your main styles and your browser-specific styles in roughly the same place in your CSS files. It also means your CSS is more future-proof (since it doesn't rely on bugs that may be fixed) and helps your CSS code make much more sense since you only have to see
.IE8 #container { .... }
Instead of
* html #container { .... }
or worse!
You need to define a valid type of SelectParameter. This MSDN article describes the various types and how to use them.
Search, charts, one-click setup....
I needed to export log in one line for a specific branch.
So I probably came out with a simpler solution.
When doing git log --pretty=oneline --graph
we can see that all commit not done in the current branch are lines starting with |
So a simple grep -v
do the job:
git log --pretty=oneline --graph | grep -v "^|"
Of course you can change the pretty parameter if you need other info, as soon as you keep it in one line.
You probably want to remove merge commit too.
As the message start with "Merge branch", pipe another grep -v
and you're done.
In my specific ase, the final command was:
git log --pretty="%ad : %an, %s" --graph | grep -v "^|" | grep -v "Merge branch"
This downloaded the entire website for me:
wget --no-clobber --convert-links --random-wait -r -p -E -e robots=off -U mozilla http://site/path/
Use simple CSS height: 100%; matches the height of the parent and using height: 100vh matches the height of the viewport.
Use vh instead of %;
How about a real world solution.
If all you need is a "quick and dirty" way to write something to the event log without registering "custom sources" (requires admin rights), or providing "message files" (requires work and headache) just do this:
EventLog.WriteEntry(
".NET Runtime", //magic
"Your error message goes here!!",
EventLogEntryType.Warning,
1000); //magic
This way you'll be writing to an existing "Application" log without the annoying "The description for Event ID 0 cannot be found"
If you want the "magic" part explained I blogged about it here
Accessing package variables in a Script Component (of a Data Flow Task) is not the same as accessing package variables in a Script Task. For a Script Component, you first need to open the Script Transformation Editor (right-click on the component and select "Edit..."). In the Custom Properties section of the Script tab, you can enter (or select) the properties you want to make available to the script, either on a read-only or read-write basis: Then, within the script itself, the variables will be available as strongly-typed properties of the Variables object:
// Modify as necessary
public override void PreExecute()
{
base.PreExecute();
string thePath = Variables.FilePath;
// Do something ...
}
public override void PostExecute()
{
base.PostExecute();
string theNewValue = "";
// Do something to figure out the new value...
Variables.FilePath = theNewValue;
}
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
string thePath = Variables.FilePath;
// Do whatever needs doing here ...
}
One important caveat: if you need to write to a package variable, you can only do so in the PostExecute() method.
Regarding the code snippet:
IDTSVariables100 varCollection = null;
this.VariableDispenser.LockForRead("User::FilePath");
string XlsFile;
XlsFile = varCollection["User::FilePath"].Value.ToString();
varCollection
is initialized to null and never set to a valid value. Thus, any attempt to dereference it will fail.
I use this extension method to accomplish something similar:
public static string GetFriendlyTypeName(this Type t)
{
var typeName = t.Name.StripStartingWith("`");
var genericArgs = t.GetGenericArguments();
if (genericArgs.Length > 0)
{
typeName += "<";
foreach (var genericArg in genericArgs)
{
typeName += genericArg.GetFriendlyTypeName() + ", ";
}
typeName = typeName.TrimEnd(',', ' ') + ">";
}
return typeName;
}
public static string StripStartingWith(this string s, string stripAfter)
{
if (s == null)
{
return null;
}
var indexOf = s.IndexOf(stripAfter, StringComparison.Ordinal);
if (indexOf > -1)
{
return s.Substring(0, indexOf);
}
return s;
}
You use it like this:
[TestMethod]
public void GetFriendlyTypeName_ShouldHandleReallyComplexTypes()
{
typeof(Dictionary<string, Dictionary<string, object>>).GetFriendlyTypeName()
.ShouldEqual("Dictionary<String, Dictionary<String, Object>>");
}
This isn't quite what you're looking for, but it's helpful in demonstrating the techniques involved.
ng-change
1To make an <input type=file>
element work the ng-change directive, it needs a custom directive that works with the ng-model directive.
<input type="file" files-input ng-model="fileList"
ng-change="onInputChange()" multiple />
angular.module("app",[])_x000D_
.directive("filesInput", function() {_x000D_
return {_x000D_
require: "ngModel",_x000D_
link: function postLink(scope,elem,attrs,ngModel) {_x000D_
elem.on("change", function(e) {_x000D_
var files = elem[0].files;_x000D_
ngModel.$setViewValue(files);_x000D_
})_x000D_
}_x000D_
}_x000D_
})_x000D_
_x000D_
.controller("ctrl", function($scope) {_x000D_
$scope.onInputChange = function() {_x000D_
console.log("input change");_x000D_
};_x000D_
})
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>_x000D_
<body ng-app="app" ng-controller="ctrl">_x000D_
<h1>AngularJS Input `type=file` Demo</h1>_x000D_
_x000D_
<input type="file" files-input ng-model="fileList" _x000D_
ng-change="onInputChange()" multiple />_x000D_
_x000D_
<h2>Files</h2>_x000D_
<div ng-repeat="file in fileList">_x000D_
{{file.name}}_x000D_
</div>_x000D_
</body>
_x000D_
ruby:
ruby -ne 'print $stdin.eof ? $_.strip : $_'
or:
ruby -ane 'q=p;p=$_;puts q if $.>1;END{print p.strip!}'
Your question is a little unclear...as the part that you indicate you want to bold in Excel is a DataGridView in the import from word method. Do you maybe want to bold the first row in the excel document?
using xl = Microsoft.Office.Interop.Excel;
xl.Range rng = (xl.Range)xlWorkSheet.Rows[0];
rng.Font.Bold = true;
Simple as that!
HTH, Z
If your String input is:
String a = " abc ";
System.out.println(a);
Yes, output will be, "abc"; But if your String input is:
String b = " This is a test "
System.out.println(b);
Output will be This is a test
So trim only removes spaces before your first character and after your last character in the string and ignores the inner spaces.
This is a piece of my code that slightly optimizes the built in String
trim method removing the inner spaces and removes spaces before and after your first and last character in the string. Hope it helps.
public static String trim(char [] input){
char [] output = new char [input.length];
int j=0;
int jj=0;
if(input[0] == ' ' ) {
while(input[jj] == ' ')
jj++;
}
for(int i=jj; i<input.length; i++){
if(input[i] !=' ' || ( i==(input.length-1) && input[input.length-1] == ' ')){
output[j]=input[i];
j++;
}
else if (input[i+1]!=' '){
output[j]=' ';
j++;
}
}
char [] m = new char [j];
int a=0;
for(int i=0; i<m.length; i++){
m[i]=output[a];
a++;
}
return new String (m);
}
It generally comes to mind that you have set up two-factor authentication, after a few password trials and maybe a password reset. So, how can we git clone a private repository using two-factor authentication? It is simple, using access tokens.
How to Authenticate Git using Access Tokens
Wow, it works!
This site seems to keep a complete list that's still maintained
iPhone, iPod Touch, and iPad from iOS 2.0 - 5.1.1 (to date).
You do need to assemble the full user-agent string out of the information listed in the page's columns.
You can use the Scanner class in Java
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println("String: " + s);
This is called an initialization list. It is a way of initializing class members. There are benefits to using this instead of simply assigning new values to the members in the body of the constructor, but if you have class members which are constants or references they must be initialized.
Suppose you want to create a vector x whose length is zero. Now let v be any vector.
> v<-c(4,7,8)
> v
[1] 4 7 8
> x<-v[0]
> length(x)
[1] 0
wp_register_script('custom-js',WP_PLUGIN_URL.'/PLUGIN_NAME/js/custom.js',array(),NULL,true);
wp_enqueue_script('custom-js');
$wnm_custom = array( 'template_url' => get_bloginfo('template_url') );
wp_localize_script( 'custom-js', 'wnm_custom', $wnm_custom );
and in custom.js
alert(wnm_custom.template_url);
You're using Comparators
incorrectly.
Collections.sort(movieItems, new Comparator<Movie>(){
public int compare (Movie m1, Movie m2){
return m1.getDate().compareTo(m2.getDate());
}
});
Since I'm too low reputation to comment, I will post this as an answer since it saved me after hours of struggeling and it may help somebody else:
As most people state GC.Collect(); is NOT recommended to do this normally, except in edge cases. As an example of this running garbage collection was exactly the solution to my scenario.
My program runs a long running operation on a file in a thread and afterwards deletes the file from the main thread. However: when the file operation throws an exception .NET does NOT release the filelock until the garbage is actually collected, EVEN when the long running task is encapsulated in a using statement. Therefore the program has to force garbage collection before attempting to delete the file.
In code:
var returnvalue = 0;
using (var t = Task.Run(() => TheTask(args, returnvalue)))
{
//TheTask() opens a file and then throws an exception. The exception itself is handled within the task so it does return a result (the errorcode)
returnvalue = t.Result;
}
//Even though at this point the Thread is closed the file is not released untill garbage is collected
System.GC.Collect();
DeleteLockedFile();
Controller trying to find the "action" value in bean but according to your example you have not set any bean name of "action". try to do name="action". @RequestParam always find in the bean class.
Just create a new branch with git checkout -b ABC_1
; your uncommitted changes will be kept, and you then commit them to that branch.
May I suggest numbro for locale based formatting and number-format.js for the general case. A combination of the two depending on use-case may help.
I'm using window.location.reload(true)
according to MDN (and this similar question) it forces page to reload from server.
You can execute this code in the browser by typing javascript:location.reload(true)
in the address bar.
Try Libman, it's as simple as Bower and you can specify wwwroot/lib/ as the download folder.
Just Right Click on Project
Click on Team
Click Refresh/Cleaup
this will remove all the current lock files created by SVN
hope this will help !!!!
I figured it out and posted the answer in Can't run Business Intelligence Development Studio, file is not found.
I had this same problem. I am running .NET framework 3.5, SQL Server 2005, and Visual Studio 2008. While I was trying to run SQL Server Business Intelligence Development Studio the icon was grayed out and the devenv.exe file was not found.
I hope this helps.
Launch adb shell and enter the command as follows
am start -n yourpackagename/.activityname
One way to do this that correctly uses group by
:
select l.*
from table l
inner join (
select
m_id, max(timestamp) as latest
from table
group by m_id
) r
on l.timestamp = r.latest and l.m_id = r.m_id
order by timestamp desc
How this works:
m_id
in the subquerytable
that match a row from the subquery (this operation -- where a join is performed, but no columns are selected from the second table, it's just used as a filter -- is known as a "semijoin" in case you were curious)All cookies are client and server
There is no difference. A regular cookie can be set server side or client side. The 'classic' cookie will be sent back with each request. A cookie that is set by the server, will be sent to the client in a response. The server only sends the cookie when it is explicitly set or changed, while the client sends the cookie on each request.
But essentially it's the same cookie.
But, behavior can change
A cookie is basically a name=value
pair, but after the value can be a bunch of semi-colon separated attributes that affect the behavior of the cookie if it is so implemented by the client (or server).
Those attributes can be about lifetime, context and various security settings.
HTTP-only (is not server-only)
One of those attributes can be set by a server to indicate that it's an HTTP-only cookie. This means that the cookie is still sent back and forth, but it won't be available in JavaScript. Do note, though, that the cookie is still there! It's only a built in protection in the browser, but if somebody would use a ridiculously old browser like IE5, or some custom client, they can actually read the cookie!
So it seems like there are 'server cookies', but there are actually not. Those cookies are still sent to the client. On the client there is no way to prevent a cookie from being sent to the server.
Alternatives to achieve 'only-ness'
If you want to store a value only on the server, or only on the client, then you'd need some other kind of storage, like a file or database on the server, or Local Storage on the client.
if num in range(min, max):
"""do stuff..."""
else:
"""do other stuff..."""
First
ps -ef
to list all processes. Note the the process number of the one you want to kill. Then
kill 1234
were you replace 1234 with the process number that you want.
Alternatively, if you are absolutely certain that there is only one process with a particular name, or you want to kill multiple processes which share the same name
killall processname
To retain both the margins and background color use:
background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<padding
android:bottom="10dp"
android:left="4dp"
android:right="8dp"
android:top="10dp" />
<solid android:color="@android:color/transparent" />
</shape>
Edit Text:
<androidx.appcompat.widget.AppCompatEditText
android:id="@+id/none_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/background"
android:inputType="text"
android:text="First Name And Last Name"
android:textSize="18sp" />
Use std::algorithms. This question has some suitably reusable suggestions Remove spaces from std::string in C++
I will simply leave this here because none of the other approaches worked for me. Also, I can look it up myself when I need it for new devices.
conda create --name tensorflow
conda activate tensorflow
conda search tensorflow
for all available TensorFlow versions1.14
was installed): conda install -c conda-forge tensorflow=YOUR_VERSION
.dll
-File to the Windows\System32
folderNow it should work like a charm!
If it still doesn't work, try this, it worked for me:
Open Anaconda-Prompt:
Python 3.6
like this: conda create --name tensorflow_env python=3.6
conda activate tensorflow
conda install tensorflow=YOUR_VERSION
(not forge, just like this!)If you want to use your GPU, do it the same way as described above, with the only difference to install tensorflow-gpu
instead if tensorflow
.
And, you must install the newest NVIDIA driver for your GPU, you can find and choose the right one here.
(Yes, in TF 2 there's both, a CPU and GPU support, in the "normal" library. However, if you install tensorflow-gpu
via conda, it installs the CUDA and cudNN etc. you need automatically for you - also the right versions. This way easier and faster.)
Just add margin: 0 auto;
to the inside div.
span { display: table-cell; height: (your-height + px); vertical-align: middle; }
For spans to work like a table-cell (or any other element, for that matter), height must be specified. I've given spans a height, and they work just fine--but you must add height to get them to do what you want.
I had this same issue.I updated to buildToolsVersion "23.0.3" It all of a sudden worked. Hope this helps anyone having this issue.
The relevant part of the error message is
...when a column list is used...
You are not using a column list, you are using SELECT *
. Use a column list instead:
SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] ON
INSERT INTO [MyDB].[dbo].[Equipment] (Col1, Col2, ...)
SELECT Col1, Col2, ... FROM [MyDBQA].[dbo].[Equipment]
SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] OFF
if(navigator.userAgent.match(/iPad/i)){
//code for iPad here
}
if(navigator.userAgent.match(/iPhone/i)){
//code for iPhone here
}
if(navigator.userAgent.match(/Android/i)){
//code for Android here
}
if(navigator.userAgent.match(/BlackBerry/i)){
//code for BlackBerry here
}
if(navigator.userAgent.match(/webOS/i)){
//code for webOS here
}
Method 1:
You can find all information for a YouTube video with a JSON page which has even "thumbnail_url", http://www.youtube.com/oembed?format=json&url={your video URL goes here}
Like final URL look + PHP test code
$data = file_get_contents("https://www.youtube.com/oembed?format=json&url=https://www.youtube.com/watch?v=_7s-6V_0nwA");
$json = json_decode($data);
var_dump($json);
object(stdClass)[1]
public 'width' => int 480
public 'version' => string '1.0' (length=3)
public 'thumbnail_width' => int 480
public 'title' => string 'how to reminder in window as display message' (length=44)
public 'provider_url' => string 'https://www.youtube.com/' (length=24)
public 'thumbnail_url' => string 'https://i.ytimg.com/vi/_7s-6V_0nwA/hqdefault.jpg' (length=48)
public 'author_name' => string 'H2 ZONE' (length=7)
public 'type' => string 'video' (length=5)
public 'author_url' => string 'https://www.youtube.com/channel/UC9M35YwDs8_PCWXd3qkiNzg' (length=56)
public 'provider_name' => string 'YouTube' (length=7)
public 'height' => int 270
public 'html' => string '<iframe width="480" height="270" src="https://www.youtube.com/embed/_7s-6V_0nwA?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>' (length=171)
public 'thumbnail_height' => int 360
For details, you can also see How to get a YouTube video thumbnail using id or https://www.youtube.com/watch?v=mXde7q59BI8 video tutorial 1
Method 2:
Using YouTube image link, https://img.youtube.com/vi/"insert-youtube-video-id-here"/default.jpg
Method 3:
Using browser source code for getting thumbnail using video URL link -go to video source code and search for thumbnailurl. Now you can use this URL into your source code:
{img src="https://img.youtube.com/vi/"insert-youtube-video-id-here"/default.jpg"}
For details you can also see How to get a YouTube video thumbnail using id or https://www.youtube.com/watch?v=9f6E8MeM6PI video tutorial 2
This is old topic but on my last test on one my API, cURL is faster and more stable. Sometimes file_get_contents on larger request need over 5 seconds when cURL need only from 1.4 to 1.9 seconds what is double faster.
I need to add one note on this that I just send GET and recive JSON content. If you setup cURL properly, you will have a great response. Just "tell" to cURL what you need to send and what you need to recive and that's it.
On your exampe I would like to do this setup:
$ch = curl_init('http://api.bitly.com/v3/shorten?login=user&apiKey=key&longUrl=url');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
$result = curl_exec($ch);
This request will return data in 0.10 second max
Something like this - for each line read into string variable a
:
>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456
Now you can do what is necessary with x
and y
as assigned, which are integers.
Run PHP file from command Promp.
Please set Environment Variable as per below mention steps.
Now open Command prompt where your source file are available and run command "php test.php"
You basically have two options, either define it as a service, or place it on your root scope. I would suggest that you make a service out of it to avoid polluting the root scope. You create a service and make it available in your controller like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) {
$scope.callFoo = function() {
myService.foo();
}
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="callFoo()">Call foo</button>
</body>
</html>
If that's not an option for you, you can add it to the root scope like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.globalFoo = function() {
alert("I'm global foo!");
};
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="globalFoo()">Call global foo</button>
</body>
</html>
That way, all of your templates can call globalFoo()
without having to pass it to the template from the controller.
$mylabel.text("-123456");
var string = $mylabel.text().replace('-', '');
if you have done it that way variable string
now holds "123456"
you can also (i guess the better way) do this...
$mylabel.text("-123456");
$mylabel.text(function(i,v){
return v.replace('-','');
});
Old question I know. You don't need to convert it. See this function:
function getType( oObj )
{
if( typeof oObj === "object" )
{
return ( oObj === null )?'Null':
// Check if it is an alien object, for example created as {world:'hello'}
( typeof oObj.constructor !== "function" )?'Object':
// else return object name (string)
oObj.constructor.name;
}
// Test simple types (not constructed types)
return ( typeof oObj === "boolean")?'Boolean':
( typeof oObj === "number")?'Number':
( typeof oObj === "string")?'String':
( typeof oObj === "function")?'Function':false;
};
Examples:
function MyObject() {}; // Just for example
console.log( getType( new String( "hello ") )); // String
console.log( getType( new Function() ); // Function
console.log( getType( {} )); // Object
console.log( getType( [] )); // Array
console.log( getType( new MyObject() )); // MyObject
var bTest = false,
uAny, // Is undefined
fTest function() {};
// Non constructed standard types
console.log( getType( bTest )); // Boolean
console.log( getType( 1.00 )); // Number
console.log( getType( 2000 )); // Number
console.log( getType( 'hello' )); // String
console.log( getType( "hello" )); // String
console.log( getType( fTest )); // Function
console.log( getType( uAny )); // false, cannot produce
// a string
Low cost and simple.
For Makefile.PL-based distributions, use the INSTALL_BASE option when generating Makefiles:
perl Makefile.PL INSTALL_BASE=/mydir/perl
If you're assembling the HTML in Java, you can use this nice utility class from Apache commons-lang to do all the escaping correctly:
org.apache.commons.lang.StringEscapeUtils
Escapes and unescapes Strings for Java, Java Script, HTML, XML, and SQL.
Here's one way:
CString str;
str.Format("%d", 5);
In your case, try _T("%d")
or L"%d"
rather than "%d"
The \caption
command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example:
\begin{figure}
\[ E = m c^2 \]
\caption{A famous equation}
\end{figure}
The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The \captionof
command of the caption package can be used to place a caption outside of a floating environment. It is used like this:
\[ E = m c^2 \]
\captionof{figure}{A famous equation}
This will also produce an entry for the \listoffigures
, if your document has one.
To align parts of an equation, take a look at the eqnarray
environment, or some of the environments of the amsmath package: align, gather, multiline,...
typeof
is an operator to obtain a type known at compile-time (or at least a generic type parameter). The operand of typeof
is always the name of a type or type parameter - never an expression with a value (e.g. a variable). See the C# language specification for more details.
GetType()
is a method you call on individual objects, to get the execution-time type of the object.
Note that unless you only want exactly instances of TextBox
(rather than instances of subclasses) you'd usually use:
if (myControl is TextBox)
{
// Whatever
}
Or
TextBox tb = myControl as TextBox;
if (tb != null)
{
// Use tb
}
Easiest way is
/**
* Check if two rectangles collide
* x_1, y_1, width_1, and height_1 define the boundaries of the first rectangle
* x_2, y_2, width_2, and height_2 define the boundaries of the second rectangle
*/
boolean rectangle_collision(float x_1, float y_1, float width_1, float height_1, float x_2, float y_2, float width_2, float height_2)
{
return !(x_1 > x_2+width_2 || x_1+width_1 < x_2 || y_1 > y_2+height_2 || y_1+height_1 < y_2);
}
first of all put it in to your mind that in computers the coordinates system is upside down. x-axis is same as in mathematics but y-axis increases downwards and decrease on going upward.. if rectangle are drawn from center. if x1 coordinates is greater than x2 plus its its half of widht. then it means going half they will touch each other. and in the same manner going downward + half of its height. it will collide..
Why not use a list comprehension?
In Python 2
ran_floats = [random.uniform(low,high) for _ in xrange(size)]
In Python 3, range
works like xrange
(ref)
ran_floats = [random.uniform(low,high) for _ in range(size)]
Check which one the system is currently using:
python --version
Add the main folder location (e.g. C/ProgramFiles) and Scripts location (C/ProgramFiles/Scripts) to Environment Variables of the system. Add both 3.x version and 2.x version
Path location is ranked inside environment variable. If you want to use Python 2.x simply put path of python 2.x first, if you want for Python 3.x simply put 3.x first
If you really want to micro optimise your code your best approach is always benchmarking.
The .net framework has an excellent stopwatch implementation - System.Diagnostics.Stopwatch
I checked the line 35 of xampp/apache/conf/httpd.conf and it was:
ServerRoot "/xampp/apache"
Which doesn't exist. ...
Create the directory, or change the path to the directory that contains your hypertext documents.
Most kinds of smart pointers handle disposing of the pointer-to object for you. It's very handy because you don't have to think about disposing of objects manually anymore.
The most commonly-used smart pointers are std::tr1::shared_ptr
(or boost::shared_ptr
), and, less commonly, std::auto_ptr
. I recommend regular use of shared_ptr
.
shared_ptr
is very versatile and deals with a large variety of disposal scenarios, including cases where objects need to be "passed across DLL boundaries" (the common nightmare case if different libc
s are used between your code and the DLLs).
$.ajax({
url:url,
type:"POST",
data:data,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
})
See : jQuery.ajax()
Is something like this what you're looking for?
def write_vars_to_file(f, **vars):
for name, val in vars.items():
f.write("%s = %s\n" % (name, repr(val)))
Usage:
>>> import sys
>>> write_vars_to_file(sys.stdout, dict={'one': 1, 'two': 2})
dict = {'two': 2, 'one': 1}
This might not really answer the question, but just in case someone just need to quickly send a string value to a function that require a NSArray parameter.
NSArray *data = @[@"The String Value"];
if you need to send more than just 1 string value, you could also use
NSArray *data = @[@"The String Value", @"Second String", @"Third etc"];
then you can send it to the function like below
theFunction(data);
TL;DR Log all your queries and tail the mysql log.
These directions are for my install of Ubuntu 14.04. Issue command lsb_release -a
to get your version. Your install might be different.
cd /etc/mysql
. You should see a file called my.cnf
. That’s the file we’re gonna change.cat my.cnf | grep general_log
. This filters the my.cnf
file for you. You should see two entries: #general_log_file = /var/log/mysql/mysql.log
&& #general_log = 1
.sudo service mysql restart
. sudo service nginx restart
.Nice work! You’re all set. Now all you have to do is tail the log file so you can see the PDO queries your app makes in real time.
Enter this cmd tail -f /var/log/mysql/mysql.log
.
Your output will look something like this:
73 Connect xyz@localhost on your_db
73 Query SET NAMES utf8mb4
74 Connect xyz@localhost on your_db
75 Connect xyz@localhost on your_db
74 Quit
75 Prepare SELECT email FROM customer WHERE email=? LIMIT ?
75 Execute SELECT email FROM customer WHERE email='[email protected]' LIMIT 5
75 Close stmt
75 Quit
73 Quit
Any new queries your app makes will automatically pop into view, as long as you continue tailing the log. To exit the tail, hit cmd/ctrl c
.
truncate --size 0 mysql.log
.Huge shout out to Nathan Long’s answer above for the inspo to figure this out on Ubuntu. Also to dikirill for his comment on Nathan’s post which lead me to this solution.
Love you stackoverflow!
Mads Hansen's solution is good but to succeed in reading the external file in .NET 4 took some time to figure out using hints in the comments about resolvers, ProhibitDTD and so on.
This is how it's done:
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;
settings.XmlResolver = resolver;
var reader = XmlReader.Create("logfile.xml", settings);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
foreach (XmlElement element in doc.SelectNodes("//event"))
{
var ch = element.ChildNodes;
var count = ch.Count;
}
logfile.xml:
<?xml version="1.0"?>
<!DOCTYPE logfile [
<!ENTITY events
SYSTEM "events.txt">
]>
<logfile>
&events;
</logfile>
events.txt:
<event>
<item1>item1</item1>
<item2>item2</item2>
</event>
As Bevan said, but keep in mind, that the list-index is 0-based. If you want to move an element to the front of the list, you have to insert it at index 0 (not 1 as shown in your example).
Use type="application/javascript"
In case of HTML5, the type attribute is obsolete, you may remove it. Note: that it defaults to "text/javascript" according to w3.org, so I would suggest to add the "application/javascript" instead of removing it.
http://www.w3.org/TR/html5/scripting-1.html#attr-script-type
The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. The default, which is used if the attribute is absent, is "text/javascript".
Use "application/javascript", because "text/javascript" is obsolete:
RFC 4329: http://www.rfc-editor.org/rfc/rfc4329.txt
Deployed Scripting Media Types and Compatibility
Various unregistered media types have been used in an ad-hoc fashion to label and exchange programs written in ECMAScript and JavaScript. These include:
+-----------------------------------------------------+ | text/javascript | text/ecmascript | | text/javascript1.0 | text/javascript1.1 | | text/javascript1.2 | text/javascript1.3 | | text/javascript1.4 | text/javascript1.5 | | text/jscript | text/livescript | | text/x-javascript | text/x-ecmascript | | application/x-javascript | application/x-ecmascript | | application/javascript | application/ecmascript | +-----------------------------------------------------+
Use of the "text" top-level type for this kind of content is known to be problematic. This document thus defines text/javascript and text/
ecmascript but marks them as "obsolete". Use of experimental and
unregistered media types, as listed in part above, is discouraged.
The media types,* application/javascript * application/ecmascript
which are also defined in this document, are intended for common use and should be used instead.
This document defines equivalent processing requirements for the
types text/javascript, text/ecmascript, and application/javascript.
Use of and support for the media type application/ecmascript is
considerably less widespread than for other media types defined in
this document. Using that to its advantage, this document defines
stricter processing rules for this type to foster more interoperable
processing.
x-javascript is experimental, don't use it.
Try {{model?.person.name}}
this should wait for model to not be undefined
and then render.
Angular 2 refers to this ?.
syntax as the Elvis operator. Reference to it in the documentation is hard to find so here is a copy of it in case they change/move it:
The Elvis Operator ( ?. ) and null property paths
The Angular “Elvis” operator ( ?. ) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null.
The current hero's name is {{currentHero?.firstName}}
Let’s elaborate on the problem and this particular solution.
What happens when the following data bound title property is null?
The title is {{ title }}
The view still renders but the displayed value is blank; we see only "The title is" with nothing after it. That is reasonable behavior. At least the app doesn't crash.
Suppose the template expression involves a property path as in this next example where we’re displaying the firstName of a null hero.
The null hero's name is {{nullHero.firstName}}
JavaScript throws a null reference error and so does Angular:
TypeError: Cannot read property 'firstName' of null in [null]
Worse, the entire view disappears.
We could claim that this is reasonable behavior if we believed that the hero property must never be null. If it must never be null and yet it is null, we've made a programming error that should be caught and fixed. Throwing an exception is the right thing to do.
On the other hand, null values in the property path may be OK from time to time, especially when we know the data will arrive eventually.
While we wait for data, the view should render without complaint and the null property path should display as blank just as the title property does.
Unfortunately, our app crashes when the currentHero is null.
We could code around that problem with NgIf
<!--No hero, div not displayed, no error -->
<div *ngIf="nullHero">The null hero's name is {{nullHero.firstName}}</div>
Or we could try to chain parts of the property path with &&, knowing that the expression bails out when it encounters the first null.
The null hero's name is {{nullHero && nullHero.firstName}}
These approaches have merit but they can be cumbersome, especially if the property path is long. Imagine guarding against a null somewhere in a long property path such as a.b.c.d.
The Angular “Elvis” operator ( ?. ) is a more fluent and convenient way to guard against nulls in property paths. The expression bails out when it hits the first null value. The display is blank but the app keeps rolling and there are no errors.
<!-- No hero, no problem! -->
The null hero's name is {{nullHero?.firstName}}
It works perfectly with long property paths too:
a?.b?.c?.d
You could create a database for x conversations which contains all messages of these conversations. This would allow you to add a new Database (or server) each time x exceeds. X is the number conversations your infrastructure supports (depending on your hardware,...).
The problem is still, that there may be big conversations (with a lot of messages) on the same database. e.g. you have database A and database B an each stores e.g. 1000 conversations. It my be possible that there are far more "big" conversations on server A than on server B (since this is user created content). You could add a "master" database that contains a lookup, on which database/server the single conversations can be found (or you have a schema to assign a database from hash/modulo or something).
Maybe you can find real world architectures that deal with the same problems (you may not be the first one), and that have already been solved.
restart packager worked for me. just kill react native packager and run it again.
I was getting this error due to the BasicHttpBinding not sending a compatible messageVersion to the service i was calling. My solution was to use a custom binding like below
<bindings>
<customBinding>
<binding name="Soap11UserNameOverTransport" openTimeout="00:01:00" receiveTimeout="00:1:00" >
<security authenticationMode="UserNameOverTransport">
</security>
<textMessageEncoding messageVersion="Soap11WSAddressing10" writeEncoding="utf-8" />
<httpsTransport></httpsTransport>
</binding>
</customBinding>
</bindings>
Building on dnolans example, this is the version I could actually get to work (there were some errors with the boundary, encoding wasn't set) :-)
To send the data:
HttpWebRequest oRequest = null;
oRequest = (HttpWebRequest)HttpWebRequest.Create("http://you.url.here");
oRequest.ContentType = "multipart/form-data; boundary=" + PostData.boundary;
oRequest.Method = "POST";
PostData pData = new PostData();
Encoding encoding = Encoding.UTF8;
Stream oStream = null;
/* ... set the parameters, read files, etc. IE:
pData.Params.Add(new PostDataParam("email", "[email protected]", PostDataParamType.Field));
pData.Params.Add(new PostDataParam("fileupload", "filename.txt", "filecontents" PostDataParamType.File));
*/
byte[] buffer = encoding.GetBytes(pData.GetPostData());
oRequest.ContentLength = buffer.Length;
oStream = oRequest.GetRequestStream();
oStream.Write(buffer, 0, buffer.Length);
oStream.Close();
HttpWebResponse oResponse = (HttpWebResponse)oRequest.GetResponse();
The PostData class should look like:
public class PostData
{
// Change this if you need to, not necessary
public static string boundary = "AaB03x";
private List<PostDataParam> m_Params;
public List<PostDataParam> Params
{
get { return m_Params; }
set { m_Params = value; }
}
public PostData()
{
m_Params = new List<PostDataParam>();
}
/// <summary>
/// Returns the parameters array formatted for multi-part/form data
/// </summary>
/// <returns></returns>
public string GetPostData()
{
StringBuilder sb = new StringBuilder();
foreach (PostDataParam p in m_Params)
{
sb.AppendLine("--" + boundary);
if (p.Type == PostDataParamType.File)
{
sb.AppendLine(string.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", p.Name, p.FileName));
sb.AppendLine("Content-Type: application/octet-stream");
sb.AppendLine();
sb.AppendLine(p.Value);
}
else
{
sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", p.Name));
sb.AppendLine();
sb.AppendLine(p.Value);
}
}
sb.AppendLine("--" + boundary + "--");
return sb.ToString();
}
}
public enum PostDataParamType
{
Field,
File
}
public class PostDataParam
{
public PostDataParam(string name, string value, PostDataParamType type)
{
Name = name;
Value = value;
Type = type;
}
public PostDataParam(string name, string filename, string value, PostDataParamType type)
{
Name = name;
Value = value;
FileName = filename;
Type = type;
}
public string Name;
public string FileName;
public string Value;
public PostDataParamType Type;
}
SQL Server 2012 version above,
SELECT format(Closing_Date,'yyyy-MM') as ClosingMonth,
Category,
COUNT(Status) TotalCount
FROM MyTable
WHERE Closing_Date >= '2012-02-01'
AND Closing_Date <= '2012-12-31'
AND Defect_Status1 IS NOT NULL
GROUP BY format(Closing_Date,'yyyy-MM'), Category;
If it's a server socket, you should call listen()
on your socket, and then getsockname()
to find the port number on which it is listening:
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
perror("getsockname");
else
printf("port number %d\n", ntohs(sin.sin_port));
As for the IP address, if you use INADDR_ANY
then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname()
on the socket for a specific connection (which you get from accept()
) in order to find out which local IP address is being used on that connection.
Just to add some more empirical info, I have been investigating the whole issue of upgradable locks, and Example for boost shared_mutex (multiple reads/one write)? is a good answer adding the important info that only one thread can have an upgrade_lock even if it is not upgraded, that is important as it means you cannot upgrade from a shared lock to a unique lock without releasing the shared lock first. (This has been discussed elsewhere but the most interesting thread is here http://thread.gmane.org/gmane.comp.lib.boost.devel/214394)
However I did find an important (undocumented) difference between a thread waiting for an upgrade to a lock (ie needs to wait for all readers to release the shared lock) and a writer lock waiting for the same thing (ie a unique_lock).
The thread that is waiting for a unique_lock on the shared_mutex blocks any new readers coming in, they have to wait for the writers request. This ensures readers do not starve writers (however I believe writers could starve readers).
The thread that is waiting for an upgradeable_lock to upgrade allows other threads to get a shared lock, so this thread could be starved if readers are very frequent.
This is an important issue to consider, and probably should be documented.
You can use the HTML5 input of type number
It does not accept any characters in its declaration
<input type="number" [(model)]='myvar' min=0 max=100 step=5 />
Here is an example of its usage with angular 2 [(model)]
I'm not sure about older versions, but from NEON onward, you can just right click on workspace and select Remove from launcher selection option.
of course this won't remove the original files. It simply removes it from the list of suggested workspaces.
You don't need complicated algorithms.
Just one simple line:
Random random = new Random();
array.ToList().Sort((x, y) => random.Next(-1, 1)).ToArray();
Note that we need to convert the Array
to a List
first, if you don't use List
in the first place.
Also, mind that this is not efficient for very large arrays! Otherwise it's clean & simple.
Just to complement the answer given by Thibaut Barrère.
I used
wget -r -nH --cut-dirs=5 -nc ftp://user:pass@server//absolute/path/to/directory
Note the double slash after the server name. If you don't put an extra slash the path is relative to the home directory of user.
-nH
avoids the creation of a directory named after the server name-nc
avoids creating a new file if it already exists on the destination (it is just skipped)--cut-dirs=5
allows to take the content of /absolute/path/to/directory and to put it in the directory where you launch wget. The number 5 is used to filter out the 5 components of the path. The double slash means an extra component.You should use DecimalFormat("0.#")
For 4.3000
Double price = 4.3000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));
output is:
4.3
In case of 5.000 we have
Double price = 5.000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));
And the output is:
5
After a few futile hours battling with a 'SyntaxError: missing : after property id' message I can now expand on this topic:
border-width is a valid css property but it is not included in the jQuery css oject definition, so .css({border-width: '2px'}) will cause an error, but it's quite happy with .css({'border-width': '2px'}), presumably property names in quotes are just passed on as received.
Simplest way would be to define default and allow it to be overridden. I am not sure what is the use of systemProperty in this case. Simple arguments will do the job.
def profiles = 'prod'
bootRun {
args = ["--spring.profiles.active=" + profiles]
}
To run dev:
./gradlew bootRun -Pdev
To add dependencies on your task you can do something like this:
task setDevProperties(dependsOn: bootRun) << {
doFirst {
System.setProperty('spring.profiles.active', profiles)
}
}
There are lots of ways achieving this in Gradle.
Edit:
Configure separate configuration files per environment.
if (project.hasProperty('prod')) {
apply from: 'gradle/profile_prod.gradle'
} else {
apply from: 'gradle/profile_dev.gradle'
}
Each configuration can override tasks for example:
def profiles = 'prod'
bootRun {
systemProperty "spring.profiles.active", activeProfile
}
Run by providing prod
flag in this case just like that:
./gradlew <task> -Pprod
Use WITH ORDINALITY
for set-returning functions:
When a function in the
FROM
clause is suffixed byWITH ORDINALITY
, abigint
column is appended to the output which starts from 1 and increments by 1 for each row of the function's output. This is most useful in the case of set returning functions such asunnest()
.
In combination with the LATERAL
feature in pg 9.3+, and according to this thread on pgsql-hackers, the above query can now be written as:
SELECT t.id, a.elem, a.nr
FROM tbl AS t
LEFT JOIN LATERAL unnest(string_to_array(t.elements, ','))
WITH ORDINALITY AS a(elem, nr) ON TRUE;
LEFT JOIN ... ON TRUE
preserves all rows in the left table, even if the table expression to the right returns no rows. If that's of no concern you can use this otherwise equivalent, less verbose form with an implicit CROSS JOIN LATERAL
:
SELECT t.id, a.elem, a.nr
FROM tbl t, unnest(string_to_array(t.elements, ',')) WITH ORDINALITY a(elem, nr);
Or simpler if based off an actual array (arr
being an array column):
SELECT t.id, a.elem, a.nr
FROM tbl t, unnest(t.arr) WITH ORDINALITY a(elem, nr);
Or even, with minimal syntax:
SELECT id, a, ordinality
FROM tbl, unnest(arr) WITH ORDINALITY a;
a
is automatically table and column alias. The default name of the added ordinality column is ordinality
. But it's better (safer, cleaner) to add explicit column aliases and table-qualify columns.
With row_number() OVER (PARTITION BY id ORDER BY elem)
you get numbers according to the sort order, not the ordinal number of the original ordinal position in the string.
You can simply omit ORDER BY
:
SELECT *, row_number() OVER (PARTITION by id) AS nr
FROM (SELECT id, regexp_split_to_table(elements, ',') AS elem FROM tbl) t;
While this normally works and I have never seen it fail in simple queries, PostgreSQL asserts nothing concerning the order of rows without ORDER BY
. It happens to work due to an implementation detail.
To guarantee ordinal numbers of elements in the blank-separated string:
SELECT id, arr[nr] AS elem, nr
FROM (
SELECT *, generate_subscripts(arr, 1) AS nr
FROM (SELECT id, string_to_array(elements, ' ') AS arr FROM tbl) t
) sub;
Or simpler if based off an actual array:
SELECT id, arr[nr] AS elem, nr
FROM (SELECT *, generate_subscripts(arr, 1) AS nr FROM tbl) t;
Related answer on dba.SE:
None of these features are available, yet: RETURNS TABLE
, generate_subscripts()
, unnest()
, array_length()
. But this works:
CREATE FUNCTION f_unnest_ord(anyarray, OUT val anyelement, OUT ordinality integer)
RETURNS SETOF record
LANGUAGE sql IMMUTABLE AS
'SELECT $1[i], i - array_lower($1,1) + 1
FROM generate_series(array_lower($1,1), array_upper($1,1)) i';
Note in particular, that the array index can differ from ordinal positions of elements. Consider this demo with an extended function:
CREATE FUNCTION f_unnest_ord_idx(anyarray, OUT val anyelement, OUT ordinality int, OUT idx int)
RETURNS SETOF record
LANGUAGE sql IMMUTABLE AS
'SELECT $1[i], i - array_lower($1,1) + 1, i
FROM generate_series(array_lower($1,1), array_upper($1,1)) i';
SELECT id, arr, (rec).*
FROM (
SELECT *, f_unnest_ord_idx(arr) AS rec
FROM (VALUES (1, '{a,b,c}'::text[]) -- short for: '[1:3]={a,b,c}'
, (2, '[5:7]={a,b,c}')
, (3, '[-9:-7]={a,b,c}')
) t(id, arr)
) sub;
id | arr | val | ordinality | idx
----+-----------------+-----+------------+-----
1 | {a,b,c} | a | 1 | 1
1 | {a,b,c} | b | 2 | 2
1 | {a,b,c} | c | 3 | 3
2 | [5:7]={a,b,c} | a | 1 | 5
2 | [5:7]={a,b,c} | b | 2 | 6
2 | [5:7]={a,b,c} | c | 3 | 7
3 | [-9:-7]={a,b,c} | a | 1 | -9
3 | [-9:-7]={a,b,c} | b | 2 | -8
3 | [-9:-7]={a,b,c} | c | 3 | -7
Compare:
Depending on your ssh client, you can set the StrictHostKeyChecking option to no on the command line, and/or send the key to a null known_hosts file. You can also set these options in your config file, either for all hosts or for a given set of IP addresses or host names.
ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no
EDIT
As @IanDunn notes, there are security risks to doing this. If the resource you're connecting to has been spoofed by an attacker, they could potentially replay the destination server's challenge back to you, fooling you into thinking that you're connecting to the remote resource while in fact they are connecting to that resource with your credentials. You should carefully consider whether that's an appropriate risk to take on before altering your connection mechanism to skip HostKeyChecking.
You can use the localeCompare()
method.
string_a.localeCompare(string_b);
/* Expected Returns:
0: exact match
-1: string_a < string_b
1: string_a > string_b
*/
Further Reading:
You can use array_pop combined with explode
Code:
$string = 'abc-123-xyz-789';
$output = array_pop(explode("-",$string));
echo $output;
DEMO: Click here
Make sure you include the rel and type as in " rel="stylesheet" type='text/css'" in the link to the awesomefont css file. Without these the file wasn't loading correctly for me.
getline(fin, buffer, '\n')
where fin
is opened file(ifstream object) and buffer
is of string/char
type where you want to copy line.
I want to add on this that you can also get Hibernate's session by calling getDelegate()
method from EntityManager
.
ex:
Session session = (Session) entityManager.getDelegate();
You probably want to have something like this:
this.sendRequest(...)
.map(...)
.catch((err) => {
//handle your error here
})
It highly depends also how do you use your service but this is the basic case.
Both do different things.
The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }
) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;
The second creates an object with dynamic storage duration and allows two things:
Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete
;
Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)
Neither is preferred; it depends on what you're doing as to which is most appropriate.
Use the former unless you need to use the latter.
Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.
Good luck.
Your original code is broken, as it delete
s a char
array that it did not new
. In fact, nothing new
d the C-style string; it came from a string literal. delete
ing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).
Usually an object should not have the responsibility of delete
ing anything that it didn't itself new
. This behaviour should be well-documented. In this case, the rule is being completely broken.
js-md5 supports UTF-8 string, array, ArrayBuffer, AMD....
and fast. jsperf
pylab
, not matplotlib.pyplot
You may try using hist
to put your data info along with the fitted curve as below:
import numpy as np
import scipy.stats as stats
import pylab as pl
h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]) #sorted
fit = stats.norm.pdf(h, np.mean(h), np.std(h)) #this is a fitting indeed
pl.plot(h,fit,'-o')
pl.hist(h,normed=True) #use this to draw histogram of your data
pl.show() #use may also need add this