You might need to register this DLL using the 32 bit version of regsvr32.exe
:
c:\windows\syswow64\regsvr32 c:\tempdl\temp12.dll
Verify what are you attempting to write. I was having the same issue, but I realized i was trying to write a byte array with length of 0.
It doesn't make sense to me, but I get: "Access to the path "
Each application pool in IIs creates its own secure user folder with FULL read/write permission by default under c:\users. Open up your Users folder and see what application pool folders are there, right click, and check their rights for the application pool virtual account assigned. You should see your application pool account added already with read/write access assigned to its root and subfolders.
So that type of file storage access is automatically done and you should be able to write whatever you like there in the app pools user account folders without changing anything. That's why virtual user accounts for each application pool were created.
In terms of diagnosing what App Pool is causing trouble, you can:
This should bring up a menu like this so you can determine which App Pool is running amok.
From there you can simply restart the the app pool and 9 times out of 10 that will fix any immediate issues you're having.
Unless you run some sort of controversial business, this is probably not a DDOS attack. It's likely that some code is just hanging because it couldn't get through to another server or got stuck in a loop or mis-allocated resources or your app pool just hasn't been recycled in a while.
You can deal with this problem programmatically without having to manually identify, log in, and recycle the app pool. Just configure the CPU property on your App Pool. You can have it kill (and automatically restart) your process anytime you reach a CPU threshold for a certain amount of time.
In your case, if you want it to restart at 80%, you can right click on the app pool and go to Advanced Settings and apply the following configurations:
NOTE: As kraken101 pointed out, different IIS GUIs have treated this differently over time. While the config value is always in 1/1000 of a %, sometimes the GUI takes the whole percent.
You can add this to your config section like this:
<applicationPools>
<add name="DefaultAppPool">
<cpu limit="80000" action="KillW3wp" resetInterval="00:01:00" />
</add>
</applicationPools>
Alternatively, you could script it with Powershell's WebAdministration Module like this:
(*make sure web-scripting-tools is enabled)
Import-Module WebAdministration
$appPoolName = "DefaultAppPool"
$appPool = Get-Item "IIS:\AppPools\$appPoolName"
$appPool.cpu.limit = 80000
$appPool.cpu.action = "KillW3wp"
$appPool.cpu.resetInterval = "00:01:00"
$appPool | Set-Item
The steps above will help fix some things once they've broken, but won't really solve any underlying issues you have.
Here are some resources on doing performance monitoring:
I had a similar issue and noted that the default cmd
on Windows Server 2012, was running the x64 one.
For Windows 7, Windows 8, Windows 10, Windows Server 2008 R2 or Windows Server 2012, run the following commands as Administrator:
x86 (32 bit)
Open C:\Windows\SysWOW64\cmd.exe
Run the command powershell Set-ExecutionPolicy RemoteSigned
x64 (64 bit)
Open C:\Windows\system32\cmd.exe
Run the command powershell Set-ExecutionPolicy RemoteSigned
You can check mode using
echo %PROCESSOR_ARCHITECTURE%
[Environment]::Is64BitProcess
References:
MSDN - Windows PowerShell execution policies
Windows - 32bit vs 64bit directory explanation
If you logged into "phpmyadmin", then logged out, you might have trouble attempting to log back in on the same browser window. The logout sends the browser to a URL that looks like this:
http://localhost/phpmyadmin/index.php?db=&token=354a350abed02588e4b59f44217826fd&old_usr=tester
But for me, on Mac OS X in Safari browser, that URL just doesn't want to work. Therefore, I have to put in the clean URL:
http://localhost/phpmyadmin
Don't know why, but as of today, Oct 20, 2015, that is what I am experiencing.
According to this, you will need .NET 4.5 installed. For more details, visit the webpage. The gist of it is that after you have .NET 4.5 installed, your 4.0 apps will use the 4.5 System.dll. You can enable TLS 1.2 in two ways:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319: SchUseStrongCrypto
to DWORD 1
git checkout stash -- .
worked for me.
Note: this can be dangerous since it doesn't try to merge the changes from the stash into your working copy, but overwrites it with the stashed files instead. So you can lose your uncommitted changes.
Paste this code in any of your source files and re-build. Worked for me !
#include stdio.h
FILE _iob[3];
FILE* __cdecl __iob_func(void) {
_iob[0] = *stdin;
_iob[0] = *stdout;
_iob[0] = *stderr;
return _iob;
}
based on @mister_lucky answer use with jquery:
$('#unobtrusive').on('click',function (e) {
e.preventDefault(); //optional
//some code
});
Html Code:
<a id="unobtrusive" href="http://jquery.com">jquery</a>
Function component example using useEffect:
Note: You need to remove the event listener by returning a "clean up" function in useEffect. If you don't, every time the component updates you will have an additional window scroll listener.
import React, { useState, useEffect } from "react"
const ScrollingElement = () => {
const [scrollY, setScrollY] = useState(0);
function logit() {
setScrollY(window.pageYOffset);
}
useEffect(() => {
function watchScroll() {
window.addEventListener("scroll", logit);
}
watchScroll();
// Remove listener (like componentWillUnmount)
return () => {
window.removeEventListener("scroll", logit);
};
}, []);
return (
<div className="App">
<div className="fixed-center">Scroll position: {scrollY}px</div>
</div>
);
}
I added it for all fieldsets with
fieldset {
border: 1px solid lightgray;
}
I didnt work if I set it separately using for example
border-color : red
. Then a black line was drawn next to the red line.
Try encodeURIComponent.
Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).
Example:
var encoded = encodeURIComponent(str);
I don't know if this is a faster alternative, but I have another solution -
from datetime import datetime
start=datetime.now()
#Statements
print datetime.now()-start
Here's an example of applying dropshadow to some svg using the 'filter' property. If you want to control the opacity of the dropshadow have a look at this example. The slope
attribute controls how much opacity to give to the dropshadow.
Relevant bits from the example:
<filter id="dropshadow" height="130%">
<feGaussianBlur in="SourceAlpha" stdDeviation="3"/> <!-- stdDeviation is how much to blur -->
<feOffset dx="2" dy="2" result="offsetblur"/> <!-- how much to offset -->
<feComponentTransfer>
<feFuncA type="linear" slope="0.5"/> <!-- slope is the opacity of the shadow -->
</feComponentTransfer>
<feMerge>
<feMergeNode/> <!-- this contains the offset blurred image -->
<feMergeNode in="SourceGraphic"/> <!-- this contains the element that the filter is applied to -->
</feMerge>
</filter>
<circle r="10" style="filter:url(#dropshadow)"/>
Box-shadow is defined to work on CSS boxes (read: rectangles), while svg is a bit more expressive than just rectangles. Read the SVG Primer to learn a bit more about what you can do with SVG filters.
Margin
is returning a struct, which means that you are editing a copy. You will need something like:
var margin = MyControl.Margin;
margin.Left = 10;
MyControl.Margin = margin;
If you know the groupId and aritifactId,you can generate download url like this.
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
http://central.maven.org/maven2/ch/qos/logback/logback-classic/
and you will get a page like this, chose the version you need,just enjoy it!
For someone who is new to IPC and Named Pipes, I found the following NuGet package to be a great help.
GitHub: Named Pipe Wrapper for .NET 4.0
To use first install the package:
PS> Install-Package NamedPipeWrapper
Then an example server (copied from the link):
var server = new NamedPipeServer<SomeClass>("MyServerPipe");
server.ClientConnected += delegate(NamedPipeConnection<SomeClass> conn)
{
Console.WriteLine("Client {0} is now connected!", conn.Id);
conn.PushMessage(new SomeClass { Text: "Welcome!" });
};
server.ClientMessage += delegate(NamedPipeConnection<SomeClass> conn, SomeClass message)
{
Console.WriteLine("Client {0} says: {1}", conn.Id, message.Text);
};
server.Start();
Example client:
var client = new NamedPipeClient<SomeClass>("MyServerPipe");
client.ServerMessage += delegate(NamedPipeConnection<SomeClass> conn, SomeClass message)
{
Console.WriteLine("Server says: {0}", message.Text);
};
client.Start();
Best thing about it for me is that unlike the accepted answer here it supports multiple clients talking to a single server.
I've been listening to Tanked Podcast. It's three friends that hang out and talk about tech, movies, video games, and they talk about the odd stuff that happens every week on the web. These guys are a blast and have way to much fun!
See for maximum numbers: http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html
TINYBLOB, TINYTEXT L + 1 bytes, where L < 2^8 (255 Bytes)
BLOB, TEXT L + 2 bytes, where L < 2^16 (64 Kilobytes)
MEDIUMBLOB, MEDIUMTEXT L + 3 bytes, where L < 2^24 (16 Megabytes)
LONGBLOB, LONGTEXT L + 4 bytes, where L < 2^32 (4 Gigabytes)
L is the number of bytes in your text field. So the maximum number of chars for text is 216-1 (using single-byte characters). Means 65 535 chars(using single-byte characters).
UTF-8/MultiByte encoding: using MultiByte encoding each character might consume more than 1 byte of space. For UTF-8 space consumption is between 1 to 4 bytes per char.
In Python 2, I didn't have a lot luck with super(). I used the answer from jimifiki on this SO thread how to refer to a parent method in python?. Then, I added my own little twist to it, which I think is an improvement in usability (Especially if you have long class names).
Define the base class in one module:
# myA.py
class A():
def foo( self ):
print "foo"
Then import the class into another modules as parent
:
# myB.py
from myA import A as parent
class B( parent ):
def foo( self ):
parent.foo( self ) # calls 'A.foo()'
This is an old post, but has a high page rank so I'll chime in with my solution.
I had a similar issue and ended up creating a subclass of UIToolbar
to manage the next/previous/done functionality in a dynamic tableView with sections: https://github.com/jday001/DataEntryToolbar
You set the toolbar as inputAccessoryView of your text fields and add them to its dictionary. This allows you to cycle through them forwards and backwards, even with dynamic content. There are delegate methods if you want to trigger your own functionality when textField navigation happens, but you don't have to deal with managing any tags or first responder status.
There are code snippets & an example app at the GitHub link to help with the implementation details. You will need your own data model to keep track of the values inside the fields.
Type-check with the -is operator returns false for any null value. In most cases, if not all, $value -is [System.Object] will be true for any possible non-null value. (In all cases, it will be false for any null-value.)
My value is nothing if not an object.
No. The method for appending an entire sequence is list.extend()
.
>>> L = [1, 2]
>>> L.extend((3, 4, 5))
>>> L
[1, 2, 3, 4, 5]
You need to set figure
properties.
At the very beginning of the script, call
figure('name','something else')
Calling figure
is a good thing, anyway, because without it, you always plot into the same window, and sometimes you may want to compare two windows side-by-side.
Alternatively, you can store the figure's handle by calling
figH = figure;
so that you can later change the figure properties to your liking (the 'numberTitle'
property setting eliminates the "figure X" text)
set(figH,'Name','something else','NumberTitle','off')
Have a look at the figure properties in the MATLAB documentation to see what else you can change if you want.
Yes, but if you have your structure in a union then you cannot. It is the same as a class.
struct Example
{
unsigned int mTest;
Example()
{
}
};
Unions will not allow constructors in the structs. You can make a constructor on the union though. This question relates to non-trivial constructors in unions.
Use : '
to open and '
to close.
For example:
: '
This is a
very neat comment
in bash
'
This is from Vegas's example found here
systemd
sudo systemctl stop mysqld.service && sudo yum remove -y mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf
sysvinit
sudo service mysql stop && sudo apt-get remove mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf
By using to_string
print(df.Name.to_string(index=False))
Adam
Bob
Cathy
Get the graphviz-2.24.msi Graphviz.org. Then get zgrviewer.
Zgrviewer requires java (probably 1.5+). You might have to set the paths to the Graphviz binaries in Zgrviewer's preferences.
File -> Open -> Open with dot -> SVG pipeline (standard) ... Pick your .dot file.
You can zoom in, export, all kinds of fun stuff.
You need to give the WebClient object the credentials. Something like this...
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
Try with array_merge_recursive
$A = array('a' => 1, 'b' => 2, 'c' => 3);
$B = array('c' => 4, 'd'=> 5);
$c = array_merge_recursive($A,$B);
echo "<pre>";
print_r($c);
echo "</pre>";
will return
Array
(
[a] => 1
[b] => 2
[c] => Array
(
[0] => 3
[1] => 4
)
[d] => 5
)
The best way to do, I think, is to handle it like the MSDN said on http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown.aspx
But handle it, how you really need it. My way (in the example below) is to catch every KeyDown ;-)
/// <summary>
/// onPreviewKeyDown
/// </summary>
/// <param name="e"></param>
protected override void OnPreviewKeyDown(PreviewKeyDownEventArgs e)
{
e.IsInputKey = true;
}
/// <summary>
/// onKeyDown
/// </summary>
/// <param name="e"></param>
protected override void OnKeyDown(KeyEventArgs e)
{
Input.SetFlag(e.KeyCode);
e.Handled = true;
}
/// <summary>
/// onKeyUp
/// </summary>
/// <param name="e"></param>
protected override void OnKeyUp(KeyEventArgs e)
{
Input.RemoveFlag(e.KeyCode);
e.Handled = true;
}
# sudo apt-get install g++-multilib
Should fix this error on 64-bit machines (Debian/Ubuntu).
Destructors in C++ automatically gets called in the order of their constructions (Derived then Base) only when the Base class destructor is declared virtual
.
If not, then only the base class destructor is invoked at the time of object deletion.
Example: Without virtual Destructor
#include <iostream>
using namespace std;
class Base{
public:
Base(){
cout << "Base Constructor \n";
}
~Base(){
cout << "Base Destructor \n";
}
};
class Derived: public Base{
public:
int *n;
Derived(){
cout << "Derived Constructor \n";
n = new int(10);
}
void display(){
cout<< "Value: "<< *n << endl;
}
~Derived(){
cout << "Derived Destructor \n";
}
};
int main() {
Base *obj = new Derived(); //Derived object with base pointer
delete(obj); //Deleting object
return 0;
}
Output
Base Constructor
Derived Constructor
Base Destructor
Example: With Base virtual Destructor
#include <iostream>
using namespace std;
class Base{
public:
Base(){
cout << "Base Constructor \n";
}
//virtual destructor
virtual ~Base(){
cout << "Base Destructor \n";
}
};
class Derived: public Base{
public:
int *n;
Derived(){
cout << "Derived Constructor \n";
n = new int(10);
}
void display(){
cout<< "Value: "<< *n << endl;
}
~Derived(){
cout << "Derived Destructor \n";
delete(n); //deleting the memory used by pointer
}
};
int main() {
Base *obj = new Derived(); //Derived object with base pointer
delete(obj); //Deleting object
return 0;
}
Output
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
It is recommended to declare base class destructor as virtual
otherwise, it causes undefined behavior.
Reference: Virtual Destructor
First, disable the currently installed version of Java. To do this, go to Control Panel > Java > Advanced > Default Java for Browsers and uncheck Microsoft Internet Explorer.
Next, enable the version of Java you want to use instead. To do this, go to (for example) C:\Program Files\Java\jre1.5.0_15\bin (where jre1.5.0_15 is the version of Java you want to use), and run javacpl.exe. Go to Advanced > Default Java for Browsers and check Microsoft Internet Explorer.
To get your old version of Java back you need to reverse these steps.
Note that in older versions of Java, Default Java for Browsers is called <APPLET> Tag Support (but the effect is the same).
The good thing about this method is that it doesn't affect other browsers, and doesn't affect the default system JRE.
If you want to use names, try a namedtuple:
from collections import namedtuple
Pair = namedtuple("Pair", ["first", "second"])
pairs = [Pair("a", 1), Pair("b", 2), Pair("c", 3)]
for pair in pairs:
print("First = {}, second = {}".format(pair.first, pair.second))
What you can do to get it right is:
1) npm uninstall reat-native-fs
to uninstall library
2)npm unlink react-native-fs
to unlink the library
Now the library is successfully removed and now install the lib again in your project and this time link everything manually. Sometime automatic linking causes this error.
The top 2 answers (from Adam Robinson and Andrejs Cainikovs) are kinda, sorta correct, in that they do technically work, but their explanations are wrong and so could be misleading in many cases. For example, while the SQL_Latin1_General_CP1_CI_AS
collation will work in many cases, it should not be assumed to be the appropriate case-insensitive collation. In fact, given that the O.P. is working in a database with a case-sensitive (or possibly binary) collation, we know that the O.P. isn't using the collation that is the default for so many installations (especially any installed on an OS using US English as the language): SQL_Latin1_General_CP1_CI_AS
. Sure, the O.P. could be using SQL_Latin1_General_CP1_CS_AS
, but when working with VARCHAR
data, it is important to not change the code page as it could lead to data loss, and that is controlled by the locale / culture of the collation (i.e. Latin1_General vs French vs Hebrew etc). Please see point # 9 below.
The other four answers are wrong to varying degrees.
I will clarify all of the misunderstandings here so that readers can hopefully make the most appropriate / efficient choices.
Do not use UPPER()
. That is completely unnecessary extra work. Use a COLLATE
clause. A string comparison needs to be done in either case, but using UPPER()
also has to check, character by character, to see if there is an upper-case mapping, and then change it. And you need to do this on both sides. Adding COLLATE
simply directs the processing to generate the sort keys using a different set of rules than it was going to by default. Using COLLATE
is definitely more efficient (or "performant", if you like that word :) than using UPPER()
, as proven in this test script (on PasteBin).
There is also the issue noted by @Ceisc on @Danny's answer:
In some languages case conversions do not round-trip. i.e. LOWER(x) != LOWER(UPPER(x)).
The Turkish upper-case "I" is the common example.
No, collation is not a database-wide setting, at least not in this context. There is a database-level default collation, and it is used as the default for altered and newly created columns that do not specify the COLLATE
clause (which is likely where this common misconception comes from), but it does not impact queries directly unless you are comparing string literals and variables to other string literals and variables, or you are referencing database-level meta-data.
No, collation is not per query.
Collations are per predicate (i.e. something operand something) or expression, not per query. And this is true for the entire query, not just the WHERE
clause. This covers JOINs, GROUP BY, ORDER BY, PARTITION BY, etc.
No, do not convert to VARBINARY
(e.g.convert(varbinary, myField) = convert(varbinary, 'sOmeVal')
) for the following reasons:
_BIN2
if you are using SQL Server 2008 or newer, else you have no choice but to use one that ends with _BIN
. If the data is NVARCHAR
then it doesn't matter which locale you use as they are all the same in that case, hence Latin1_General_100_BIN2
always works. If the data is VARCHAR
, you must use the same locale that the data is currently in (e.g. Latin1_General
, French
, Japanese_XJIS
, etc) because the locale determines the code page that is used, and changing code pages can alter the data (i.e. data loss).CONVERT()
it will use the 30 default value. The danger is, if the string can be over 30 bytes, it will get silently truncated and you will likely get incorrect results from this predicate.No, LIKE
is not always case-sensitive. It uses the collation of the column being referenced, or the collation of the database if a variable is compared to a string literal, or the collation specified via the optional COLLATE
clause.
LCASE
is not a SQL Server function. It appears to be either Oracle or MySQL. Or possibly Visual Basic?
Since the context of the question is comparing a column to a string literal, neither the collation of the instance (often referred to as "server") nor the collation of the database have any direct impact here. Collations are stored per each column, and each column can have a different collation, and those collations don't need to be the same as the database's default collation or the instance's collation. Sure, the instance collation is the default for what a newly created database will use as its default collation if the COLLATE
clause wasn't specified when creating the database. And likewise, the database's default collation is what an altered or newly created column will use if the COLLATE
clause wasn't specified.
You should use the case-insensitive collation that is otherwise the same as the collation of the column. Use the following query to find the column's collation (change the table's name and schema name):
SELECT col.*
FROM sys.columns col
WHERE col.[object_id] = OBJECT_ID(N'dbo.TableName')
AND col.[collation_name] IS NOT NULL;
Then just change the _CS
to be _CI
. So, Latin1_General_100_CS_AS
would become Latin1_General_100_CI_AS
.
If the column is using a binary collation (ending in _BIN
or _BIN2
), then find a similar collation using the following query:
SELECT *
FROM sys.fn_helpcollations() col
WHERE col.[name] LIKE N'{CurrentCollationMinus"_BIN"}[_]CI[_]%';
For example, assuming the column is using Japanese_XJIS_100_BIN2
, do this:
SELECT *
FROM sys.fn_helpcollations() col
WHERE col.[name] LIKE N'Japanese_XJIS_100[_]CI[_]%';
For more info on collations, encodings, etc, please visit: Collations Info
Which types to use in order to accomplish this in Java?
Answer: long
public class Stream {
public long startTime;
public long endTime;
public long getDuration() {
return endTime - startTime;
}
// I would add
public void start() {
startTime = System.currentTimeMillis();
}
public void stop() {
endTime = System.currentTimeMillis();
}
}
Usage:
Stream s = ....
s.start();
// do something for a while
s.stop();
s.getDuration(); // gives the elapsed time in milliseconds.
That's my direct answer for your first question.
For the last "note" I would suggest you to use Joda Time. It contains an interval class suitable for what you need.
for example try this :
<a href="http://www.google.com" id="myLink1">open link 1</a><br/> <a href="http://www.youtube.com" id="myLink2">open link 2</a>
document.getElementById("myLink1").onclick = function() { window.open( "http://www.facebook.com" ); return false; }; document.getElementById("myLink2").onclick = function() { window.open( "http://www.yahoo.com" ); return false; };
You can use Watchtower to watch for updates to the image a container is instantiated from and automatically pull the update and restart the container using the updated image. However, that doesn't solve the problem of rebuilding your own custom images when there's a change to the upstream image it's based on. You could view this as a two-part problem: (1) knowing when an upstream image has been updated, and (2) doing the actual image rebuild. (1) can be solved fairly easily, but (2) depends a lot on your local build environment/practices, so it's probably much harder to create a generalized solution for that.
If you're able to use Docker Hub's automated builds, the whole problem can be solved relatively cleanly using the repository links feature, which lets you trigger a rebuild automatically when a linked repository (probably an upstream one) is updated. You can also configure a webhook to notify you when an automated build occurs. If you want an email or SMS notification, you could connect the webhook to IFTTT Maker. I found the IFTTT user interface to be kind of confusing, but you would configure the Docker webhook to post to https://maker.ifttt.com/trigger/`docker_xyz_image_built`/with/key/`your_key`.
If you need to build locally, you can at least solve the problem of getting notifications when an upstream image is updated by creating a dummy repo in Docker Hub linked to your repo(s) of interest. The sole purpose of the dummy repo would be to trigger a webhook when it gets rebuilt (which implies one of its linked repos was updated). If you're able to receive this webhook, you could even use that to trigger a rebuild on your side.
To trim a list in place without creating copies of it, use del
:
>>> t = [1, 2, 3, 4, 5]
>>> # delete elements starting from index 4 to the end
>>> del t[4:]
>>> t
[1, 2, 3, 4]
>>> # delete elements starting from index 5 to the end
>>> # but the list has only 4 elements -- no error
>>> del t[5:]
>>> t
[1, 2, 3, 4]
>>>
Static methods should be called on the Class, Instance methods should be called on the Instances of the Class. But what does that mean in reality? Here is a useful example:
A car class might have an instance method called Accelerate(). You can only Accelerate a car, if the car actually exists (has been constructed) and therefore this would be an instance method.
A car class might also have a count method called GetCarCount(). This would return the total number of cars created (or constructed). If no cars have been constructed, this method would return 0, but it should still be able to be called, and therefore it would have to be a static method.
Add div wrapper
<div id=myForm>
<select name=countries>
<option value=af>Afghanistan</option>
<option value=ax>Åland Islands</option>
...
<option value=gs>South Georgia and the South Sandwich Islands</option>
...
</select>
</div>
and then write CSS
#myForm select {
width:200px; }
#myForm select:focus {
width:auto; }
Hope this will help.
A new answer to reflect the most current practices: as of version 1.0.1, neither astype('str')
nor astype(str)
work.
As per the documentation, a Series can be converted to the string datatype in the following ways:
df['id'] = df['id'].astype("string")
df['id'] = pandas.Series(df['id'], dtype="string")
df['id'] = pandas.Series(df['id'], dtype=pandas.StringDtype)
The main question was to remove the CR/LF. Using the replace and char functions works for me:
Select replace(replace(Name,char(10),''),char(13),'')
For Postgres or Oracle SQL, use the CHR function instead:
replace(replace(Name,CHR(10),''),CHR(13),'')
Python strings are immutable, you change them by making a copy.
The easiest way to do what you want is probably:
text = "Z" + text[1:]
The text[1:]
returns the string in text
from position 1 to the end, positions count from 0 so '1' is the second character.
edit: You can use the same string slicing technique for any part of the string
text = text[:1] + "Z" + text[2:]
Or if the letter only appears once you can use the search and replace technique suggested below
tr:hover
doesn't work in old browsers.
You can use jQuery for this:
.tr-hover
{
background-color:#fefefe;
}
$('.list1 tr').hover(function()
{
$(this).addClass('tr-hover');
},function()
{
$(this).removeClass('tr-hover');
});
As karim79 mentioned, the first is the most concise. However I could argue that the second is more understandable as it is not obvious/known to some Javascript/jQuery programmers that non-zero/false values are evaluated to true
in if-statements. And because of that, the third method is incorrect.
I have implemented a multiple file select with instant preview and upload after removing unwanted files from preview via ajax.
Detailed documentation can be found here: http://anasthecoder.blogspot.ae/2014/12/multi-file-select-preview-without.html
Demo: http://jsfiddle.net/anas/6v8Kz/7/embedded/result/
jsFiddle: http://jsfiddle.net/anas/6v8Kz/7/
Javascript:
$(document).ready(function(){
$('form').submit(function(ev){
$('.overlay').show();
$(window).scrollTop(0);
return upload_images_selected(ev, ev.target);
})
})
function add_new_file_uploader(addBtn) {
var currentRow = $(addBtn).parent().parent();
var newRow = $(currentRow).clone();
$(newRow).find('.previewImage, .imagePreviewTable').hide();
$(newRow).find('.removeButton').show();
$(newRow).find('table.imagePreviewTable').find('tr').remove();
$(newRow).find('input.multipleImageFileInput').val('');
$(addBtn).parent().parent().parent().append(newRow);
}
function remove_file_uploader(removeBtn) {
$(removeBtn).parent().parent().remove();
}
function show_image_preview(file_selector) {
//files selected using current file selector
var files = file_selector.files;
//Container of image previews
var imageContainer = $(file_selector).next('table.imagePreviewTable');
//Number of images selected
var number_of_images = files.length;
//Build image preview row
var imagePreviewRow = $('<tr class="imagePreviewRow_0"><td valign=top style="width: 510px;"></td>' +
'<td valign=top><input type="button" value="X" title="Remove Image" class="removeImageButton" imageIndex="0" onclick="remove_selected_image(this)" /></td>' +
'</tr> ');
//Add image preview row
$(imageContainer).html(imagePreviewRow);
if (number_of_images > 1) {
for (var i =1; i<number_of_images; i++) {
/**
*Generate class name of the respective image container appending index of selected images,
*sothat we can match images selected and the one which is previewed
*/
var newImagePreviewRow = $(imagePreviewRow).clone().removeClass('imagePreviewRow_0').addClass('imagePreviewRow_'+i);
$(newImagePreviewRow).find('input[type="button"]').attr('imageIndex', i);
$(imageContainer).append(newImagePreviewRow);
}
}
for (var i = 0; i < files.length; i++) {
var file = files[i];
/**
* Allow only images
*/
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
/**
* Create an image dom object dynamically
*/
var img = document.createElement("img");
/**
* Get preview area of the image
*/
var preview = $(imageContainer).find('tr.imagePreviewRow_'+i).find('td:first');
/**
* Append preview of selected image to the corresponding container
*/
preview.append(img);
/**
* Set style of appended preview(Can be done via css also)
*/
preview.find('img').addClass('previewImage').css({'max-width': '500px', 'max-height': '500px'});
/**
* Initialize file reader
*/
var reader = new FileReader();
/**
* Onload event of file reader assign target image to the preview
*/
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
/**
* Initiate read
*/
reader.readAsDataURL(file);
}
/**
* Show preview
*/
$(imageContainer).show();
}
function remove_selected_image(close_button)
{
/**
* Remove this image from preview
*/
var imageIndex = $(close_button).attr('imageindex');
$(close_button).parents('.imagePreviewRow_' + imageIndex).remove();
}
function upload_images_selected(event, formObj)
{
event.preventDefault();
//Get number of images
var imageCount = $('.previewImage').length;
//Get all multi select inputs
var fileInputs = document.querySelectorAll('.multipleImageFileInput');
//Url where the image is to be uploaded
var url= "/upload-directory/";
//Get number of inputs
var number_of_inputs = $(fileInputs).length;
var inputCount = 0;
//Iterate through each file selector input
$(fileInputs).each(function(index, input){
fileList = input.files;
// Create a new FormData object.
var formData = new FormData();
//Extra parameters can be added to the form data object
formData.append('bulk_upload', '1');
formData.append('username', $('input[name="username"]').val());
//Iterate throug each images selected by each file selector and find if the image is present in the preview
for (var i = 0; i < fileList.length; i++) {
if ($(input).next('.imagePreviewTable').find('.imagePreviewRow_'+i).length != 0) {
var file = fileList[i];
// Check the file type.
if (!file.type.match('image.*')) {
continue;
}
// Add the file to the request.
formData.append('image_uploader_multiple[' +(inputCount++)+ ']', file, file.name);
}
}
// Set up the request.
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function () {
if (xhr.status === 200) {
var jsonResponse = JSON.parse(xhr.responseText);
if (jsonResponse.status == 1) {
$(jsonResponse.file_info).each(function(){
//Iterate through response and find data corresponding to each file uploaded
var uploaded_file_name = this.original;
var saved_file_name = this.target;
var file_name_input = '<input type="hidden" class="image_name" name="image_names[]" value="' +saved_file_name+ '" />';
file_info_container.append(file_name_input);
imageCount--;
})
//Decrement count of inputs to find all images selected by all multi select are uploaded
number_of_inputs--;
if(number_of_inputs == 0) {
//All images selected by each file selector is uploaded
//Do necessary acteion post upload
$('.overlay').hide();
}
} else {
if (typeof jsonResponse.error_field_name != 'undefined') {
//Do appropriate error action
} else {
alert(jsonResponse.message);
}
$('.overlay').hide();
event.preventDefault();
return false;
}
} else {
/*alert('Something went wrong!');*/
$('.overlay').hide();
event.preventDefault();
}
};
xhr.send(formData);
})
return false;
}
Please note the distinction between "defined" and "assigned".
$ ruby -e 'def f; if 1>2; x=99; end;p x, defined? x; end;f'
nil
"local-variable"
x is defined even though it is never assigned!
I use INSERT 'a' + Char(10) + 'b' INTO wherever WHERE whatever
Use Like this:
Uri uri = Uri.parse(URL); //Declare your url here.
VideoView mVideoView = (VideoView)findViewById(R.id.videoview)
mVideoView.setMediaController(new MediaController(this));
mVideoView.setVideoURI(uri);
mVideoView.requestFocus();
mVideoView.start();
Another Method:
String LINK = "type_here_the_link";
VideoView mVideoView = (VideoView) findViewById(R.id.videoview);
MediaController mc = new MediaController(this);
mc.setAnchorView(videoView);
mc.setMediaPlayer(videoView);
Uri video = Uri.parse(LINK);
mVideoView.setMediaController(mc);
mVideoView.setVideoURI(video);
mVideoView.start();
If you are getting this error Couldn't open file on client side, trying server side Error in Android. and also Refer this. Hope this will give you some solution.
for me the default search in chrome was locked by smartsputnik.ru. and deleting all the entries in registry and also resetting and reinstalling chrome did not helped . except the below solution.
I use following code, found somewhere in the internet don't remember the source though.
var allText;
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
allText = rawFile.responseText;
}
}
}
rawFile.send(null);
return JSON.parse(allText);
Try this - https://github.com/laracasts/PHP-Vars-To-Js-Transformer Is simple way to append PHP variables to Javascript.
There are two options here.
One is to do an interactive rebase and edit the merge commit, redo the merge manually and continue the rebase.
Another is to use the --rebase-merges
option on git rebase
, which is described as follows from the manual:
By default, a rebase will simply drop merge commits from the todo list, and put the rebased commits into a single, linear branch. With --rebase-merges, the rebase will instead try to preserve the branching structure within the commits that are to be rebased, by recreating the merge commits. Any resolved merge conflicts or manual amendments in these merge commits will have to be resolved/re-applied manually."
Agreeing with r-dub, keep it in source control, but to me, the real benefit is this:
collaboration in identical environments (disregarding the windohs and linux/mac stuff). Before Gemfile.lock, the next dude to install the project might see all kinds of confusing errors, blaming himself, but he was just that lucky guy getting the next version of super gem, breaking existing dependencies.
Worse, this happened on the servers, getting untested version unless being disciplined and install exact version. Gemfile.lock makes this explicit, and it will explicitly tell you that your versions are different.
Note: remember to group stuff, as :development and :test
Just catch the submit event and prevent that, then do ajax
$(document).ready(function () {
$('#myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
data: $(this).serialize(),
success: function (data) {
$("#form_output").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
==
and !=
work on object identity. While the two String
s have the same value, they are actually two different objects.
use !"success".equals(statusCheck)
instead.
Don't forget to insert SET IDENTITY_INSERT MobileApplication1 ON
to the top, else you will get an error. This is for SQL Server
SET IDENTITY_INSERT MOB.MobileApplication1 ON
INSERT INTO [SERVER1].DB.MOB.MobileApplication1 m
(m.MobileApplicationDetailId,
m.MobilePlatformId)
SELECT ma.MobileApplicationId,
ma.MobilePlatformId
FROM [SERVER2].DB.MOB.MobileApplication2 ma
Take a look at the -openURL:
method on UIApplication. It should allow you to pass an NSURL instance to the system, which will determine what app to open it in and launch that application. (Keep in mind you'll probably want to check -canOpenURL:
first, just in case the URL can't be handled by apps currently installed on the system - though this is likely not a problem for plain http://
links.)
This will end the function, and you can even customize the "Error" message:
import sys
def end():
if condition:
# the player wants to play again:
main()
elif not condition:
sys.exit("The player doesn't want to play again") #Right here
psexec \\RemoteComputer cmd.exe
or use ssh or TeamViewer or RemoteDesktop!
HashMap regs = (HashMap) parser.parse(stringjson);
(String)((HashMap)regs.get("firstlevelkey")).get("secondlevelkey");
If your data includes BLOB
data:
Note that an import of data from the command line seems to choke on BLOB data, resulting in the 'MySQL server has gone away' error.
To avoid this, re-create the mysqldump but with the --hex-blob
flag:
http://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#option_mysqldump_hex-blob
which will write out the data file with hex values rather than binary amongst other text.
PhpMyAdmin also has the option "Dump binary columns in hexadecimal notation (for example, "abc" becomes 0x616263)" which works nicely.
Note that there is a long-standing bug (as of December 2015) which means that GEOM
columns are not converted:
Back up a table with a GEOMETRY column using mysqldump?
so using a program like PhpMyAdmin seems to be the only workaround (the option noted above does correctly convert GEOM columns).
Declare your progress dialog:
ProgressDialog progressDialog;
To start the progress dialog:
progressDialog = ProgressDialog.show(this, "","Please Wait...", true);
To dismiss the Progress Dialog :
progressDialog.dismiss();
@GitaarLAB and @Jukka elaborate that <xmp>
tag is obsolete, but still the best. When I use it like this
<xmp>
<div>Lorem ipsum</div>
<p>Hello</p>
</xmp>
then the first EOL is inserted in the code, and it looks awful.
It can be solved by removing that EOL
<xmp><div>Lorem ipsum</div>
<p>Hello</p>
</xmp>
but then it looks bad in the source. I used to solve it with wrapping <div>
, but recently I figured out a nice CSS3 rule, I hope it also helps somebody:
xmp { margin: 5px 0; padding: 0 5px 5px 5px; background: #CCC; }
xmp:before { content: ""; display: block; height: 1em; margin: 0 -5px -2em -5px; }
This looks better.
You could use frameset as the previous answer states but if you are insistent on using iFrames, the 2 following examples should work:
<body style="margin:0px;padding:0px;overflow:hidden">
<iframe src="http://www.youraddress.com" frameborder="0" style="overflow:hidden;height:100%;width:100%" height="100%" width="100%"></iframe>
</body>
An alternative:
<body style="margin:0px;padding:0px;overflow:hidden">
<iframe src="http://www.youraddress.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe>
</body>
To hide scrolling with 2 alternatives as shown above:
<body style="margin:0px;padding:0px;overflow:hidden">
<iframe src="http://www.youraddress.com" frameborder="0" style="overflow:hidden;height:150%;width:150%" height="150%" width="150%"></iframe>
</body>
Hack with the second example:
<body style="margin:0px;padding:0px;overflow:hidden">
<iframe src="http://www.youraddress.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:150%;width:150%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="150%" width="150%"></iframe>
</body>
To hide the scroll-bars of the iFrame, the parent is made overflow: hidden
to hide scrollbars and the iFrame is made to go upto 150% width and height which forces the scroll-bars outside the page and since the body doesn't have scroll-bars one may not expect the iframe to be exceeding the bounds of the page. This hides the scrollbars of the iFrame with full width!
I think you can use
sys.exit(0)
You may check it here in the python 2.7 doc:
The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like.
SELECT *
FROM mytable
ORDER BY
column1 DESC, column2 ASC
Make sure that all functions with non-void return type have a return
statement.
While some compilers automatically provide a default return value, others will send a SIGILL or SIGTRAP at runtime when trying to leave a function without a return value.
First of all open applicationhost.config file in visual studio.
address>>C:\Users\Your User Name\Documents\IISExpress\config\applicationhost.config
Then find this codes:
<site name="Your Site_Name" id="24">
<application path="/" applicationPool="Clr4IntegratedAppPool"
<virtualDirectory path="/" physicalPath="C:\Users\Your User Name\Documents\Visual Studio 2013\Projects\Your Site Name" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:Port_Number:*" />
</bindings>
</site>
*)Port_Number:While your site running in IIS express on your computer, port number will visible in address bar of your browser like this: localhost:port_number/... When edit this file save it.
In the Second step you must run cmd as administrator and type this code:
netsh http add urlacl url=http://*:port_Number/ user=everyone
and press enter
In Third step you must Enable port on firewall
Go to the “Control Panel\System and Security\Windows Firewall”
Click “Advanced settings”
Select “Inbound Rules”
Click on “New Rule …” button
Select “Port”, click “Next”
Fill your IIS Express listening port number, click “Next”
Select “Allow the connection”, click “Next”
Check where you would like allow connection to IIS Express (Domain,Private, Public), click “Next”
Fill rule name (e.g “IIS Express), click “Finish”
I hopeful this answer be useful for you
Update for Visual Studio 2015 in this link: https://johan.driessen.se/posts/Accessing-an-IIS-Express-site-from-a-remote-computer
I am reading a book (Effective Python) by Brett Slatkin and he shows another way to iterate over a list and also know the index of the current item in the list but he suggests that it is better not to use it and to use enumerate
instead.
I know you asked what enumerate means, but when I understood the following, I also understood how enumerate
makes iterating over a list while knowing the index of the current item easier (and more readable).
list_of_letters = ['a', 'b', 'c']
for i in range(len(list_of_letters)):
letter = list_of_letters[i]
print (i, letter)
The output is:
0 a
1 b
2 c
I also used to do something, even sillier before I read about the enumerate
function.
i = 0
for n in list_of_letters:
print (i, n)
i += 1
It produces the same output.
But with enumerate
I just have to write:
list_of_letters = ['a', 'b', 'c']
for i, letter in enumerate(list_of_letters):
print (i, letter)
This question was answered a while back, but it can modernized by rewriting as a kotlin extension function.
fun Drawable.overrideColor(@ColorInt colorInt: Int) {
when (this) {
is GradientDrawable -> setColor(colorInt)
is ShapeDrawable -> paint.color = colorInt
is ColorDrawable -> color = colorInt
}
}
The scenarios that you have mentioned are not of overloading, you are just concatenating different variables with a String.
System.out.print("Hello World");
System.out.print("My name is" + foo);
System.out.print("Sum of " + a + "and " + b + "is " + c);
System.out.print("Total USD is " + usd);
in all of these cases, you are only calling print(String s) because when something is concatenated with a string it gets converted to a String by calling the toString() of that object, and primitives are directly concatenated. However if you want to know of different signatures then yes print() is overloaded for various arguments.
As @alucic mentioned, use:
composer require vendor/package:version
or you can use:
composer update vendor/package:version
You should probably review this StackOverflow post about differences between composer install and composer update.
Related to question about version numbers, you can review Composer documentation on versions, but here in short:
So, with Tilde you will get automatic updates of patches but minor and major versions will not be updated. However, if you use Caret you will get patches and minor versions, but you will not get major (breaking changes) versions.
Tilde Version is considered a "safer" approach, but if you are using reliable dependencies (well-maintained libraries) you should not have any problems with Caret Version (because minor changes should not be breaking changes.
Don't use exec
. Use spawn
which is an EventEmmiter
object. Then you can listen to stdout
/stderr
events (spawn.stdout.on('data',callback..)
) as they happen.
From NodeJS documentation:
var spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data.toString());
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data.toString());
});
ls.on('exit', function (code) {
console.log('child process exited with code ' + code.toString());
});
exec
buffers the output and usually returns it when the command has finished executing.
Lets say we have existing list, and gonna use java 8 for this activity `
import java.util.*;
import java.util.stream.Collectors;
public class AddingArray {
public void addArrayInList(){
List<Integer> list = Arrays.asList(3, 7, 9);
// And we have an array of Integer type
int nums[] = {4, 6, 7};
//Now lets add them all in list
// converting array to a list through stream and adding that list to previous list
list.addAll(Arrays.stream(nums).map(num ->
num).boxed().collect(Collectors.toList()));
}
}
`
In my case, I have Jackson automatically (de)serializing objects that I return from a Spring MVC controller (I am using @RestController with Spring 4.1.6). I had to use com.fasterxml.jackson.annotation.JsonIgnore
instead of org.codehaus.jackson.annotate.JsonIgnore
, as otherwise, it simply did nothing.
I am not sure about gson but this is how you do it with Jon.sample hope there must be similar way using gson
{ "Players": [ "player 1", "player 2", "player 3", "player 4", "player 5" ] }
===============================================
import java.io.FileReader;
import java.util.List;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JosnFileDemo {
public static void main(String[] args) throws Exception
{
String jsonfile ="fileloaction/fileName.json";
FileReader reader = null;
JSONObject jsb = null;
try {
reader = new FileReader(jsonfile);
JSONParser jsonParser = new JSONParser();
jsb = (JSONObject) jsonParser.parse(reader);
} catch (Exception e) {
throw new Exception(e);
} finally {
if (reader != null)
reader.close();
}
List<String> Players=(List<String>) jsb.get("Players");
for (String player : Players) {
System.out.println(player);
}
}
}
Upto five team members it is free. Try it :)
Just met one special case that I had to use easy_install
instead of pip
, or I have to pull the source codes directly.
For the package GitPython
, the version in pip
is too old, which is 0.1.7
, while the one from easy_install
is the latest which is 0.3.2.rc1
.
I'm using Python 2.7.8
. I'm not sure about the underlay mechanism of easy_install
and pip
, but at least the versions of some packages may be different from each other, and sometimes easy_install
is the one with newer version.
easy_install GitPython
Make sure you are using binding to get component props in REACT
class FileUploader extends Component {
constructor (props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
onChange=(e,props)=>{
const files = e.target.files;
const selectedFile = files[0];
ProcessFileUpload(selectedFile,props.ProgressCallBack,props.ErrorCallBack,props.CompleatedCallBack,props.BaseURL,props.Location,props.FilesAllowed);
}
handleClick = () => {
this.refs.fileUploader.click();
}
render()
{
return(
<div>
<button type="button" onClick={this.handleClick}>Select File</button>
<input type='file' onChange={(e)=>this.onChange(e,this.props)} ref="fileUploader" style={{display:"none"}} />
</div>)
}
}
In this way the content of your container will sit in the middle.
Example: suppose that container width = 800px;
<div class='container' width='device-width' id='updatedContent'>
<p id='myContent'></p>
<contents></contents>
<contents></contents>
</div>
if ($("#myContent").parent === $("updatedContent"))
{
$("#myContent").css({
'left': '-(device-width/0.25)px';
'right': '-(device-width/0.225)px';
});
}
Heard you can do this in postman:
If you want to get a sub list including the last element, you leave blank after colon:
>>> ll=range(10)
>>> ll
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ll[5:]
[5, 6, 7, 8, 9]
>>> ll[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Here is a little utility function that collapses a named or unnamed list of values to a single string for easier printing. It will also print the code line itself. It's from my list examples in R page.
Generate some lists named or unnamed:
# Define Lists
ls_num <- list(1,2,3)
ls_str <- list('1','2','3')
ls_num_str <- list(1,2,'3')
# Named Lists
ar_st_names <- c('e1','e2','e3')
ls_num_str_named <- ls_num_str
names(ls_num_str_named) <- ar_st_names
# Add Element to Named List
ls_num_str_named$e4 <- 'this is added'
Here is the a function that will convert named or unnamed list to string:
ffi_lst2str <- function(ls_list, st_desc, bl_print=TRUE) {
# string desc
if(missing(st_desc)){
st_desc <- deparse(substitute(ls_list))
}
# create string
st_string_from_list = paste0(paste0(st_desc, ':'),
paste(names(ls_list), ls_list, sep="=", collapse=";" ))
if (bl_print){
print(st_string_from_list)
}
}
Testing the function with the lists created prior:
> ffi_lst2str(ls_num)
[1] "ls_num:=1;=2;=3"
> ffi_lst2str(ls_str)
[1] "ls_str:=1;=2;=3"
> ffi_lst2str(ls_num_str)
[1] "ls_num_str:=1;=2;=3"
> ffi_lst2str(ls_num_str_named)
[1] "ls_num_str_named:e1=1;e2=2;e3=3;e4=this is added"
Testing the function with subset of list elements:
> ffi_lst2str(ls_num_str_named[c('e2','e3','e4')])
[1] "ls_num_str_named[c(\"e2\", \"e3\", \"e4\")]:e2=2;e3=3;e4=this is added"
> ffi_lst2str(ls_num[2:3])
[1] "ls_num[2:3]:=2;=3"
> ffi_lst2str(ls_str[2:3])
[1] "ls_str[2:3]:=2;=3"
> ffi_lst2str(ls_num_str[2:4])
[1] "ls_num_str[2:4]:=2;=3;=NULL"
> ffi_lst2str(ls_num_str_named[c('e2','e3','e4')])
[1] "ls_num_str_named[c(\"e2\", \"e3\", \"e4\")]:e2=2;e3=3;e4=this is added"
Can be achieved also with scriptrunner
ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30
Which also have some features as rollback , timeout and waiting.
I don't think there is any significance to number 9. In addition, despite common believe, kill
is used not only to kill processes but also send a signal to a process.
If you are really curious you can read here and here.
You can do that without the terminal. You just need to create a branch with the new name, and remove the old after.
Create a branch
In your repository’s branch selector, just start typing a new branch name. It’ll give you the option to create a new branch:
It’ll branch off of your current context. For example, if you’re on the bugfix branch, it’ll create a new branch from bugfix instead of master. Looking at a commit or a tag instead? It’ll branch your code from that specific revision.
Delete a branch
You’ll also see a delete button in your repository’s Branches page:
As an added bonus, it’ll also give you a link to the branch’s Pull Request, if it has one.
I just copied this content from: Create and delete branches
I have win 7 64 bit + Excel 2010 32 bit. The registry is HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Registration{90140000-002A-0000-1000-0000000FF1CE}
So this can tell bitness of OS, not bitness of Office
Welcome to Java's misnamed .matches()
method... It tries and matches ALL the input. Unfortunately, other languages have followed suit :(
If you want to see if the regex matches an input text, use a Pattern
, a Matcher
and the .find()
method of the matcher:
Pattern p = Pattern.compile("[a-z]");
Matcher m = p.matcher(inputstring);
if (m.find())
// match
If what you want is indeed to see if an input only has lowercase letters, you can use .matches()
, but you need to match one or more characters: append a +
to your character class, as in [a-z]+
. Or use ^[a-z]+$
and .find()
.
I was having similar issue because of a different reason:
Error:
cord@node1:~$ kubectl get nodes
NAME STATUS ROLES AGE VERSION
node1 Ready master 17h v1.13.5
node2 Ready <none> 17h v1.13.5
node3 NotReady <none> 9m48s v1.13.5
cord@node1:~$ kubectl describe node node3
Name: node3
Conditions:
Type Status LastHeartbeatTime LastTransitionTime Reason Message
---- ------ ----------------- ------------------ ------ -------
Ready False Thu, 18 Apr 2019 01:15:46 -0400 Thu, 18 Apr 2019 01:03:48 -0400 KubeletNotReady runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized
Addresses:
InternalIP: 192.168.2.6
Hostname: node3
cord@node3:~$ journalctl -u kubelet
Apr 18 01:24:50 node3 kubelet[54132]: W0418 01:24:50.649047 54132 cni.go:149] Error loading CNI config list file /etc/cni/net.d/10-calico.conflist: error parsing configuration list: no 'plugins' key
Apr 18 01:24:50 node3 kubelet[54132]: W0418 01:24:50.649086 54132 cni.go:203] Unable to update cni config: No valid networks found in /etc/cni/net.d
Apr 18 01:24:50 node3 kubelet[54132]: E0418 01:24:50.649402 54132 kubelet.go:2192] Container runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized
Apr 18 01:24:55 node3 kubelet[54132]: W0418 01:24:55.650816 54132 cni.go:149] Error loading CNI config list file /etc/cni/net.d/10-calico.conflist: error parsing configuration list: no 'plugins' key
Apr 18 01:24:55 node3 kubelet[54132]: W0418 01:24:55.650845 54132 cni.go:203] Unable to update cni config: No valid networks found in /etc/cni/net.d
Apr 18 01:24:55 node3 kubelet[54132]: E0418 01:24:55.651056 54132 kubelet.go:2192] Container runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized
Apr 18 01:24:57 node3 kubelet[54132]: I0418 01:24:57.248519 54132 setters.go:72] Using node IP: "192.168.2.6"
Issue:
My file: 10-calico.conflist was incorrect. Verified it from a different node and from sample file in the same directory "calico.conflist.template".
Resolution:
Changing the file, "10-calico.conflist" and restarting the service using "systemctl restart kubelet", resolved my issue:
NAME STATUS ROLES AGE VERSION
node1 Ready master 18h v1.13.5
node2 Ready <none> 18h v1.13.5
node3 Ready <none> 48m v1.13.5
Or use sed & regex.
<some_command> | sed 's/^.* \(".*"$\)/\1/'
You can also add two lines to your .jshintrc
"globals": {
"$": false,
"jQuery": false
}
This tells jshint that there are two global variables.
With MySQL if you are inserting into a table that has a auto increment primary key and you want to use a built-in MySQL function such as NOW()
then you can do something like this:
INSERT INTO course_payment
SELECT NULL, order_id, payment_gateway, total_amt, charge_amt, refund_amt, NOW()
FROM orders ORDER BY order_id DESC LIMIT 10;
If you have Spring in you classpath then the following will do it.
Find all classes in a package that are annotated with XmlRootElement:
private List<Class> findMyTypes(String basePackage) throws IOException, ClassNotFoundException
{
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
List<Class> candidates = new ArrayList<Class>();
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
resolveBasePackage(basePackage) + "/" + "**/*.class";
Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
for (Resource resource : resources) {
if (resource.isReadable()) {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
if (isCandidate(metadataReader)) {
candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
}
}
}
return candidates;
}
private String resolveBasePackage(String basePackage) {
return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage));
}
private boolean isCandidate(MetadataReader metadataReader) throws ClassNotFoundException
{
try {
Class c = Class.forName(metadataReader.getClassMetadata().getClassName());
if (c.getAnnotation(XmlRootElement.class) != null) {
return true;
}
}
catch(Throwable e){
}
return false;
}
C# 3.0 :
char[] az = Enumerable.Range('a', 'z' - 'a' + 1).Select(i => (Char)i).ToArray();
foreach (var c in az)
{
Console.WriteLine(c);
}
yes it does work even if the only overload of Enumerable.Range accepts int parameters ;-)
Things to ponder:
this
is your code refering togetElementById
usually document.getElementById
?You should probably use the ngHref directive along with the ngClick:
<a ng-href='#here' ng-click='go()' >click me</a>
Here is an example: http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
{{msg}}
<a ng-href='#here' ng-click='go()' >click me</a>
<div style='height:1000px'>
<a id='here'></a>
</div>
<h1>here</h1>
</body>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.go = function() {
$scope.msg = 'clicked';
}
});
I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.
** Update **
Here is a demo of the set and get working fine with a service.
http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, sharedProperties) {
$scope.name = 'World';
$scope.go = function(item) {
sharedProperties.setListName(item);
}
$scope.getItem = function() {
$scope.msg = sharedProperties.getListName();
}
});
app.service('sharedProperties', function () {
var list_name = '';
return {
getListName: function() {
return list_name;
},
setListName: function(name) {
list_name = name;
}
};
});
* Edit *
Please review https://github.com/centralway/lungo-angular-bridge which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.
To install a new package and only that, you have two options:
Using the require
command, just run:
composer require new/package
Composer will guess the best version constraint to use, install the package, and add it to composer.lock
.
You can also specify an explicit version constraint by running:
composer require new/package ~2.5
–OR–
Using the update
command, add the new package manually to composer.json
, then run:
composer update new/package
If Composer complains, stating "Your requirements could not be resolved to an installable set of packages.", you can resolve this by passing the flag --with-dependencies
. This will whitelist all dependencies of the package you are trying to install/update (but none of your other dependencies).
Regarding the question asker's issues with Laravel and mcrypt: check that it's properly enabled in your CLI php.ini. If php -m
doesn't list mcrypt then it's missing.
Important: Don't forget to specify new/package
when using composer update
! Omitting that argument will cause all dependencies, as well as composer.lock
, to be updated.
The account which is running the service might not have mapped the D:-drive (they are user-specific). Try sharing the directory, and use full UNC-path in your backupConfig
.
Your watcher
of type FileSystemWatcher
is a local variable, and is out of scope when the OnStart
method is done. You probably need it as an instance or class variable.
This script removes any white space (multiple spaces, tabs, returns, etc) between words and trims:
// Trims & replaces any wihtespacing to single space between words
String.prototype.clearExtraSpace = function(){
var _trimLeft = /^\s+/,
_trimRight = /\s+$/,
_multiple = /\s+/g;
return this.replace(_trimLeft, '').replace(_trimRight, '').replace(_multiple, ' ');
};
Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:
http://www.backtrack-linux.org/wiki/index.php/Java_Install
root@bt:~# killall -9 /opt/firefox/firefox-bin
root@bt:~# mkdir /opt/java
root@bt:~# mv -f jre1.7.0_05/ /opt/java/
root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1
root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java
root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"
For Java 7 (32 bit)
root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/
For Java 8 (64 bit)
root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/
root@bt:~# firefox http://java.com/en/download/testjava.jsp
That this works is not trivial at all! It's a property of the IEEE floating point representation that int°floor = ?·? if the magnitude of the numbers in question is small enough, but different representations are possible where int(floor(2.3)) might be 1.
This post explains why it works in that range.
In a double, you can represent 32bit integers without any problems. There cannot be any rounding issues. More precisely, doubles can represent all integers between and including 253 and -253.
Short explanation: A double can store up to 53 binary digits. When you require more, the number is padded with zeroes on the right.
It follows that 53 ones is the largest number that can be stored without padding. Naturally, all (integer) numbers requiring less digits can be stored accurately.
Adding one to 111(omitted)111 (53 ones) yields 100...000, (53 zeroes). As we know, we can store 53 digits, that makes the rightmost zero padding.
This is where 253 comes from.
More detail: We need to consider how IEEE-754 floating point works.
1 bit 11 / 8 52 / 23 # bits double/single precision
[ sign | exponent | mantissa ]
The number is then calculated as follows (excluding special cases that are irrelevant here):
-1sign × 1.mantissa ×2exponent - bias
where bias = 2exponent - 1 - 1, i.e. 1023 and 127 for double/single precision respectively.
Knowing that multiplying by 2X simply shifts all bits X places to the left, it's easy to see that any integer must have all bits in the mantissa that end up right of the decimal point to zero.
Any integer except zero has the following form in binary:
1x...x where the x-es represent the bits to the right of the MSB (most significant bit).
Because we excluded zero, there will always be a MSB that is one—which is why it's not stored. To store the integer, we must bring it into the aforementioned form: -1sign × 1.mantissa ×2exponent - bias.
That's saying the same as shifting the bits over the decimal point until there's only the MSB towards the left of the MSB. All the bits right of the decimal point are then stored in the mantissa.
From this, we can see that we can store at most 52 binary digits apart from the MSB.
It follows that the highest number where all bits are explicitly stored is
111(omitted)111. that's 53 ones (52 + implicit 1) in the case of doubles.
For this, we need to set the exponent, such that the decimal point will be shifted 52 places. If we were to increase the exponent by one, we cannot know the digit right to the left after the decimal point.
111(omitted)111x.
By convention, it's 0. Setting the entire mantissa to zero, we receive the following number:
100(omitted)00x. = 100(omitted)000.
That's a 1 followed by 53 zeroes, 52 stored and 1 added due to the exponent.
It represents 253, which marks the boundary (both negative and positive) between which we can accurately represent all integers. If we wanted to add one to 253, we would have to set the implicit zero (denoted by the x
) to one, but that's impossible.
I combined the two best solutions to cover all the possibilities:
BufferedReader br = new BufferedReader(new FileReader(fileName));
File file = new File(fileName);
if (br.readLine() == null && file.length() == 0)
{
System.out.println("No errors, and file empty");
}
else
{
System.out.println("File contains something");
}
Here are the changes that I had to make to the accepted answer when I did this with an image as the centre element:
#center
in this case). If it isn't, you'll have to set display
to block
, and it seems to centre relative to the space between the floated elements.Make sure to set the size of both the image and its container:
#center {
margin: 0 auto;
}
#center, #center > img {
width: 100px;
height: auto;
}
https://github.com/jasonday/printThis
$("#myID").printThis();
Great Jquery plugin to do exactly what your after
addEventListener and removeEventListener,the Callback must not be Anonymous inner class,and they should have the same params
The error is also caused by quirky handling of quotes and single qutoes. To include single quotes inside the query, use doubled single quotes.
This won't work
select dbms_xmlgen.getxml("Select ....") XML from dual;
or this either
select dbms_xmlgen.getxml('Select .. where something='red'..') XML from dual;
but this DOES work
select dbms_xmlgen.getxml('Select .. where something=''red''..') XML from dual;
This should do the trick
export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get -q -y install mysql-server
Of course, it leaves you with a blank root password - so you'll want to run something like
mysqladmin -u root password mysecretpasswordgoeshere
Afterwards to add a password to the account.
This can be done by building a javascript object to match your mvc model. The names of the javascript properties have to match exactly to the mvc model or else the autobind won't happen on the post. Once you have your model on the server side you can then manipulate it and store the data to the database.
I am achieving this either by a double click event on a grid row or click event on a button of some sort.
@model TestProject.Models.TestModel
<script>
function testButton_Click(){
var javaModel ={
ModelId: '@Model.TestId',
CreatedDate: '@Model.CreatedDate.ToShortDateString()',
TestDescription: '@Model.TestDescription',
//Here I am using a Kendo editor and I want to bind the text value to my javascript
//object. This may be different for you depending on what controls you use.
TestStatus: ($('#StatusTextBox'))[0].value,
TestType: '@Model.TestType'
}
//Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox
//selected value. This puzzled me due to the conversion to Json object in the Ajax call.
//By parsing the Type to an int this worked.
javaModel.TestType = parseInt(javaModel.TestType);
$.ajax({
//This is where you want to post to.
url:'@Url.Action("TestModelUpdate","TestController")',
async:true,
type:"POST",
contentType: 'application/json',
dataType:"json",
data: JSON.stringify(javaModel)
});
}
</script>
//This is your controller action on the server, and it will autobind your values
//to the newTestModel on post.
[HttpPost]
public ActionResult TestModelUpdate(TestModel newTestModel)
{
TestModel.UpdateTestModel(newTestModel);
return //do some return action;
}
Here's what's been working for me:
<plugin>
<artifactId>exec-maven-plugin</artifactId>
<groupId>org.codehaus.mojo</groupId>
<executions>
<execution><!-- Run our version calculation script -->
<id>Version Calculation</id>
<phase>generate-sources</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>${basedir}/scripts/calculate-version.sh</executable>
</configuration>
</execution>
</executions>
</plugin>
The solution for me on a CentOS 8 system was checking the System Cryptography Policy by verifying the /etc/crypto-policies/config reads the default value of DEFAULT rather than any other value.
Once changing this value to DEFAULT, run the following command:
/usr/bin/update-crypto-policies --set DEFAULT
Rerun the curl command and it should work.
Immutable objects are simply objects whose state (the object's data) cannot change after construction. Examples of immutable objects from the JDK include String and Integer.
For example:(Point is mutable and string immutable)
Point myPoint = new Point( 0, 0 );
System.out.println( myPoint );
myPoint.setLocation( 1.0, 0.0 );
System.out.println( myPoint );
String myString = new String( "old String" );
System.out.println( myString );
myString.replaceAll( "old", "new" );
System.out.println( myString );
The output is:
java.awt.Point[0.0, 0.0]
java.awt.Point[1.0, 0.0]
old String
old String
You can use this simple 'inline' method to construct a string_list_type parameter (works in SQL Server 2014):
declare @p1 dbo.string_list_type
insert into @p1 values(N'myFirstString')
insert into @p1 values(N'mySecondString')
Example use when executing a stored proc:
exec MyStoredProc @MyParam=@p1
Inspired by Johann's table, I've decided to extend the table. I wanted to see which ASCII characters get encoded.
var ascii = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";_x000D_
_x000D_
var encoded = [];_x000D_
_x000D_
ascii.split("").forEach(function (char) {_x000D_
var obj = { char };_x000D_
if (char != encodeURI(char))_x000D_
obj.encodeURI = encodeURI(char);_x000D_
if (char != encodeURIComponent(char))_x000D_
obj.encodeURIComponent = encodeURIComponent(char);_x000D_
if (obj.encodeURI || obj.encodeURIComponent)_x000D_
encoded.push(obj);_x000D_
});_x000D_
_x000D_
console.table(encoded);
_x000D_
Table shows only the encoded characters. Empty cells mean that the original and the encoded characters are the same.
Just to be extra, I'm adding another table for urlencode()
vs rawurlencode()
. The only difference seems to be the encoding of space character.
<script>
<?php
$ascii = str_split(" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", 1);
$encoded = [];
foreach ($ascii as $char) {
$obj = ["char" => $char];
if ($char != urlencode($char))
$obj["urlencode"] = urlencode($char);
if ($char != rawurlencode($char))
$obj["rawurlencode"] = rawurlencode($char);
if (isset($obj["rawurlencode"]) || isset($obj["rawurlencode"]))
$encoded[] = $obj;
}
echo "var encoded = " . json_encode($encoded) . ";";
?>
console.table(encoded);
</script>
Here's a simple-and-stupid approach: on input, discretize your polygons into a bitmap. To intersect, AND the bitmaps together. To produce output polygons, trace out the jaggy borders of the bitmap and smooth the jaggies using a polygon-approximation algorithm. (I don't remember if that link gives the most suitable algorithms, it's just the first Google hit. You might check out one of the tools out there to convert bitmap images to vector representations. Maybe you could call on them without reimplementing the algorithm?)
The most complex part would be tracing out the borders, I think.
Back in the early 90s I faced something like this problem at work, by the way. I muffed it: I came up with a (completely different) algorithm that would work on real-number coordinates, but seemed to run into a completely unfixable plethora of degenerate cases in the face of the realities of floating-point (and noisy input). Perhaps with the help of the internet I'd have done better!
For anyone on Mac OS X, you can find netbeans.conf
here:
/Applications/NetBeans/NetBeans <version>.app/Contents/Resources/NetBeans/etc/netbeans.conf
In case anyone needs to know :)
You can also convert it to an array if you prefer. If Array generics are available:
var args = Array.slice(arguments)
Otherwise:
var args = Array.prototype.slice.call(arguments);
from Mozilla MDN:
You should not slice on arguments because it prevents optimizations in JavaScript engines (V8 for example).
As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.
Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash
is incorrect and should have been callbackOnLocationHash
(note the mis-spelling of "Location").
This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.
Example:
interface TextOptions {
alignment?: string;
color?: string;
padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'
There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes
Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v
or v as T
) do not check for extra properties, so you can use them in place of a type annotation:
interface Options {
x?: string;
y?: number;
}
// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;
Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking
Before
interface Model {
name: string;
}
function createModel(x: Model) { ... }
// Error
createModel({name: 'hello', length: 100});
After
interface Model {
name: string;
[others: string]: any;
}
function createModel(x: Model) { ... }
// OK
createModel({name: 'hello', length: 100});
interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }
let x: Animal;
if(...) {
x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
x = { move: 'catwalk', meow: 'mrar' };
} else {
x = { move: 'gallop', neigh: 'wilbur' };
}
Two good solutions come to mind here
Specify a closed set for x
// Removes all errors
let x: Dog|Cat|Horse;
or Type assert each thing
// For each initialization
x = { move: 'doggy paddle', woof: 'bark' } as Dog;
A clean solution to the "data model" problem using intersection types:
interface DataModelOptions {
name?: string;
id?: number;
}
interface UserProperties {
[key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
/* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
/* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });
See also https://github.com/Microsoft/TypeScript/issues/3755
It is little tricky when you try to combine optional parameter and default value for that parameter. Like this,
func test(param: Int? = nil)
These two are completely opposite ideas. When you have an optional type parameter but you also provide default value to it, it is no more an optional type now since it has a default value. Even if the default is nil, swift simply removes the optional binding without checking what the default value is.
So it is always better not to use nil as default value.
<!--[if IE]>
<style type='text/css'>
#header ul#h-menu li a{font-weight:normal!important}
</style>
<![endif]-->
will apply that style in all versions of IE.
In addition, if you want to see Sources and Console on one window, go to:
"Customize and control DevTools -> "Show console drawer"
You can also see it here at the right corner:
step 1) Declare TextEditingController.
step 2) supply controller to the TextField.
step 3) user controller's text property to change the value of the textField.
follow this official solution to the problem
In the newer versions of Handlebars index (or key in the case of object iteration) is provided by default with the standard each helper.
snippet from : https://github.com/wycats/handlebars.js/issues/250#issuecomment-9514811
The index of the current array item has been available for some time now via @index:
{{#each array}}
{{@index}}: {{this}}
{{/each}}
For object iteration, use @key instead:
{{#each object}}
{{@key}}: {{this}}
{{/each}}
I'm going to say right off the bat that you will not be able to achieve the look they have with radio buttons with strictly CSS.
You could, however, stick to the list style in the example you posted and replace the anchors
with clickable spans
that would trigger a javascript event that would in turn save that rating to your database via ajax.
If you went that route you would probably also want to save a cookie to the users machine so that they could not submit over and over again to your database. That would prevent them from submitting more than once at least until they deleted their cookies.
But of course there are many ways to address this problem. This is just one of them. Hope that helps.
Add maven directory /bin
to System variables under the name Path
.
To check this, you can echo %PATH%
Try to disable SElinux or configuration virtualhost for SElinux
to configuration with SElinux https://muchbits.com/apache-selinux-vhosts.html
to disable SElinux https://linuxize.com/post/how-to-disable-selinux-on-centos-7/
If you have different pool per user make sure user and group are set correctly in configuration file. You can find nginx user in /etc/nginx/nginx.conf file. nginx group is same as nginx user.
user = [pool-user]
group = [pool-group]
listen.owner = [nginx-user]
listen.group = [nginx-group]
Instead of saving it to a file, save it to php://output
Docs:
$objWriter->save('php://output');
This will send it AS-IS to the browser.
You want to add some headersDocs first, like it's common with file downloads, so the browser knows which type that file is and how it should be named (the filename):
// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');
// It will be called file.xls
header('Content-Disposition: attachment; filename="file.xls"');
// Write file to the browser
$objWriter->save('php://output');
First do the headers, then the save. For the excel headers see as well the following question: Setting mime type for excel document.
For the first part, try
echo Aa | od -t x1
It prints byte-by-byte
$ echo Aa | od -t x1
0000000 41 61 0a
0000003
The 0a
is the implicit newline that echo produces.
Use echo -n
or printf
instead.
$ printf Aa | od -t x1
0000000 41 61
0000002
Thanks to the jQuery, a simple HTML5 compliant solution is to create an extra HTML tag, like div, to store the data.
HTML:
<div id='dataDiv' data-arg1='content1' data-arg2='content2'>
<button id='clickButton'>Click me</button>
</div>
JavaScript:
$(document).ready(function() {
var fetchData = $("#dataDiv").data('arg1') +
$("#dataDiv").data('arg2') ;
$('#clickButton').click(function() {
console.log(fetchData);
})
});
Live demo with the code above: http://codepen.io/anon/pen/KzzNmQ?editors=1011#0
On the live demo, one can see the data from HTML5 data-* attributes to be concatenated and printed to the log.
Source: https://api.jquery.com/data/
Specify complete path and grant proper permission to scriptfile. I tried following script file to run through cron:
#!/bin/bash
/bin/mkdir /scratch/ofsaaweb/CHEF_FICHOME/ficdb/bin/crondir
And crontab command is
* * * * * /bin/bash /scratch/ofsaaweb/CHEF_FICHOME/ficdb/bin/test.sh
It worked for me.
I have posted a very simple method to install OpenCV 2.4 for Python in Windows here : Install OpenCV in Windows for Python
It is just as simple as copy and paste. Hope it will be useful for future viewers.
Download Python, Numpy, OpenCV from their official sites.
Extract OpenCV (will be extracted to a folder opencv)
Copy ..\opencv\build\python\x86\2.7\cv2.pyd
Paste it in C:\Python27\Lib\site-packages
Open Python IDLE or terminal, and type
>>> import cv2
If no errors shown, it is OK.
UPDATE (Thanks to dana for this info):
If you are using the VideoCapture feature, you must copy opencv_ffmpeg.dll
into your path as well. See: https://stackoverflow.com/a/11703998/1134940
After struggling for long I was finally able to resolve this issue on Windows, For me the User env variable GIT_SSH was set to point to
"C:\Program Files(x86)\WinScp\PuTTY\plink.exe"
which was installed along with WinScp. I changed the pointing to use default ssh.exe which comes with git-scm "C:\Program Files\Git\usr\bin\ssh.exe"
Yes, just delete the branch by running git push origin :branchname
. To fix a new issue later, branch off from master again.
Sometime I use such class, when I need to return multiple values from a method. Of course, such object is short lived and with very limited visibility, so it should be OK.
If your implementation provides a 64-bit integer type, you may get a different (incorrect) answer by using fmin or fmax. Your 64-bit integers will be converted to doubles, which will (at least usually) have a significand that's smaller than 64-bits. When you convert such a number to a double, some of the least significant bits can/will be lost completely.
This means that two numbers that were really different could end up equal when converted to double -- and the result will be that incorrect number, that's not necessarily equal to either of the original inputs.
Here is swift 3 version of H R's solution.
func overlayImage(color: UIColor) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
color.setFill()
context!.translateBy(x: 0, y: self.size.height)
context!.scaleBy(x: 1.0, y: -1.0)
context!.setBlendMode(CGBlendMode.colorBurn)
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
context!.draw(self.cgImage!, in: rect)
context!.setBlendMode(CGBlendMode.sourceIn)
context!.addRect(rect)
context!.drawPath(using: CGPathDrawingMode.fill)
let coloredImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return coloredImage
}
Update now Chrome also supports MediaRecorder API from v47. The same thing to do would be to use it( guessing native recording method is bound to be faster than work arounds), the API is really easy to use, and you would find tons of answers as to how to upload a blob for the server.
Demo - would work in Chrome and Firefox, intentionally left out pushing blob to server...
Currently, there are three ways to do it:
wav
[ all code client-side, uncompressed recording], you can check out --> Recorderjs. Problem: file size is quite big, more upload bandwidth required.mp3
[ all code client-side, compressed recording], you can check out --> mp3Recorder. Problem: personally, I find the quality bad, also there is this licensing issue.as ogg
[ client+ server(node.js
) code, compressed recording, infinite hours of recording without browser crash ], you can check out --> recordOpus, either only client-side recording, or client-server bundling, the choice is yours.
ogg recording example( only firefox):
var mediaRecorder = new MediaRecorder(stream);
mediaRecorder.start(); // to start recording.
...
mediaRecorder.stop(); // to stop recording.
mediaRecorder.ondataavailable = function(e) {
// do something with the data.
}
Fiddle Demo for ogg recording.
You need to use identical/not identical operators because strpos can return 0 as it's index value. If you like ternary operators, consider using the following (seems a little backwards I'll admit):
echo FALSE === strpos($a,'are') ? 'false': 'true';
The following ways to fetch local JSON file-
ES6 version:
import customData from './customData.json';
or import customData from './customData';
If it's inside .js
file instead of .json
then import like -
import { customData } from './customData';
for more clarification/understanding refer example - Live working demo
There are many valid answers already but I'd like to add anther implementation as a Type extension and a list of unit tests to demonstrate different scenarios:
public static class TypeExtensions
{
public static IEnumerable<Type> GetAllTypes(this Type type)
{
var typeInfo = type.GetTypeInfo();
var allTypes = GetAllImplementedTypes(type).Concat(typeInfo.ImplementedInterfaces);
return allTypes;
}
private static IEnumerable<Type> GetAllImplementedTypes(Type type)
{
yield return type;
var typeInfo = type.GetTypeInfo();
var baseType = typeInfo.BaseType;
if (baseType != null)
{
foreach (var foundType in GetAllImplementedTypes(baseType))
{
yield return foundType;
}
}
}
}
This algorithm supports the following scenarios:
public static class GetAllTypesTests
{
public class Given_A_Sample_Standalone_Class_Type_When_Getting_All_Types
: Given_When_Then_Test
{
private Type _sut;
private IEnumerable<Type> _expectedTypes;
private IEnumerable<Type> _result;
protected override void Given()
{
_sut = typeof(SampleStandalone);
_expectedTypes =
new List<Type>
{
typeof(SampleStandalone),
typeof(object)
};
}
protected override void When()
{
_result = _sut.GetAllTypes();
}
[Fact]
public void Then_It_Should_Return_The_Right_Type()
{
_result.Should().BeEquivalentTo(_expectedTypes);
}
}
public class Given_A_Sample_Abstract_Base_Class_Type_When_Getting_All_Types
: Given_When_Then_Test
{
private Type _sut;
private IEnumerable<Type> _expectedTypes;
private IEnumerable<Type> _result;
protected override void Given()
{
_sut = typeof(SampleBase);
_expectedTypes =
new List<Type>
{
typeof(SampleBase),
typeof(object)
};
}
protected override void When()
{
_result = _sut.GetAllTypes();
}
[Fact]
public void Then_It_Should_Return_The_Right_Type()
{
_result.Should().BeEquivalentTo(_expectedTypes);
}
}
public class Given_A_Sample_Child_Class_Type_When_Getting_All_Types
: Given_When_Then_Test
{
private Type _sut;
private IEnumerable<Type> _expectedTypes;
private IEnumerable<Type> _result;
protected override void Given()
{
_sut = typeof(SampleChild);
_expectedTypes =
new List<Type>
{
typeof(SampleChild),
typeof(SampleBase),
typeof(object)
};
}
protected override void When()
{
_result = _sut.GetAllTypes();
}
[Fact]
public void Then_It_Should_Return_The_Right_Type()
{
_result.Should().BeEquivalentTo(_expectedTypes);
}
}
public class Given_A_Sample_Base_Interface_Type_When_Getting_All_Types
: Given_When_Then_Test
{
private Type _sut;
private IEnumerable<Type> _expectedTypes;
private IEnumerable<Type> _result;
protected override void Given()
{
_sut = typeof(ISampleBase);
_expectedTypes =
new List<Type>
{
typeof(ISampleBase)
};
}
protected override void When()
{
_result = _sut.GetAllTypes();
}
[Fact]
public void Then_It_Should_Return_The_Right_Type()
{
_result.Should().BeEquivalentTo(_expectedTypes);
}
}
public class Given_A_Sample_Child_Interface_Type_When_Getting_All_Types
: Given_When_Then_Test
{
private Type _sut;
private IEnumerable<Type> _expectedTypes;
private IEnumerable<Type> _result;
protected override void Given()
{
_sut = typeof(ISampleChild);
_expectedTypes =
new List<Type>
{
typeof(ISampleBase),
typeof(ISampleChild)
};
}
protected override void When()
{
_result = _sut.GetAllTypes();
}
[Fact]
public void Then_It_Should_Return_The_Right_Type()
{
_result.Should().BeEquivalentTo(_expectedTypes);
}
}
public class Given_A_Sample_Implementation_Class_Type_When_Getting_All_Types
: Given_When_Then_Test
{
private Type _sut;
private IEnumerable<Type> _expectedTypes;
private IEnumerable<Type> _result;
protected override void Given()
{
_sut = typeof(SampleImplementation);
_expectedTypes =
new List<Type>
{
typeof(SampleImplementation),
typeof(SampleChild),
typeof(SampleBase),
typeof(ISampleChild),
typeof(ISampleBase),
typeof(object)
};
}
protected override void When()
{
_result = _sut.GetAllTypes();
}
[Fact]
public void Then_It_Should_Return_The_Right_Type()
{
_result.Should().BeEquivalentTo(_expectedTypes);
}
}
public class Given_A_Sample_Interface_Instance_Type_When_Getting_All_Types
: Given_When_Then_Test
{
private Type _sut;
private IEnumerable<Type> _expectedTypes;
private IEnumerable<Type> _result;
class Foo : ISampleChild { }
protected override void Given()
{
var foo = new Foo();
_sut = foo.GetType();
_expectedTypes =
new List<Type>
{
typeof(Foo),
typeof(ISampleChild),
typeof(ISampleBase),
typeof(object)
};
}
protected override void When()
{
_result = _sut.GetAllTypes();
}
[Fact]
public void Then_It_Should_Return_The_Right_Type()
{
_result.Should().BeEquivalentTo(_expectedTypes);
}
}
sealed class SampleStandalone { }
abstract class SampleBase { }
class SampleChild : SampleBase { }
interface ISampleBase { }
interface ISampleChild : ISampleBase { }
class SampleImplementation : SampleChild, ISampleChild { }
}
If you want to use justify align in Jupyter Notebook use the following syntax:
<p style='text-align: justify;'> Your Text </p>
For right alignment:
<p style='text-align: right;'> Your Text </p>
$a = 1..5
$b = 4..8
$Yellow = $a | Where {$b -NotContains $_}
$Yellow
contains all the items in $a
except the ones that are in $b
:
PS C:\> $Yellow
1
2
3
$Blue = $b | Where {$a -NotContains $_}
$Blue
contains all the items in $b
except the ones that are in $a
:
PS C:\> $Blue
6
7
8
$Green = $a | Where {$b -Contains $_}
Not in question, but anyways; Green
contains the items that are in both $a
and $b
.
PS C:\> $Green
4
5
Note: Where
is an alias of Where-Object
. Alias can introduce possible problems and make scripts hard to maintain.
Addendum 12 October 2019
As commented by @xtreampb and @mklement0: although not shown from the example in the question, the task that the question implies (values "not in common") is the symmetric difference between the two input sets (the union of yellow and blue).
The symmetric difference between the $a
and $b
can be literally defined as the union of $Yellow
and $Blue
:
$NotGreen = $Yellow + $Blue
Which is written out:
$NotGreen = ($a | Where {$b -NotContains $_}) + ($b | Where {$a -NotContains $_})
As you might notice, there are quite some (redundant) loops in this syntax: all items in list $a
iterate (using Where
) through items in list $b
(using -NotContains
) and visa versa. Unfortunately the redundancy is difficult to avoid as it is difficult to predict the result of each side. A Hash Table is usually a good solution to improve the performance of redundant loops. For this, I like to redefine the question: Get the values that appear once in the sum of the collections ($a + $b
):
$Count = @{}
$a + $b | ForEach-Object {$Count[$_] += 1}
$Count.Keys | Where-Object {$Count[$_] -eq 1}
By using the ForEach
statement instead of the ForEach-Object
cmdlet and the Where
method instead of the Where-Object
you might increase the performance by a factor 2.5:
$Count = @{}
ForEach ($Item in $a + $b) {$Count[$Item] += 1}
$Count.Keys.Where({$Count[$_] -eq 1})
But Language Integrated Query (LINQ) will easily beat any native PowerShell and native .Net methods (see also High Performance PowerShell with LINQ and mklement0's answer for Can the following Nested foreach loop be simplified in PowerShell?:
To use LINQ you need to explicitly define the array types:
[Int[]]$a = 1..5
[Int[]]$b = 4..8
And use the [Linq.Enumerable]::
operator:
$Yellow = [Int[]][Linq.Enumerable]::Except($a, $b)
$Blue = [Int[]][Linq.Enumerable]::Except($b, $a)
$Green = [Int[]][Linq.Enumerable]::Intersect($a, $b)
$NotGreen = [Int[]]([Linq.Enumerable]::Except($a, $b) + [Linq.Enumerable]::Except($b, $a))
Benchmark results highly depend on the sizes of the collections and how many items there are actually shared, as a "average", I am presuming that half of each collection is shared with the other.
Using Time
Compare-Object 111,9712
NotContains 197,3792
ForEach-Object 82,8324
ForEach Statement 36,5721
LINQ 22,7091
To get a good performance comparison, caches should be cleared by e.g. starting a fresh PowerShell session.
$a = 1..1000
$b = 500..1500
(Measure-Command {
Compare-Object -ReferenceObject $a -DifferenceObject $b -PassThru
}).TotalMilliseconds
(Measure-Command {
($a | Where {$b -NotContains $_}), ($b | Where {$a -NotContains $_})
}).TotalMilliseconds
(Measure-Command {
$Count = @{}
$a + $b | ForEach-Object {$Count[$_] += 1}
$Count.Keys | Where-Object {$Count[$_] -eq 1}
}).TotalMilliseconds
(Measure-Command {
$Count = @{}
ForEach ($Item in $a + $b) {$Count[$Item] += 1}
$Count.Keys.Where({$Count[$_] -eq 1})
}).TotalMilliseconds
[Int[]]$a = $a
[Int[]]$b = $b
(Measure-Command {
[Int[]]([Linq.Enumerable]::Except($a, $b) + [Linq.Enumerable]::Except($b, $a))
}).TotalMilliseconds
I suspect ^ doesn't work the way you think it does outside of a character class.
What you're telling it to do is replace everything that isn't an alphanumeric with an empty string, OR any leading space. I think what you mean to say is that spaces are ok to not replace - try moving the \s into the [] class.
If you are using arrow functions:
it('should do something', async () => {
// do your testing
}).timeout(15000)
created this code specially for the Hacker earth exam
Scanner values = new Scanner(System.in); //initialize scanner
int[] arr = new int[6]; //initialize array
for (int i = 0; i < arr.length; i++) {
arr[i] = (values.hasNext() == true ? values.nextInt():null);
// it will read the next input value
}
/* user enter = 1 2 3 4 5
arr[1]= 1
arr[2]= 2
and soo on
*/
I'd suggest to add an class='denominationcomune'
to all elements that you want to check and then use the following:
function are_elements_emtpy(class_name)
{
return ($('.' + class_name).filter(function() { return $(this).val() == ''; }).length == 0)
}
Login to virtual machine use below command to check ip address. (anyone will work)
If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1
If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine
If you're using Laravel, do
composer update
This should be work.
Try this code:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
this.menu=menu;
updateMenuItems(menu);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.document_list_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
if (item.getItemId() == android.R.id.home) {
onHomeButtonPresssed();
}else if (item.getItemId() == R.id.action_delete) {
useCheckBoxAdapter=false;
deleteDocuments();
} else if (item.getItemId() == R.id.share) {
useCheckBoxAdapter=false;
shareDocuments();
} else if (item.getItemId() == R.id.action_tick) {
useCheckBoxAdapter=true;
onShowCheckboxes();
}
updateMenuItems(menu);
return true;
}
private void updateMenuItems(Menu menu){
if (useCheckBoxAdapter && menu != null) {
menu.findItem(R.id.action_delete).setVisible(true);
menu.findItem(R.id.share).setVisible(true);
menu.findItem(R.id.action_tick).setVisible(false);
} else {
menu.findItem(R.id.action_delete).setVisible(false);
menu.findItem(R.id.share).setVisible(false);
menu.findItem(R.id.action_tick).setVisible(true);
}
invalidateOptionsMenu();
}
the event property seems to be string first you have to parse it to json :
var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
var event = JSON.parse(req.mandrill_events);
var ts = event[0].ts
DECLARE @UserOptions TABLE(SetOption varchar(100), Value varchar(100))
DECLARE @IsolationLevel varchar(100)
INSERT @UserOptions
EXEC('DBCC USEROPTIONS WITH NO_INFOMSGS')
SELECT @IsolationLevel = Value
FROM @UserOptions
WHERE SetOption = 'isolation level'
-- Do whatever you want with the variable here...
PRINT @IsolationLevel
Enable NSZombieEnabled to know which object is being released and then accessed.
Then check if the getResultSetFromDB:
has anything to do with that. Also check if docids
has anything inside and if it is being retained.
This way you can be sure there is nothing wrong.
.radio-toolbar input[type="radio"] {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.radio-toolbar label {_x000D_
display: inline-block;_x000D_
background-color: #ddd;_x000D_
padding: 4px 11px;_x000D_
font-family: Arial;_x000D_
font-size: 16px;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.radio-toolbar input[type="radio"]:checked+label {_x000D_
background-color: #bbb;_x000D_
}
_x000D_
<div class="radio-toolbar">_x000D_
<input type="radio" id="radio1" name="radios" value="all" checked>_x000D_
<label for="radio1">All</label>_x000D_
_x000D_
<input type="radio" id="radio2" name="radios" value="false">_x000D_
<label for="radio2">Open</label>_x000D_
_x000D_
<input type="radio" id="radio3" name="radios" value="true">_x000D_
<label for="radio3">Archived</label>_x000D_
</div>
_x000D_
First of all, you probably want to add the name
attribute on the radio buttons. Otherwise, they are not part of the same group, and multiple radio buttons can be checked.
Also, since I placed the labels as siblings (of the radio buttons), I had to use the id
and for
attributes to associate them together.
If the message is "n commits behind master."
You need to rebase your dev branch with master. You got the above message because after checking out dev branch from master, the master branch got new commit and has moved ahead. You need to get those new commits to your dev branch.
Steps:
git checkout master
git pull #this will update your local master
git checkout yourDevBranch
git rebase master
Today I was asked this same exercise on pen&paper, so I come up with this function for lists:
def rev(s):
l = len(s)
for i,j in zip(range(l-1, 0, -1), range(l//2)):
s[i], s[j] = s[j], s[i]
return s
which can be used with strings with "".join(rev(list("hello")))
The original frameset model (Frameset and Frame-elements) were very bad from a usability standpoint. IFrame vas a later invention which didn't have as many problems as the original frameset model, but it does have its drawback.
If you allow the user to navigate inside the IFrame, then links and bookmarks will not work as expected (because you bookmark the URL of the outer page, but not the URL of the iframe).
If you have a wamp setup that won't send emails, there is only a couple of things to do. 1. find out what the smtp server name is for your isp. The gmail thing is most likely unnecessary complication 2. create a phpsetup.php file in your 'www' folder and edit like this:
<?php
phpinfo();
?>
this will give you a handle on what wamp is using. 3. search for the php.ini file. there may be serveral. The one you want is the one that effects the output of the file above. 4. find the smtp address in the most likely php.ini. 5. Type in your browser localhost/phpsetup.php and scroll down to smtp setting. it should say 'localhost' 6. edit the php.ini file smtp setting to the name of your ISPs smtp server. check if it changes for you phpsetup.php. if it works your done, if not you are working the wrong file.
this issue should be on the Wordpress site but they are way too up-them-selves or trying to get clients.;)
Before I show you how to reload / refresh model data from the server programmatically? I have to explain for you the concept of Data Binding. This is an extremely powerful concept that will truly revolutionize the way you develop. So may be you have to read about this concept from this link or this seconde link in order to unterstand how AngularjS work.
now I'll show you a sample example that exaplain how can you update your model from server.
HTML Code:
<div ng-controller="PersonListCtrl">
<ul>
<li ng-repeat="person in persons">
Name: {{person.name}}, Age {{person.age}}
</li>
</ul>
<button ng-click="updateData()">Refresh Data</button>
</div>
So our controller named: PersonListCtrl and our Model named: persons. go to your Controller js in order to develop the function named: updateData()
that will be invoked when we are need to update and refresh our Model persons.
Javascript Code:
app.controller('adsController', function($log,$scope,...){
.....
$scope.updateData = function(){
$http.get('/persons').success(function(data) {
$scope.persons = data;// Update Model-- Line X
});
}
});
Now I explain for you how it work:
when user click on button Refresh Data, the server will call to function updateData() and inside this function we will invoke our web service by the function $http.get()
and when we have the result from our ws we will affect it to our model (Line X).Dice that affects the results for our model, our View of this list will be changed with new Data.
Use the json
module (new in Python 2.6) or the simplejson
module which is almost always installed.
Another mock serious answer for a silly question:
The real answer is, use an appropriate data structure. Human genealogy cannot fully be expressed using a pure tree with no cycles. You should use some sort of graph. Also, talk to an anthropologist before going any further with this, because there are plenty of other places similar errors could be made trying to model genealogy, even in the most simple case of "Western patriarchal monogamous marriage."
Even if we want to ignore locally taboo relationships as discussed here, there are plenty of perfectly legal and completely unexpected ways to introduce cycles into a family tree.
For example: http://en.wikipedia.org/wiki/Cousin_marriage
Basically, cousin marriage is not only common and expected, it is the reason humans have gone from thousands of small family groups to a worldwide population of 6 billion. It can't work any other way.
There really are very few universals when it comes to genealogy, family and lineage. Almost any strict assumption about norms suggesting who an aunt can be, or who can marry who, or how children are legitimized for the purpose of inheritance, can be upset by some exception somewhere in the world or history.
SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.
As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.
More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.
You can use CAST
function:
SELECT CAST(your_column_name AS varchar(10)) FROM your_table_name
<%= string_to_datetime("2011-05-19 10:30:14") %>
def string_to_datetime(string,format="%Y-%m-%d %H:%M:%S")
DateTime.strptime(string, format).to_time unless string.blank?
end
I tried using it and didn't work, guess it's just the modal versioin.
Although, it worked as this:
$("#myModal").on("hide.bs.modal", function () {
// put your default event here
});
Just to update the answer =)
You can also create the application.properties file manually.
SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:
The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations). (From the Spring boot features external configuration doc page)
So just go ahead and create it
private boolean isGpsEnabled()
{
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
return service.isProviderEnabled(LocationManager.GPS_PROVIDER)&&service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
IIS Express Users - Using My Documents on a Network Share
If your IIS Express application.config
is located on a network drive, ensure that the drive is mapped and connected in My Computer.
I was facing this issue and when I re-mapped the network drives in My Computer the issue was resolved.
The location of jfxrt.jar in Oracle Java 7 is:
<JRE_HOME>/lib/jfxrt.jar
The location of jfxrt.jar in Oracle Java 8 is:
<JRE_HOME>/lib/ext/jfxrt.jar
The <JRE_HOME>
will depend on where you installed the Oracle Java and may differ between Linux distributions and installations.
jfxrt.jar is not in the Linux OpenJDK 7 (which is what you are using).
An open source package which provides JavaFX 8 for Debian based systems such as Ubuntu is available. To install this package it is necessary to install both the Debian OpenJDK 8 package and the Debian OpenJFX package. I don't run Debian, so I'm not sure where the Debian OpenJFX package installs jfxrt.jar.
Use Oracle Java 8.
With Oracle Java 8, JavaFX is both included in the JDK and is on the default classpath. This means that JavaFX classes will automatically be found both by the compiler during the build and by the runtime when your users use your application. So using Oracle Java 8 is currently the best solution to your issue.
OpenJDK for Java 8 could include JavaFX (as JavaFX for Java 8 is now open source), but it will depend on the OpenJDK package assemblers as to whether they choose to include JavaFX 8 with their distributions. I hope they do, as it should help remove the confusion you experienced in your question and it also provides a great deal more functionality in OpenJDK.
My understanding is that although JavaFX has been included with the standard JDK since version JDK 7u6
Yes, but only the Oracle JDK.
The JavaFX version bundled with Java 7 was not completely open source so it could not be included in the OpenJDK (which is what you are using).
In you need to use Java 7 instead of Java 8, you could download the Oracle JDK for Java 7 and use that. Then JavaFX will be included with Java 7. Due to the way Oracle configured Java 7, JavaFX won't be on the classpath. If you use Java 7, you will need to add it to your classpath and use appropriate JavaFX packaging tools to allow your users to run your application. Some tools such as e(fx)clipse and NetBeans JavaFX project type will take care of classpath issues and packaging tasks for you.
out: dict_values([{1:a, 2:b}])
in: str(dict.values())[14:-3]
out: 1:a, 2:b
Purely for visual purposes. Does not produce a useful product... Only useful if you want a long dictionary to print in a paragraph type form.
I give here 2 ways of coping array, for C and C++ language. memcpy and copy both ar usable on C++ but copy is not usable for C, you have to use memcpy if you are trying to copy array in C.
#include <stdio.h>
#include <iostream>
#include <algorithm> // for using copy (library function)
#include <string.h> // for using memcpy (library function)
int main(){
int arr[] = {1, 1, 2, 2, 3, 3};
int brr[100];
int len = sizeof(arr)/sizeof(*arr); // finding size of arr (array)
std:: copy(arr, arr+len, brr); // which will work on C++ only (you have to use #include <algorithm>
memcpy(brr, arr, len*(sizeof(int))); // which will work on both C and C++
for(int i=0; i<len; i++){ // Printing brr (array).
std:: cout << brr[i] << " ";
}
return 0;
}
import java.util.*;
public class Main {
public static void main(String[] args) {
TreeMap<String, Integer> initTree = new TreeMap();
initTree.put("D", 0);
initTree.put("C", -3);
initTree.put("A", 43);
initTree.put("B", 32);
System.out.println("Sorted by keys:");
System.out.println(initTree);
List list = new ArrayList(initTree.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
return e1.getValue().compareTo(e2.getValue());
}
});
System.out.println("Sorted by values:");
System.out.println(list);
}
}
In some cases when using numpy arrays, using random.shuffle
created duplicate data in the array.
An alternative is to use numpy.random.shuffle
. If you're working with numpy already, this is the preferred method over the generic random.shuffle
.
Example
>>> import numpy as np
>>> import random
Using random.shuffle
:
>>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> foo
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> random.shuffle(foo)
>>> foo
array([[1, 2, 3],
[1, 2, 3],
[4, 5, 6]])
Using numpy.random.shuffle
:
>>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> foo
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> np.random.shuffle(foo)
>>> foo
array([[1, 2, 3],
[7, 8, 9],
[4, 5, 6]])
If you are working with Source safe then make a new directory and take the latest there, this solved my issue...thanks
To fetch only current date excluding time stamp:
in lower versions, looks like hive CURRENT_DATE is not available, hence you can use (it worked for me on Hive 0.14)
select TO_DATE(FROM_UNIXTIME(UNIX_TIMESTAMP()));
In higher versions say hive 2.0, you can use :
select CURRENT_DATE;
May be easier using a java.util.HashSet. For example:
List <String> list = new ArrayList<String>();
list.add("behold");
list.add("bend");
list.add("bet");
//Load the list into a hashSet
Set<String> set = new HashSet<String>(list);
if (set.contains("bend"))
{
System.out.println("String found!");
}
WordUtils.capitalizeFully(str)
from apache commons-lang has the exact semantics as required.
The "ARM EABI v7a System Image" must be available. Install it via the Android SDK manager:
Another hint (see here) - with
you are able to turn on GPU emulation to get a faster emulator:
Note : As per you786 comment if you have previously created emulator then you need to recreate it, otherwise this will not work.
Alternative 1
Intel provides the "Intel hardware accelerated execution manager", which is a VM based emulator for executing X86 images and which is also served by the Android SDK Manager. See a tutorial for the Intel emulator here: HAXM Speeds Up the Android Emulator. Roman Nurik posts here that the Intel emulator with Android 4.3 is "blazing fast".
Alternative 2
In the comments of the post above you can find a reference to Genymotion which claims to be the "fastest Android emulator for app testing and presentation". Genymotion runs on VirtualBox. See also their site on Google+, this post from Cyril Mottier and this guide on reddit.
Alternative 3
In XDA-Forums I read about MEmu - Most Powerful Android Emulator for PC, Better Than Bluestacks. You can find the emulator here. This brings me to ...
Alternative 4
... this XDA-Forum entry: How to use THE FAST! BlueStack as your alternate Android development emulator. You can find the emulator here.
With a small change, it worked fine for me
$qb=$this->dm->createQueryBuilder('AppBundle:CSSDInstrument')
->update()
->field('status')->set($status)
->field('id')->equals($instrumentId)
->getQuery()
->execute();
I am not an expert in this field, but unit testing should test behaviour, not implementation. Private methods are strictly part of the implementation, so IMHO should not be tested.
Jackson provides an annotation that can be used on class level (JsonIgnoreProperties).
Add the following to the top of your class (not to individual methods):
@JsonIgnoreProperties(ignoreUnknown = true)
public class Foo {
...
}
Depending on the jackson version you are using you would have to use a different import in the current version it is:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
in older versions it has been:
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
String reverse(String s) {
int legnth = s.length();
char[] arrayCh = s.toCharArray();
for(int i=0; i< length/2; i++) {
char ch = s.charAt(i);
arrayCh[i] = arrayCh[legnth-1-i];
arrayCh[legnth-1-i] = ch;
}
return new String(arrayCh);
}
See if this works.
import java.util.ArrayList;
import java.util.List;
public class ArrayListComparison {
public static void main(String[] args) {
List<MyData> list1 = new ArrayList<MyData>();
list1.add(new MyData("Ram", true));
list1.add(new MyData("Hariom", true));
list1.add(new MyData("Shiv", true));
// list1.add(new MyData("Shiv", false));
List<MyData> list2 = new ArrayList<MyData>();
list2.add(new MyData("Ram", true));
list2.add(new MyData("Hariom", true));
list2.add(new MyData("Shiv", true));
System.out.println("Lists are equal:" + listEquals(list1, list2));
}
private static boolean listEquals(List<MyData> list1, List<MyData> list2) {
if(list1.size() != list2.size())
return true;
for (MyData myData : list1) {
if(!list2.contains(myData))
return true;
}
return false;
}
}
class MyData{
String name;
boolean check;
public MyData(String name, boolean check) {
super();
this.name = name;
this.check = check;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (check ? 1231 : 1237);
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyData other = (MyData) obj;
if (check != other.check)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
Another simple solution is to use map()
as follows:
tensor_shape = map(int, my_tensor.shape)
This converts all the Dimension
objects to int
Since aa
is the set/object that might be null, can you check aa == null
?
(aa
/ xx
might be interchangeable (a typo in the question); the original question talks about xx
but only defines aa
)
i.e.
select new {
AssetID = x.AssetID,
Status = aa == null ? (bool?)null : aa.Online; // a Nullable<bool>
}
or if you want the default to be false
(not null
):
select new {
AssetID = x.AssetID,
Status = aa == null ? false : aa.Online;
}
Update; in response to the downvote, I've investigated more... the fact is, this is the right approach! Here's an example on Northwind:
using(var ctx = new DataClasses1DataContext())
{
ctx.Log = Console.Out;
var qry = from boss in ctx.Employees
join grunt in ctx.Employees
on boss.EmployeeID equals grunt.ReportsTo into tree
from tmp in tree.DefaultIfEmpty()
select new
{
ID = boss.EmployeeID,
Name = tmp == null ? "" : tmp.FirstName
};
foreach(var row in qry)
{
Console.WriteLine("{0}: {1}", row.ID, row.Name);
}
}
And here's the TSQL - pretty much what we want (it isn't ISNULL
, but it is close enough):
SELECT [t0].[EmployeeID] AS [ID],
(CASE
WHEN [t2].[test] IS NULL THEN CONVERT(NVarChar(10),@p0)
ELSE [t2].[FirstName]
END) AS [Name]
FROM [dbo].[Employees] AS [t0]
LEFT OUTER JOIN (
SELECT 1 AS [test], [t1].[FirstName], [t1].[ReportsTo]
FROM [dbo].[Employees] AS [t1]
) AS [t2] ON ([t0].[EmployeeID]) = [t2].[ReportsTo]
-- @p0: Input NVarChar (Size = 0; Prec = 0; Scale = 0) []
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1
QED?
Select "File" -> "Project Structure".
Under "Project Settings" select "Project"
From there you can select the "Project SDK".
bash -n scriptname
Perhaps an obvious caveat: this validates syntax but won't check if your bash script tries to execute a command that isn't in your path, like ech hello
instead of echo hello
.
Supergeek, your non recursive function did not producte the correct result, but mine does. I believe yours does one too many additions.
private Point LocationOnClient(Control c)
{
Point retval = new Point(0, 0);
for (; c.Parent != null; c = c.Parent)
{ retval.Offset(c.Location); }
return retval;
}
You can set max value for your seekbar by using this code:
sb1.setMax(100);
This will set the max value for your seekbar.
But you cannot set the minimum value but yes you can do some arithmetic to adjust value. Use arithmetic to adjust your application-required value.
For example, suppose you have data values from -50 to 100 you want to display on the SeekBar. Set the SeekBar's maximum to be 150 (100-(-50)), then subtract 50 from the raw value to get the number you should use when setting the bar position.
You can get more info via this link.
ugh, just to iterate over my own case, which gave out approximately the same error - in the Resource declaration (server.xml) make sure to NOT omit driverClassName, and that e.g. for Oracle it is "oracle.jdbc.OracleDriver", and that the right JAR file (e.g. ojdbc14.jar) exists in %CATALINA_HOME%/lib
The clean
, install
and deploy
phases are valid lifecycle phases and invoking them will trigger all the phases preceding them, and the goals bound to these phases.
mvn clean install
This command invokes the clean
phase and then the install
phase sequentially:
clean
: removes files generated at build-time in a project's directory (target
by default)install
: installs the package into the local repository, for use as a dependency in other projects locally.mvn deploy
This command invokes the deploy
phase:
deploy
: copies the final package to the remote repository for sharing with other developers and projects.mvn release
This is not a valid phase nor a goal so this won't do anything. But if refers to the Maven Release Plugin that is used to automate release management. Releasing a project is done in two steps: prepare
and perform
. As documented:
Preparing a release goes through the following release phases:
- Check that there are no uncommitted changes in the sources
- Check that there are no SNAPSHOT dependencies
- Change the version in the POMs from x-SNAPSHOT to a new version (you will be prompted for the versions to use)
- Transform the SCM information in the POM to include the final destination of the tag
- Run the project tests against the modified POMs to confirm everything is in working order
- Commit the modified POMs
- Tag the code in the SCM with a version name (this will be prompted for)
- Bump the version in the POMs to a new value y-SNAPSHOT (these values will also be prompted for)
- Commit the modified POMs
And then:
Performing a release runs the following release phases:
- Checkout from an SCM URL with optional tag
- Run the predefined Maven goals to release the project (by default, deploy site-deploy)
you can use your method by this way
var app = 'AirFare';
var d1 = new Date();
var d2 = new Date();
$http({
url: '/api/apiControllerName/methodName',
method: 'POST',
params: {application:app, from:d1, to:d2},
headers: { 'Content-Type': 'application/json;charset=utf-8' },
//timeout: 1,
//cache: false,
//transformRequest: false,
//transformResponse: false
}).then(function (results) {
return results;
}).catch(function (e) {
});
You could easily use:
label1.Text = dateTimePicker1.Value.Date.ToString("dd/MM/yyyy")
and if you want to change '/' or '-', just add this:
label1.Text = label1.Text.Replace(".", "-")
More info about DateTimePicker.CustomFormat Property: Link
Below is the fixed code:
#!/bin/ksh
safeRunCommand() {
typeset cmnd="$*"
typeset ret_code
echo cmnd=$cmnd
eval $cmnd
ret_code=$?
if [ $ret_code != 0 ]; then
printf "Error : [%d] when executing command: '$cmnd'" $ret_code
exit $ret_code
fi
}
command="ls -l | grep p"
safeRunCommand "$command"
Now if you look into this code few things that I changed are:
typeset
is not necessary but a good practice. It make cmnd
and ret_code
local to safeRunCommand
ret_code
is not necessary but a good practice to store return code in some variable (and store it ASAP) so that you can use it later like I did in printf "Error : [%d] when executing command: '$command'" $ret_code
safeRunCommand "$command"
. If you dont then cmnd
will get only the value ls
and not ls -l
. And it is even more important if your command contains pipes.typeset cmnd="$*"
instead of typeset cmnd="$1"
if you want to keep the spaces. You can try with both depending upon how complex is your command argument.NOTE: Do remember some commands give 1 as return code even though there is no error like grep
. If grep
found something it will return 0 else 1.
I had tested with KSH/BASH. And it worked fine. Let me know if u face issues running this.
You can use the java.time
package (since Java8 and late) to get start/end of day/week/month.
The util class example below:
import org.junit.Test;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
public class DateUtil {
private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of("UTC");
public static LocalDateTime startOfDay() {
return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MIN);
}
public static LocalDateTime endOfDay() {
return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MAX);
}
public static boolean belongsToCurrentDay(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfDay()) && localDateTime.isBefore(endOfDay());
}
//note that week starts with Monday
public static LocalDateTime startOfWeek() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MIN)
.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
}
//note that week ends with Sunday
public static LocalDateTime endOfWeek() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MAX)
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
}
public static boolean belongsToCurrentWeek(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfWeek()) && localDateTime.isBefore(endOfWeek());
}
public static LocalDateTime startOfMonth() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MIN)
.with(TemporalAdjusters.firstDayOfMonth());
}
public static LocalDateTime endOfMonth() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MAX)
.with(TemporalAdjusters.lastDayOfMonth());
}
public static boolean belongsToCurrentMonth(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfMonth()) && localDateTime.isBefore(endOfMonth());
}
public static long toMills(final LocalDateTime localDateTime) {
return localDateTime.atZone(DEFAULT_ZONE_ID).toInstant().toEpochMilli();
}
public static Date toDate(final LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(DEFAULT_ZONE_ID).toInstant());
}
public static String toString(final LocalDateTime localDateTime) {
return localDateTime.format(DateTimeFormatter.ISO_DATE_TIME);
}
@Test
public void test() {
//day
final LocalDateTime now = LocalDateTime.now();
System.out.println("Now: " + toString(now) + ", in mills: " + toMills(now));
System.out.println("Start of day: " + toString(startOfDay()));
System.out.println("End of day: " + toString(endOfDay()));
System.out.println("Does '" + toString(now) + "' belong to the current day? > " + belongsToCurrentDay(now));
final LocalDateTime yesterday = now.minusDays(1);
System.out.println("Does '" + toString(yesterday) + "' belong to the current day? > " + belongsToCurrentDay(yesterday));
final LocalDateTime tomorrow = now.plusDays(1);
System.out.println("Does '" + toString(tomorrow) + "' belong to the current day? > " + belongsToCurrentDay(tomorrow));
//week
System.out.println("Start of week: " + toString(startOfWeek()));
System.out.println("End of week: " + toString(endOfWeek()));
System.out.println("Does '" + toString(now) + "' belong to the current week? > " + belongsToCurrentWeek(now));
final LocalDateTime previousWeek = now.minusWeeks(1);
System.out.println("Does '" + toString(previousWeek) + "' belong to the current week? > " + belongsToCurrentWeek(previousWeek));
final LocalDateTime nextWeek = now.plusWeeks(1);
System.out.println("Does '" + toString(nextWeek) + "' belong to the current week? > " + belongsToCurrentWeek(nextWeek));
//month
System.out.println("Start of month: " + toString(startOfMonth()));
System.out.println("End of month: " + toString(endOfMonth()));
System.out.println("Does '" + toString(now) + "' belong to the current month? > " + belongsToCurrentMonth(now));
final LocalDateTime previousMonth = now.minusMonths(1);
System.out.println("Does '" + toString(previousMonth) + "' belong to the current month? > " + belongsToCurrentMonth(previousMonth));
final LocalDateTime nextMonth = now.plusMonths(1);
System.out.println("Does '" + toString(nextMonth) + "' belong to the current month? > " + belongsToCurrentMonth(nextMonth));
}
}
Test output:
Now: 2020-02-16T22:12:49.957, in mills: 1581891169957
Start of day: 2020-02-16T00:00:00
End of day: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current day? > true
Does '2020-02-15T22:12:49.957' belong to the current day? > false
Does '2020-02-17T22:12:49.957' belong to the current day? > false
Start of week: 2020-02-10T00:00:00
End of week: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current week? > true
Does '2020-02-09T22:12:49.957' belong to the current week? > false
Does '2020-02-23T22:12:49.957' belong to the current week? > false
Start of month: 2020-02-01T00:00:00
End of month: 2020-02-29T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current month? > true
Does '2020-01-16T22:12:49.957' belong to the current month? > false
Does '2020-03-16T22:12:49.957' belong to the current month? > false
There is a difference between .
and text()
, but this difference might not surface because of your input document.
If your input document looked like (the simplest document one can imagine given your XPath expressions)
Example 1
<html>
<a>Ask Question</a>
</html>
Then //a[text()="Ask Question"]
and //a[.="Ask Question"]
indeed return exactly the same result. But consider a different input document that looks like
Example 2
<html>
<a>Ask Question<other/>
</a>
</html>
where the a
element also has a child element other
that follows immediately after "Ask Question". Given this second input document, //a[text()="Ask Question"]
still returns the a
element, while //a[.="Ask Question"]
does not return anything!
This is because the meaning of the two predicates (everything between [
and ]
) is different. [text()="Ask Question"]
actually means: return true if any of the text nodes of an element contains exactly the text "Ask Question". On the other hand, [.="Ask Question"]
means: return true if the string value of an element is identical to "Ask Question".
In the XPath model, text inside XML elements can be partitioned into a number of text nodes if other elements interfere with the text, as in Example 2 above. There, the other
element is between "Ask Question" and a newline character that also counts as text content.
To make an even clearer example, consider as an input document:
Example 3
<a>Ask Question<other/>more text</a>
Here, the a
element actually contains two text nodes, "Ask Question" and "more text", since both are direct children of a
. You can test this by running //a/text()
on this document, which will return (individual results separated by ----
):
Ask Question
-----------------------
more text
So, in such a scenario, text()
returns a set of individual nodes, while .
in a predicate evaluates to the string concatenation of all text nodes. Again, you can test this claim with the path expression //a[.='Ask Questionmore text']
which will successfully return the a
element.
Finally, keep in mind that some XPath functions can only take one single string as an input. As LarsH has pointed out in the comments, if such an XPath function (e.g. contains()
) is given a sequence of nodes, it will only process the first node and silently ignore the rest.
This is an example which produces output separate by commas. You can replace the comma by whatever separator you need.
cat <<EOD | xargs | sed 's/ /,/g'
> 1
> 2
> 3
> 4
> 5
> EOD
produces:
1,2,3,4,5
You can use css float
<div style='float: left;'><a href="login.php">Log in</a></div>
<div style='float: right;'><a href="home.php">Back to Home</a></div>
Have a look at this CSS Positioning
Just if someone is interested in another option:
content=( $(cat test.txt) )
a=0
while [ $a -le ${#content[@]} ]
do
echo ${content[$a]}
a=$[a+1]
done
The advantage of IEnumerable is deferred execution (usually with databases). The query will not get executed until you actually loop through the data. It's a query waiting until it's needed (aka lazy loading).
If you call ToList, the query will be executed, or "materialized" as I like to say.
There are pros and cons to both. If you call ToList, you may remove some mystery as to when the query gets executed. If you stick to IEnumerable, you get the advantage that the program doesn't do any work until it's actually required.