Java libs makes it almost a one liner to read the public cert, as generated by openssl:
val certificate: X509Certificate = ByteArrayInputStream(
publicKeyCert.toByteArray(Charsets.US_ASCII))
.use {
CertificateFactory.getInstance("X.509")
.generateCertificate(it) as X509Certificate
}
But, o hell, reading the private key was problematic:
RSAPrivateKey
.see this: Final solution in kotlin
This is PKCS#1 format of a private key. Try this code. It doesn't use Bouncy Castle or other third-party crypto providers. Just java.security and sun.security for DER sequece parsing. Also it supports parsing of a private key in PKCS#8 format (PEM file that has a header "-----BEGIN PRIVATE KEY-----").
import sun.security.util.DerInputStream;
import sun.security.util.DerValue;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Base64;
public static PrivateKey pemFileLoadPrivateKeyPkcs1OrPkcs8Encoded(File pemFileName) throws GeneralSecurityException, IOException {
// PKCS#8 format
final String PEM_PRIVATE_START = "-----BEGIN PRIVATE KEY-----";
final String PEM_PRIVATE_END = "-----END PRIVATE KEY-----";
// PKCS#1 format
final String PEM_RSA_PRIVATE_START = "-----BEGIN RSA PRIVATE KEY-----";
final String PEM_RSA_PRIVATE_END = "-----END RSA PRIVATE KEY-----";
Path path = Paths.get(pemFileName.getAbsolutePath());
String privateKeyPem = new String(Files.readAllBytes(path));
if (privateKeyPem.indexOf(PEM_PRIVATE_START) != -1) { // PKCS#8 format
privateKeyPem = privateKeyPem.replace(PEM_PRIVATE_START, "").replace(PEM_PRIVATE_END, "");
privateKeyPem = privateKeyPem.replaceAll("\\s", "");
byte[] pkcs8EncodedKey = Base64.getDecoder().decode(privateKeyPem);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(new PKCS8EncodedKeySpec(pkcs8EncodedKey));
} else if (privateKeyPem.indexOf(PEM_RSA_PRIVATE_START) != -1) { // PKCS#1 format
privateKeyPem = privateKeyPem.replace(PEM_RSA_PRIVATE_START, "").replace(PEM_RSA_PRIVATE_END, "");
privateKeyPem = privateKeyPem.replaceAll("\\s", "");
DerInputStream derReader = new DerInputStream(Base64.getDecoder().decode(privateKeyPem));
DerValue[] seq = derReader.getSequence(0);
if (seq.length < 9) {
throw new GeneralSecurityException("Could not parse a PKCS1 private key.");
}
// skip version seq[0];
BigInteger modulus = seq[1].getBigInteger();
BigInteger publicExp = seq[2].getBigInteger();
BigInteger privateExp = seq[3].getBigInteger();
BigInteger prime1 = seq[4].getBigInteger();
BigInteger prime2 = seq[5].getBigInteger();
BigInteger exp1 = seq[6].getBigInteger();
BigInteger exp2 = seq[7].getBigInteger();
BigInteger crtCoef = seq[8].getBigInteger();
RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(keySpec);
}
throw new GeneralSecurityException("Not supported format of a private key");
}
Disclaimer: I am the author of Jsonix, a powerful open-source XML<->JSON JavaScript mapping library.
Today I've released the new version of the Jsonix Schema Compiler, with the new JSON Schema generation feature.
Let's take the Purchase Order schema for example. Here's a fragment:
<xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
<xsd:complexType name="PurchaseOrderType">
<xsd:sequence>
<xsd:element name="shipTo" type="USAddress"/>
<xsd:element name="billTo" type="USAddress"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="items" type="Items"/>
</xsd:sequence>
<xsd:attribute name="orderDate" type="xsd:date"/>
</xsd:complexType>
You can compile this schema using the provided command-line tool:
java -jar jsonix-schema-compiler-full.jar
-generateJsonSchema
-p PO
schemas/purchaseorder.xsd
The compiler generates Jsonix mappings as well the matching JSON Schema.
Here's what the result looks like (edited for brevity):
{
"id":"PurchaseOrder.jsonschema#",
"definitions":{
"PurchaseOrderType":{
"type":"object",
"title":"PurchaseOrderType",
"properties":{
"shipTo":{
"title":"shipTo",
"allOf":[
{
"$ref":"#/definitions/USAddress"
}
]
},
"billTo":{
"title":"billTo",
"allOf":[
{
"$ref":"#/definitions/USAddress"
}
]
}, ...
}
},
"USAddress":{ ... }, ...
},
"anyOf":[
{
"type":"object",
"properties":{
"name":{
"$ref":"http://www.jsonix.org/jsonschemas/w3c/2001/XMLSchema.jsonschema#/definitions/QName"
},
"value":{
"$ref":"#/definitions/PurchaseOrderType"
}
},
"elementName":{
"localPart":"purchaseOrder",
"namespaceURI":""
}
}
]
}
Now this JSON Schema is derived from the original XML Schema. It is not exactly 1:1 transformation, but very very close.
The generated JSON Schema matches the generatd Jsonix mappings. So if you use Jsonix for XML<->JSON conversion, you should be able to validate JSON with the generated JSON Schema. It also contains all the required metadata from the originating XML Schema (like element, attribute and type names).
Disclaimer: At the moment this is a new and experimental feature. There are certain known limitations and missing functionality. But I'm expecting this to manifest and mature very fast.
Links:
npm install
Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.
if (window.location.href.indexOf("?added-to-cart=555") > -1) {
alert("found it");
}
Bad news I'm afraid (or maybe great news?) : it isn't C code, it's an example of "Processing" - an open source language aimed at programming images. Take a look here
Looks very cool.
It's been more than 10 years and not sure if anyone still finding this question or answer relevant.
But a quick workaround is just to wrap the asp control
within a html container
<div id="myElement" style="display: inline-block">
<asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
</div>
Whenever the Javascript Event
is triggered, if it needs to be an event by the asp control
, just wrap the asp control
around the div
container.
<div id="testG">
<asp:Button ID="Button2" runat="server" CssClass="btn" Text="Activate" />
</div>
The jQuery Code is below:
$(document).ready(function () {
$("#testG").click(function () {
$("#myElement").css("display", "none");
});
});
If you want to convert an Instant
to a Date
:
Date myDate = Date.from(instant);
And then you can use SimpleDateFormat
for the formatting part of your question:
SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
String formattedDate = formatter.format(myDate);
Figured this out:
<input type="text" id="txtSearch" onkeypress="return searchKeyPress(event);" />
<input type="button" id="btnSearch" Value="Search" onclick="doSomething();" />
<script>
function searchKeyPress(e)
{
// look for window.event in case event isn't passed in
e = e || window.event;
if (e.keyCode == 13)
{
document.getElementById('btnSearch').click();
return false;
}
return true;
}
</script>
I believe IsEmpty is just method that takes return value of Cell and checks if its Empty so: IsEmpty(.Cell(i,1)) does ->
return .Cell(i,1) <> Empty
yes! you should be using pip as your python package manager ( http://pypi.python.org/pypi/pip )
with pip installed packages, you can do a
pip freeze
and it will list all installed packages. You should probably also be using virtualenv and virtualenvwrapper. When you start a new project, you can do
mkvirtualenv my_new_project
and then (inside that virtualenv), do
pip install all_your_stuff
This way, you can workon my_new_project
and then pip freeze
to see which packages are installed for that virtualenv/project.
for example:
? ~ mkvirtualenv yo_dude
New python executable in yo_dude/bin/python
Installing setuptools............done.
Installing pip...............done.
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/predeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postdeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/preactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/get_env_details
(yo_dude)? ~ pip install django
Downloading/unpacking django
Downloading Django-1.4.1.tar.gz (7.7Mb): 7.7Mb downloaded
Running setup.py egg_info for package django
Installing collected packages: django
Running setup.py install for django
changing mode of build/scripts-2.7/django-admin.py from 644 to 755
changing mode of /Users/aaylward/dev/virtualenvs/yo_dude/bin/django-admin.py to 755
Successfully installed django
Cleaning up...
(yo_dude)? ~ pip freeze
Django==1.4.1
wsgiref==0.1.2
(yo_dude)? ~
or if you have a python package with a requirements.pip file,
mkvirtualenv my_awesome_project
pip install -r requirements.pip
pip freeze
will do the trick
In python this work for me
self.set_your_value = "your value"
def your_method_name(self):
self.driver.find_element_by_name(self.set_your_value).send_keys(Keys.TAB)`
According to the jQuery documentation for .keypress(), it does not catch non-printable characters, so backspace will not work on keypress, but it is caught in keydown and keyup:
The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser. (https://api.jquery.com/keypress/)
In some instances keyup isn't desired or has other undesirable effects and keydown is sufficient, so one way to handle this is to use keydown
to catch all keystrokes then set a timeout of a short interval so that the key is entered, then do processing in there after.
jQuery(el).keydown( function() {
var that = this; setTimeout( function(){
/** Code that processes backspace, etc. **/
}, 100 );
} );
The answers given here already may work in limited situations, but are certainly not the best way to go about it. Don't reinvent the wheel. The File System Object in the Microsoft Scripting Runtime library already has a method to do exactly this. It's called GetBaseName. It handles periods in the file name as is.
Public Sub Test()
Dim fso As New Scripting.FileSystemObject
Debug.Print fso.GetBaseName(ActiveWorkbook.Name)
End Sub
Public Sub Test2()
Dim fso As New Scripting.FileSystemObject
Debug.Print fso.GetBaseName("MyFile.something.txt")
End Sub
Instructions for adding a reference to the Scripting Library
Your piece of script works just great. Are you sure you are not assigning anything else before the if to "i"?
A common mistake is also not to leave a space after and before the square brackets.
On WebStorm 2016.3
Press ALT+F12 (open terminal)
Run this command:
npm install require.js
For a JQM+PhoneGap app the following worked for me.
The following was the minimum I had to go to get this to work. I was actually experiencing a stall due to the buffering while spawning ajax requests when the user pressed the back button. Pausing the video in Chrome and the Android browser kept it buffering. The non-async ajax request would get stuck waiting for the buffering to finish, which it never would.
Binding this to the beforepagehide event fixed it.
$("#SOME_JQM_PAGE").live("pagebeforehide", function(event)
{
$("video").each(function ()
{
logger.debug("PAUSE VIDEO");
this.pause();
this.src = "";
});
});
This will clear every video tag on the page.
The important part is this.src = "";
I just wanted to add that if you don't see Team -> Share project, it's likely you have to remove the project from the workspace before importing it back in. This is what happened to me, and I had to remove and readd it to the workspace for it to fix itself. (This happened when moving from dramatically different Eclipse versions + plugins using the same workspace.)
subclipse not showing "share project" option on project context menu in eclipse
Provided my_command
is canonically designed, ie returns 0 when succeeds, then &&
is exactly the opposite of what you want. You want ||
.
Also note that (
does not seem right to me in bash, but I cannot try from where I am. Tell me.
my_command || {
echo 'my_command failed' ;
exit 1;
}
HTML & CSS - No Javascript Solution
Make your button appear like a Bootstrap link
HTML:
<form>
<button class="btn-link">Submit</button>
</form>
CSS:
.btn-link {
background: none;
border: none;
padding: 0px;
color: #3097D1;
font: inherit;
}
.btn-link:hover {
color: #216a94;
text-decoration: underline;
}
In adition to Ian Boyd's answer:
Also CultureInfo
implements this interface and can be used in your case. So you could parse a French date string for example; you could use
var ci = new CultureInfo("fr-FR");
DateTime dt = DateTime.ParseExact(yourDateInputString, yourFormatString, ci);
Git -> SVN with complete commit history
I had a Git project and had to move it to SVN. This is how I made it, keeping the whole commit history. The only thing that gets lost is the original commit time since libSVN will set the local time when we do git svn dcommit
.
Howto:
Have a SVN repository where we want to import our stuff to and clone it with git-svn:
git svn clone https://path.to/svn/repository repo.git-svn`
Go there:
cd repo.git-svn
Add the remote of the Git repository (in this example I'm using C:/Projects/repo.git). You want to push to SVN and give it the name old-git:
git remote add old-git file:///C/Projects/repo.git/
Fetch the information from the master branch from the old-git repository to the current repository:
git fetch old-git master
Checkout the master branch of the old-git remote into a new branch called old in the current repository:
git checkout -b old old-git/master`
Rebase to put the HEAD on top of old-git/master. This will maintain all your commits. What this does basically is to take all of your work done in Git and put it on top of the work you are accessing from SVN.
git rebase master
Now go back to your master branch:
git checkout master
And you can see that you have a clean commit history. This is what you want to push to SVN.
Push your work to SVN:
git svn dcommit
That's all. It is very clean, no hacking, and everything works perfectly out of the box. Enjoy.
Add the @Configuration
annotation in the RestTemplateSOMENAME which extends the RestTemplate class.
@Configuration
public class RestTemplateClass extends RestTemplate {
}
Then in your controller class you can use the Autowired annotation as follows.
@Autowired
RestTemplateClass restTemplate;
Selenium2Library has get_location():
import Selenium2Library
s = Selenium2Library.Selenium2Library()
url = s.get_location()
You can use lodash sortBy (https://lodash.com/docs/4.17.4#sortBy).
Your code could be like:
const myArray = [
{
"id":25,
"name":"Anakin Skywalker",
"createdAt":"2017-04-12T12:48:55.000Z",
"updatedAt":"2017-04-12T12:48:55.000Z"
},
{
"id":1,
"name":"Luke Skywalker",
"createdAt":"2017-04-12T11:25:03.000Z",
"updatedAt":"2017-04-12T11:25:03.000Z"
}
]
const myOrderedArray = _.sortBy(myArray, o => o.name)
i fixed this by running sudo apachectl stop
- turns out apache was running in the background and prevented nginx from starting on the desired port.
On ubuntu run sudo /etc/init.d/apache2 stop
Something like this:
HTML:
<select id="choice">
<option value="0" selected="selected">Choose...</option>
<option value="1">Something</option>
<option value="2">Something else</option>
<option value="3">Another choice</option>
</select>
CSS:
#choice option { color: black; }
.empty { color: gray; }
JavaScript:
$("#choice").change(function () {
if($(this).val() == "0") $(this).addClass("empty");
else $(this).removeClass("empty")
});
$("#choice").change();
Working example: http://jsfiddle.net/Zmf6t/
It's for the same reason you don't write every method of every class to return "object". You should be as specific as you can. This is especially valuable if you're planning to write unit tests. No more testing return types and/or casting the result.
I faced exactly the same issue in a Spring web app. In fact, I had removed spring-security by commenting the config annotation:
// @ImportResource({"/WEB-INF/spring-security.xml"})
but I had forgotten to remove the corresponding filters in web.xml
:
<!-- Filters -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Commenting filters solved the issue.
As far as I can tell, there is no way to write a setter for a class property without creating a new metaclass.
I have found that the following method works. Define a metaclass with all of the class properties and setters you want. IE, I wanted a class with a title
property with a setter. Here's what I wrote:
class TitleMeta(type):
@property
def title(self):
return getattr(self, '_title', 'Default Title')
@title.setter
def title(self, title):
self._title = title
# Do whatever else you want when the title is set...
Now make the actual class you want as normal, except have it use the metaclass you created above.
# Python 2 style:
class ClassWithTitle(object):
__metaclass__ = TitleMeta
# The rest of your class definition...
# Python 3 style:
class ClassWithTitle(object, metaclass = TitleMeta):
# Your class definition...
It's a bit weird to define this metaclass as we did above if we'll only ever use it on the single class. In that case, if you're using the Python 2 style, you can actually define the metaclass inside the class body. That way it's not defined in the module scope.
from the pandas doc http://pandas.pydata.org/pandas-docs/stable/dsintro.html Series is a one-dimensional labeled array capable of holding any data type. To read data in form of panda Series:
import pandas as pd
ds = pd.Series(data, index=index)
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types.
import pandas as pd
df = pd.DataFrame(data, index=index)
In both of the above index is list
for example: I have a csv file with following data:
,country,popuplation,area,capital
BR,Brazil,10210,12015,Brasile
RU,Russia,1025,457,Moscow
IN,India,10458,457787,New Delhi
To read above data as series and data frame:
import pandas as pd
file_data = pd.read_csv("file_path", index_col=0)
d = pd.Series(file_data.country, index=['BR','RU','IN'] or index = file_data.index)
output:
>>> d
BR Brazil
RU Russia
IN India
df = pd.DataFrame(file_data.area, index=['BR','RU','IN'] or index = file_data.index )
output:
>>> df
area
BR 12015
RU 457
IN 457787
It is also very possible with this error that the field is encrypted in place. Be sure you are looking at the right table, in some cases administrators will create an unencrypted view that you can use instead. I recently encountered a very similar issue.
Add these 2 lines
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
So you have:
// Do any additional setup after loading the view, typically from a nib.
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
layout.itemSize = CGSize(width: screenWidth/3, height: screenWidth/3)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView!.collectionViewLayout = layout
That will remove all the spaces and give you a grid layout:
If you want the first column to have a width equal to the screen width then add the following function:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if indexPath.row == 0
{
return CGSize(width: screenWidth, height: screenWidth/3)
}
return CGSize(width: screenWidth/3, height: screenWidth/3);
}
Grid layout will now look like (I've also added a blue background to first cell):
The default behavior is:
If the parameter is a primitive type (int
, bool
, double
, ...), Web API tries to get the value from the URI of the HTTP request.
For complex types (your own object, for example: Person
), Web API tries to read the value from the body of the HTTP request.
So, if you have:
...then you don't have to add any attributes (neither [FromBody]
nor [FromUri]
).
But, if you have a primitive type in the body, then you have to add [FromBody]
in front of your primitive type parameter in your WebAPI controller method. (Because, by default, WebAPI is looking for primitive types in the URI of the HTTP request.)
Or, if you have a complex type in your URI, then you must add [FromUri]
. (Because, by default, WebAPI is looking for complex types in the body of the HTTP request by default.)
Primitive types:
public class UsersController : ApiController
{
// api/users
public HttpResponseMessage Post([FromBody]int id)
{
}
// api/users/id
public HttpResponseMessage Post(int id)
{
}
}
Complex types:
public class UsersController : ApiController
{
// api/users
public HttpResponseMessage Post(User user)
{
}
// api/users/user
public HttpResponseMessage Post([FromUri]User user)
{
}
}
This works as long as you send only one parameter in your HTTP request. When sending multiple, you need to create a custom model which has all your parameters like this:
public class MyModel
{
public string MyProperty { get; set; }
public string MyProperty2 { get; set; }
}
[Route("search")]
[HttpPost]
public async Task<dynamic> Search([FromBody] MyModel model)
{
// model.MyProperty;
// model.MyProperty2;
}
From Microsoft's documentation for parameter binding in ASP.NET Web API:
When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object). At most one parameter is allowed to read from the message body.
This should work:
public HttpResponseMessage Post([FromBody] string name) { ... }
This will not work:
// Caution: This won't work! public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }
The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.
You can do a distinct count as follows:
SELECT COUNT(DISTINCT column_name) FROM table_name;
EDIT:
Following your clarification and update to the question, I see now that it's quite a different question than we'd originally thought. "DISTINCT" has special meaning in SQL. If I understand correctly, you want something like this:
Now you're probably going to want to use a subquery:
select COUNT(*) column_name FROM (SELECT DISTINCT column_name);
Let me know if this isn't quite what you're looking for.
You could also use Except(produces the set difference of two sequences) to check whether there's a difference or not:
IEnumerable<string> inFirstOnly = a1.Except(a2);
IEnumerable<string> inSecondOnly = a2.Except(a1);
bool allInBoth = !inFirstOnly.Any() && !inSecondOnly.Any();
So this is an efficient way if the order and if the number of duplicates does not matter(as opposed to the accepted answer's SequenceEqual
). Demo: Ideone
If you want to compare in a case insentive way, just add StringComparer.OrdinalIgnoreCase
:
a1.Except(a2, StringComparer.OrdinalIgnoreCase)
You can use jquery
HTML file
<input id="email" name="email">
jquery code
$('#email').bind('copy paste', function (e) {
e.preventDefault();
});
You can use MessageFormat
:
<string name="customer_address">Wellcome: {0} {1}</string>
In Java code :
String text = MessageFormat(R.string.customer_address).format("Name","Family");
API level 1:
https://developer.android.com/reference/java/text/MessageFormat.html
Assuming doc
is your instance of org.w3c.dom.Document
:
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
Put Components which may be patched individually inside their own Fragments
It goes for both making product installers and patches that if you include any component in a fragment, you must include all of the components in that fragment. In the case of building an installer, if you miss any component references, you'll get a linking error from light.exe. However, when you make a patch, if you include a single component reference in a fragment, then all changed components from that fragment will show up in your patch.
like this:
<Fragment>
<DirectoryRef Id="SampleProductFolder">
<Component Id="SampleComponent1" Guid="{C28843DA-EF08-41CC-BA75-D2B99D8A1983}" DiskId="1">
<File Id="SampleFile1" Source=".\$(var.Version)f\Sample1.txt" />
</Component>
</DirectoryRef>
</Fragment>
<Fragment>
<DirectoryRef Id="SampleProductFolder">
<Component Id="SampleComponent2" Guid="{6CEA5599-E7B0-4D65-93AA-0F2F64402B22}" DiskId="1">
<File Id="SampleFile2" Source=".\$(var.Version)f\Sample2.txt" />
</Component>
</DirectoryRef>
</Fragment>
<Fragment>
<DirectoryRef Id="SampleProductFolder">
<Component Id="SampleComponent3" Guid="{4030BAC9-FAB3-426B-8D1E-DC1E2F72C2FC}" DiskId="1">
<File Id="SampleFile3" Source=".\$(var.Version)f\Sample3.txt" />
</Component>
</DirectoryRef>
</Fragment>
instead of this:
<Fragment>
<DirectoryRef Id="SampleProductFolder">
<Component Id="SampleComponent1" Guid="{C28843DA-EF08-41CC-BA75-D2B99D8A1983}" DiskId="1">
<File Id="SampleFile1" Source=".\$(var.Version)\Sample1.txt" />
</Component>
<Component Id="SampleComponent2" Guid="{6CEA5599-E7B0-4D65-93AA-0F2F64402B22}" DiskId="1">
<File Id="SampleFile2" Source=".\$(var.Version)\Sample2.txt" />
</Component>
<Component Id="SampleComponent3" Guid="{4030BAC9-FAB3-426B-8D1E-DC1E2F72C2FC}" DiskId="1">
<File Id="SampleFile3" Source=".\$(var.Version)\Sample3.txt" />
</Component>
</DirectoryRef>
</Fragment>
Also, when patching using the "Using Purely WiX" topic from the WiX.chm help file, using this procedure to generate the patch:
torch.exe -p -xi 1.0\product.wixpdb 1.1\product.wixpdb -out patch\diff.wixmst
candle.exe patch.wxs
light.exe patch.wixobj -out patch\patch.wixmsp
pyro.exe patch\patch.wixmsp -out patch\patch.msp -t RTM patch\diff.wixmst
it's not enough to just have the 1.1 version of the product.wixpdb built using the components in separate fragments. So be sure to correctly fragment your product before shipping.
Most kinds of smart pointers handle disposing of the pointer-to object for you. It's very handy because you don't have to think about disposing of objects manually anymore.
The most commonly-used smart pointers are std::tr1::shared_ptr
(or boost::shared_ptr
), and, less commonly, std::auto_ptr
. I recommend regular use of shared_ptr
.
shared_ptr
is very versatile and deals with a large variety of disposal scenarios, including cases where objects need to be "passed across DLL boundaries" (the common nightmare case if different libc
s are used between your code and the DLLs).
September 2018 (updated February 2019)
It seems that regexp /\p{L}/u
for match letters (as unicode categories)
Here is a working example
In below field you should be able to to type letters but not numbers<br>_x000D_
<input type="text" name="field" onkeydown="return /\p{L}/u.test(event.key)" >
_x000D_
I report this bug here.
After over 2 years according to: 1500035 > 1361876 > 1634135 finally this bug is fixed and will be available in Firefox v.78+
You could also use it clean and simple (but wrong! because you should use format
like Mark Byers said) by doing:
print 'This is my %s formatted with %d arguments' % ('string', 2)
let numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];
let sortFn = (n1 , n2) => number { return n1 - n2; }
const sortedArray: number[] = numericArray.sort(sortFn);
Sort by some field:
let arr:{key:number}[] = [{key : 2}, {key : 3}, {key : 4}, {key : 1}, {key : 5}, {key : 8}, {key : 11}];
let sortFn2 = (obj1 , obj2) => {key:number} { return obj1.key - obj2.key; }
const sortedArray2:{key:number}[] = arr.sort(sortFn2);
yes you can, just set the NODE_PATH env variable :
export NODE_PATH='yourdir'/node_modules
According to the doc :
If the NODE_PATH environment variable is set to a colon-delimited list of absolute paths, then node will search those paths for modules if they are not found elsewhere. (Note: On Windows, NODE_PATH is delimited by semicolons instead of colons.)
Additionally, node will search in the following locations:
1: $HOME/.node_modules
2: $HOME/.node_libraries
3: $PREFIX/lib/node
Where $HOME is the user's home directory, and $PREFIX is node's configured node_prefix.
These are mostly for historic reasons. You are highly encouraged to place your dependencies locally in node_modules folders. They will be loaded faster, and more reliably.
In order to use a CLR 2.0 mixed mode assembly, you need to modify your App.Config file to include:
<?xml version="1.0"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
The key is the useLegacyV2RuntimeActivationPolicy
flag. This causes the CLR to use the latest version (4.0) to load your mixed mode assembly. Without this, it will not work.
Note that this only matters for mixed mode (C++/CLI) assemblies. You can load all managed CLR 2 assemblies without specifying this in app.config
.
You can use Simpsons rule or the Trapezium rule to calculate the area under a graph given a table of y-values at a regular interval.
Python script that calculates Simpsons rule:
def integrate(y_vals, h):
i = 1
total = y_vals[0] + y_vals[-1]
for y in y_vals[1:-1]:
if i % 2 == 0:
total += 2 * y
else:
total += 4 * y
i += 1
return total * (h / 3.0)
h
is the offset (or gap) between y values, and y_vals
is an array of well, y values.
Example (In same file as above function):
y_values = [13, 45.3, 12, 1, 476, 0]
interval = 1.2
area = integrate(y_values, interval)
print("The area is", area)
I ran into the same issue. Most of my projects had the same thing in tools.
"tools": {
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
}
This worked fine on all but one project. I changed the entry in tools to
"tools": {
"Microsoft.EntityFrameworkCore.Tools": {
"version": "1.0.0-preview2-final",
"type": "build"
}
}
And then ran dotnet restore
. After the restore completed, Add-Migration
worked normally.
Why do you need -Xms768 (small heap must be at least 768...)?
That means any java process (search in eclipse) will start with 768m memory allocated, doesn't that? That is why your eclipse isn't able to start properly.
Try -Xms16 -Xmx2048m, for instance.
I have installed Oracle 11g XE on Windows 10 OS. It's installed successfully on my PC but it's showing error which is :
Error:
"windows cannot find 'http //127.0.0.1:%httpport%/apex/f?p4950"
Just follow some steps
In SQL command prompt just type
sql> net start OracleServiceXe after start the Oracle server.
Type SQL> Connect SYS / System as SYSDBA / SYSOPERA
Then type your password which is given by you at the time of installation of Oracle 11g XE. (Press enter).
but You can get login on oracle through this
Note: ( My suggestion to you just type port after http://127.0.0.1:[PortNumber]/apex/f?p=4950 )
http://127.0.0.1:8080/apex/f?p=4950
I got loged in successfully.
Solution is very simple.
1 Add Internet permission in Androidmanifest.xml file
<uses-permission android:name="android.permission.INTERNET" />
[2] Change your httpd.config file
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
TO
Order Deny,Allow
Allow from all
Allow from 127.0.0.1
And restart your server.
[3] And most impotent step. MAKE YOUR NETWORK AS YOUR HOME NETWORK
Go to Control Panel > Network and Internet > Network and Sharing Center
Click on your Network and select HOME NETWORK
iframe have "sandbox" attribute that may block pop up etc
For csh
and tcsh
, you can set verbose
or set echo
(or you can even set both, but it may result in some duplication most of the time).
The verbose
option prints pretty much the exact shell expression that you type.
The echo
option is more indicative of what will be executed through spawning.
http://www.tcsh.org/tcsh.html/Special_shell_variables.html#verbose
http://www.tcsh.org/tcsh.html/Special_shell_variables.html#echo
Special shell variables
verbose
If set, causes the words of each command to be printed, after history substitution (if any). Set by the -v command line option.
echo
If set, each command with its arguments is echoed just before it is executed. For non-builtin commands all expansions occur before echoing. Builtin commands are echoed before command and filename substitution, because these substitutions are then done selectively. Set by the -x command line option.
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
If you're looking for "in-place" editing of a ListView
's contents (specifically the subitems of a ListView in details view mode), you'll need to implement this yourself, or use a third-party control.
By default, the best you can achieve with a "standard" ListView
is to set it's LabelEdit
property to true to allow the user to edit the text of the first column of the ListView
(assuming you want to allow a free-format text edit).
Some examples (including full source-code) of customized ListView
's that allow "in-place" editing of sub-items are:
You can use the JFileChooser class, check this example.
From the git-branch manual page:
git branch --contains <commit>
Only list branches which contain the specified commit (HEAD if not specified). Implies
--list
.
git branch -r --contains <commit>
Lists remote tracking branches as well (as mentioned in user3941992's answer below) that is "local branches that have a direct relationship to a remote branch".
As noted by Carl Walsh, this applies only to the default refspec
fetch = +refs/heads/*:refs/remotes/origin/*
If you need to include other ref namespace (pull request, Gerrit, ...), you need to add that new refspec, and fetch again:
git config --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*"
git fetch
git branch -r --contains <commit>
See also this git ready article.
The
--contains
tag will figure out if a certain commit has been brought in yet into your branch. Perhaps you’ve got a commit SHA from a patch you thought you had applied, or you just want to check if commit for your favorite open source project that reduces memory usage by 75% is in yet.
$ git log -1 tests
commit d590f2ac0635ec0053c4a7377bd929943d475297
Author: Nick Quaranto <[email protected]>
Date: Wed Apr 1 20:38:59 2009 -0400
Green all around, finally.
$ git branch --contains d590f2
tests
* master
Note: if the commit is on a remote tracking branch, add the -a
option.
(as MichielB comments below)
git branch -a --contains <commit>
MatrixFrog comments that it only shows which branches contain that exact commit.
If you want to know which branches contain an "equivalent" commit (i.e. which branches have cherry-picked that commit) that's git cherry
:
Because
git cherry
compares the changeset rather than the commit id (sha1), you can usegit cherry
to find out if a commit you made locally has been applied<upstream>
under a different commit id.
For example, this will happen if you’re feeding patches<upstream>
via email rather than pushing or pulling commits directly.
__*__*__*__*__> <upstream>
/
fork-point
\__+__+__-__+__+__-__+__> <head>
(Here, the commits marked '-
' wouldn't show up with git cherry
, meaning they are already present in <upstream>
.)
In my case, I was linking to a third-party library that was a bit old (developed for iOS 6, on XCode 5 / iOS 7). Therefore, I had to update the third-party library, do a Clean and Build, and it now builds successfully.
If you're in a client-side web environment, the new auth2 javascript API contains a much-needed getBasicProfile()
function, which returns the user's name, email, and image URL.
https://developers.google.com/identity/sign-in/web/reference#googleusergetbasicprofile
I personally do not see any reason why one would like to use char* or char[] except for compatibility with old code. std::string's no slower than using a c-string, except that it will handle re-allocation for you. You can set it's size when you create it, and thus avoid re-allocation if you want. It's indexing operator ([]) provides constant time access (and is in every sense of the word the exact same thing as using a c-string indexer). Using the at method gives you bounds checked safety as well, something you don't get with c-strings, unless you write it. Your compiler will most often optimize out the indexer use in release mode. It is easy to mess around with c-strings; things such as delete vs delete[], exception safety, even how to reallocate a c-string.
And when you have to deal with advanced concepts like having COW strings, and non-COW for MT etc, you will need std::string.
If you are worried about copies, as long as you use references, and const references wherever you can, you will not have any overhead due to copies, and it's the same thing as you would be doing with the c-string.
Adding this into my styles.xml worked for me
<item name="android:textColorPrimary">?android:attr/textColorPrimaryInverse</item>
wait
also (optionally) takes the PID of the process to wait for, and with $! you get the PID of the last command launched in background.
Modify the loop to store the PID of each spawned sub-process into an array, and then loop again waiting on each PID.
# run processes and store pids in array
for i in $n_procs; do
./procs[${i}] &
pids[${i}]=$!
done
# wait for all pids
for pid in ${pids[*]}; do
wait $pid
done
Here is another free API for geolocation requests: http://geoip.nekudo.com
Responses are in JSON format. Additionally the API sourcecode is available on github in case you need to setup your own API.
Once gdb
starts, you can run the program using "r args".
So if you are running your code by:
$ executablefile arg1 arg2 arg3
Debug it on gdb
by:
$ gdb executablefile
(gdb) r arg1 arg2 arg3
You could try:
$h = fopen('filename.txt', 'r+');
fwrite($h, var_export($your_array, true));
The best way to do this would be to use the promise returning function as it is, like this
lookupValue(file).then(function(res) {
// Write the code which depends on the `res.val`, here
});
The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.
So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.
Dim strFirstAddress As String
Dim searchlast As Range
Dim search As Range
Set search = ActiveSheet.Range("A1:A100")
Set searchlast = search.Cells(search.Cells.Count)
Set rngFindValue = ActiveSheet.Range("A1:A100").Find(Text, searchlast, xlValues)
If Not rngFindValue Is Nothing Then
strFirstAddress = rngFindValue.Address
Do
Set rngFindValue = search.FindNext(rngFindValue)
Loop Until rngFindValue.Address = strFirstAddress
Case 1 : Yes, this works fine.
Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.
Share and enjoy.
Resize using helper methods and start-repeat-end handlers like this:
resize(
view1,
1.0f,
0.0f,
1.0f,
0.0f,
0.0f,
0.0f,
150,
null,
null,
null);
return null;
}
Helper methods:
/**
* Resize a view.
*/
public static void resize(
View view,
float fromX,
float toX,
float fromY,
float toY,
float pivotX,
float pivotY,
int duration) {
resize(
view,
fromX,
toX,
fromY,
toY,
pivotX,
pivotY,
duration,
null,
null,
null);
}
/**
* Resize a view with handlers.
*
* @param view A view to resize.
* @param fromX X scale at start.
* @param toX X scale at end.
* @param fromY Y scale at start.
* @param toY Y scale at end.
* @param pivotX Rotate angle at start.
* @param pivotY Rotate angle at end.
* @param duration Animation duration.
* @param start Actions on animation start. Otherwise NULL.
* @param repeat Actions on animation repeat. Otherwise NULL.
* @param end Actions on animation end. Otherwise NULL.
*/
public static void resize(
View view,
float fromX,
float toX,
float fromY,
float toY,
float pivotX,
float pivotY,
int duration,
Callable start,
Callable repeat,
Callable end) {
Animation animation;
animation =
new ScaleAnimation(
fromX,
toX,
fromY,
toY,
Animation.RELATIVE_TO_SELF,
pivotX,
Animation.RELATIVE_TO_SELF,
pivotY);
animation.setDuration(
duration);
animation.setInterpolator(
new AccelerateDecelerateInterpolator());
animation.setFillAfter(true);
view.startAnimation(
animation);
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
if (start != null) {
try {
start.call();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onAnimationEnd(Animation animation) {
if (end != null) {
try {
end.call();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onAnimationRepeat(
Animation animation) {
if (repeat != null) {
try {
repeat.call();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
I recently had a problem in a web application where on an Ajax post-back the datetime coming back to my server-side code was different from the datetime served out.
It most likely had to do with my JavaScript code on the client that built up the date for posting back to the client as string, because JavaScript was adjusting for time zone and daylight savings, and in some browsers the calculation for when to apply daylight savings seemed to be different than in others.
In the end I opted to remove date and time calculations on the client entirely, and posted back to my server on an integer key which then got translated to date time on the server, to allow for consistent transformations.
My learning from this: Do not use JavaScript date and time calculations in web applications unless you ABSOLUTELY have to.
I was having the same problem while running bulk tests for an assignment. Turns out when I relocated some iostream operations (printing to console) from class constructor to a method in class it was solved.
I assume it was something to do with iostream manipulations in the constructor.
Here is the fix:
// Before
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
cout << "Some text I was printing.." << endl;
};
// After
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
};
Please feel free to explain more what the error is behind the scenes since it goes beyond my cpp knowledge.
Have you tried using str.splitlines()
method?:
From the docs:
Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless
keepends
is given and true.
For example:
>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()
['Line 1', '', 'Line 3', 'Line 4']
>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines(True)
['Line 1\n', '\n', 'Line 3\r', 'Line 4\r\n']
This method uses the universal newlines approach to splitting lines.
The main difference between Python 2.X
and Python 3.X
is that the former uses the universal newlines approach to splitting lines, so "\r"
, "\n"
, and "\r\n"
are considered line boundaries for 8-bit strings, while the latter uses a superset of it that also includes:
\v
or \x0b
: Line Tabulation (added in Python 3.2
).\f
or \x0c
: Form Feed (added in Python 3.2
).\x1c
: File Separator.\x1d
: Group Separator.\x1e
: Record Separator.\x85
: Next Line (C1 Control Code).\u2028
: Line Separator.\u2029
: Paragraph Separator.Unlike
str.split()
when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:
>>> ''.splitlines()
[]
>>> 'Line 1\n'.splitlines()
['Line 1']
While str.split('\n')
returns:
>>> ''.split('\n')
['']
>>> 'Line 1\n'.split('\n')
['Line 1', '']
If you also need to remove additional leading or trailing whitespace, like spaces, that are ignored by str.splitlines()
, you could use str.splitlines()
together with str.strip()
:
>>> [str.strip() for str in 'Line 1 \n \nLine 3 \rLine 4 \r\n'.splitlines()]
['Line 1', '', 'Line 3', 'Line 4']
Lastly, if you want to filter out the empty strings from the resulting list, you could use filter()
:
>>> # Python 2.X:
>>> filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines())
['Line 1', 'Line 3', 'Line 4']
>>> # Python 3.X:
>>> list(filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()))
['Line 1', 'Line 3', 'Line 4']
As the error you posted indicates and Burhan suggested, the problem is from the print. There's a related question about that could be useful to you: UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function
I had the same problem with Apache and PHP 5.5.
In php.ini
, I had the following lines:
error_reporting E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT
display_errors Off
instead of the following:
error_reporting=E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT
display_errors=Off
(the =
sign was missing)
Because abstract classes have state (fields) and somethimes they need to be initialized somehow.
pad
In order to move the colorbar relative to the subplot, one may use the pad
argument to fig.colorbar
.
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")
fig.colorbar(im, orientation="horizontal", pad=0.2)
plt.show()
One can use an instance of make_axes_locatable
to divide the axes and create a new axes which is perfectly aligned to the image plot. Again, the pad
argument would allow to set the space between the two axes.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np; np.random.seed(1)
fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")
divider = make_axes_locatable(ax)
cax = divider.new_vertical(size="5%", pad=0.7, pack_start=True)
fig.add_axes(cax)
fig.colorbar(im, cax=cax, orientation="horizontal")
plt.show()
One can directly create two rows of subplots, one for the image and one for the colorbar. Then, setting the height_ratios
as gridspec_kw={"height_ratios":[1, 0.05]}
in the figure creation, makes one of the subplots much smaller in height than the other and this small subplot can host the colorbar.
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
fig, (ax, cax) = plt.subplots(nrows=2,figsize=(4,4),
gridspec_kw={"height_ratios":[1, 0.05]})
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")
fig.colorbar(im, cax=cax, orientation="horizontal")
plt.show()
You could do this
$("#input").blur(function(){
if($(this).val() == ''){
alert('empty');
}
});
http://jsfiddle.net/jasongennaro/Y5P9k/1/
When the input has lost focus
that is .blur()
, then check the value of the #input
.
If it is empty == ''
then trigger the alert.
You need to fix your include_path
system variable to point to the correct location.
To fix it edit the php.ini
file. In that file you will find a line that says, "include_path = ...
". (You can find out what the location of php.ini by running phpinfo()
on a page.) Fix the part of the line that says, "\xampplite\php\pear\PEAR
" to read "C:\xampplite\php\pear
". Make sure to leave the semi-colons before and/or after the line in place.
Restart PHP and you should be good to go. To restart PHP in IIS you can restart the application pool assigned to your site or, better yet, restart IIS all together.
Well, I think something is missing here. User wants to get data from the last year and not from the last 365 days. There is a huge diference. In my opinion, data from the last year is every data from 2007 (if I am in 2008 now). So the right answer would be:
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1
Then if you want to restrict this query, you can add some other filter, but always searching in the last year.
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'
Sorry, you forgot the namespace. You need:
XmlNamespaceManager ns = new XmlNamespaceManager(myXmlDoc.NameTable);
ns.AddNamespace("hl7","urn:hl7-org:v3");
XmlNode idNode = myXmlDoc.SelectSingleNode("/My_RootNode/hl7:id", ns);
In fact, whether here or in web services, getting null back from an XPath operation or anything that depends on XPath usually indicates a problem with XML namespaces.
try this
<c:forEach items="${list}" var="map">
<tr>
<c:forEach items="${map}" var="entry">
<td>${entry.value}</td>
</c:forEach>
</tr>
</c:forEach>
In case you enabled debugging mode
on your phone and adb devices
is not listing your device, it seems there is a problem with phone driver. You might not install the usb-driver of your phone or driver might be installed with problems (in windows check in system --> device manager).
In my case, I had the same problem with My HTC android usb device which installing drivers again, fixed my problems.
Have a look at this list on Wikipedia about which browsers support SVG. It also provides links to more details in the footnotes. Firefox for example supports basic SVG, but at the moment lacks most animation features.
A tutorial about how to create SVG objects using Javascript can be found here:
var svgns = "http://www.w3.org/2000/svg";
var svgDocument = evt.target.ownerDocument;
var shape = svgDocument.createElementNS(svgns, "circle");
shape.setAttributeNS(null, "cx", 25);
shape.setAttributeNS(null, "cy", 25);
shape.setAttributeNS(null, "r", 20);
shape.setAttributeNS(null, "fill", "green");
I think the keystore file you want to use has a different or unsupported format in respect to your Java version. Could you post some more info of your task?
In general, to solve this issue you might need to recreate the whole keystore (using some other JDK version for example). In export-import the keys between the old and the new one - if you manage to open the old one somewhere else.
If it is simply an unsupported version, try the BouncyCastle crypto provider for example (although I'm not sure If it adds support to Java for more keystore types?).
Edit: I looked at the feature spec of BC.
you can define attribute selected="selected" in Ex a
If you don't need the ArrayList<NameValuePair>
for parameters, this is a shorter solution that builds the query string using the Uri.Builder
class:
URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("firstParam", paramValue1)
.appendQueryParameter("secondParam", paramValue2)
.appendQueryParameter("thirdParam", paramValue3);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
you can get it from here https://slproweb.com/products/Win32OpenSSL.html
Supported and reqognized by https://wiki.openssl.org/index.php/Binaries
private List cleanInputs(String[] inputArray) {
List<String> result = new ArrayList<String>(inputArray.length);
for (String input : inputArray) {
if (input != null) {
String str = input.trim();
if (!str.isEmpty()) {
result.add(str);
}
}
}
return result;
}
Make sure your application.properties file is under src/main/resources/application.properties. Is one way to go. Then add @PostConstruct as follows
Sample Application.properties
file.directory = somePlaceOverHere
Sample Java Class
@ComponentScan
public class PrintProperty {
@Value("${file.directory}")
private String fileDirectory;
@PostConstruct
public void print() {
System.out.println(fileDirectory);
}
}
Code above will print out "somePlaceOverhere"
Just remove ()
at the end.
List<string> optionList = new List<string>
{ "AdditionalCardPersonAdressType", /* rest of elements */ };
It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with ""
and your variable will be hidden.
So, you could define the variable with:
{{f = forecast[day.iso]; ""}}
Ensure position
is on your element and set the z-index
to a value higher than the elements you want to cover.
element {
position: fixed;
z-index: 999;
}
div {
position: relative;
z-index: 99;
}
It will probably require some more work than that but it's a start since you didn't post any code.
Please check my working code.
function sendMail()
{
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => '[email protected]', // change it to yours
'smtp_pass' => 'xxx', // change it to yours
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$message = '';
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('[email protected]'); // change it to yours
$this->email->to('[email protected]');// change it to yours
$this->email->subject('Resume from JobsBuddy for your Job posting');
$this->email->message($message);
if($this->email->send())
{
echo 'Email sent.';
}
else
{
show_error($this->email->print_debugger());
}
}
Works for Win7 Enterprise and Win10 Enterprise
@if DEFINED SESSIONNAME (
@echo.
@echo You must right click to "Run as administrator"
@echo Try again
@echo.
@pause
@goto :EOF
)
You can use ReSharper for namespace refactoring. It will give 30 days free trial. It will change namespace as per folder structure.
Steps:
Right click on the project/folder/files you want to refactor.
If you have installed ReSharper then you will get an option Refactor->Adjust Namespaces.... So click on this.
It will automatically change the name spaces of all the selected files.
str.append(10u,'d'); //appends character d 10 times
Notice I have written 10u and not 10 for the number of times I'd like to append the character; replace 10 with whatever number.
A simple method of creating the service, adding headers and reading the JSON response,
private static void WebRequest()
{
const string WEBSERVICE_URL = "<<Web service URL>>";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "GET";
webRequest.Timeout = 12000;
webRequest.ContentType = "application/json";
webRequest.Headers.Add("Authorization", "Basic dchZ2VudDM6cGFdGVzC5zc3dvmQ=");
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
Console.WriteLine(String.Format("Response: {0}", jsonResponse));
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Here is another example showing the use of gather
from tidyr
. You can select the columns to gather
either by removing them individually (as I do here), or by including the years you want explicitly.
Note that, to handle the commas (and X's added if check.names = FALSE
is not set), I am also using dplyr
's mutate with parse_number
from readr
to convert the text values back to numbers. These are all part of the tidyverse
and so can be loaded together with library(tidyverse)
wide %>%
gather(Year, Value, -Code, -Country) %>%
mutate(Year = parse_number(Year)
, Value = parse_number(Value))
Returns:
Code Country Year Value
1 AFG Afghanistan 1950 20249
2 ALB Albania 1950 8097
3 AFG Afghanistan 1951 21352
4 ALB Albania 1951 8986
5 AFG Afghanistan 1952 22532
6 ALB Albania 1952 10058
7 AFG Afghanistan 1953 23557
8 ALB Albania 1953 11123
9 AFG Afghanistan 1954 24555
10 ALB Albania 1954 12246
You can do all that by using just one RelativeLayout
(which, btw, don't need android:orientation
parameter). So, instead of having a LinearLayout
, containing a bunch of stuff, you can do something like:
<RelativeLayout>
<ImageButton
android:layout_width="wrap_content"
android:id="@+id/the_first_one"
android:layout_alignParentLeft="true"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_toRightOf="@+id/the_first_one"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_alignParentRight="true"/>
</RelativeLayout>
As you noticed, there are some XML parameters missing. I was just showing the basic parameters you had to put. You can complete the rest.
A Bin file is a pure binary file with no memory fix-ups or relocations, more than likely it has explicit instructions to be loaded at a specific memory address. Whereas....
ELF files are Executable Linkable Format which consists of a symbol look-ups and relocatable table, that is, it can be loaded at any memory address by the kernel and automatically, all symbols used, are adjusted to the offset from that memory address where it was loaded into. Usually ELF files have a number of sections, such as 'data', 'text', 'bss', to name but a few...it is within those sections where the run-time can calculate where to adjust the symbol's memory references dynamically at run-time.
FWIW, htpasswd -n username
will output the result directly to stdout, and avoid touching files altogether.
Process.Start("explorer.exe" , @"C:\Users");
I had to use this, the other way of just specifying the tgt dir would shut the explorer window when my application terminated.
Casting in Java isn't magic, it's you telling the compiler that an Object of type A is actually of more specific type B, and thus gaining access to all the methods on B that you wouldn't have had otherwise. You're not performing any kind of magic or conversion when performing casting, you're essentially telling the compiler "trust me, I know what I'm doing and I can guarantee you that this Object at this line is actually an <Insert cast type here>." For example:
Object o = "str";
String str = (String)o;
The above is fine, not magic and all well. The object being stored in o is actually a string, and therefore we can cast to a string without any problems.
There's two ways this could go wrong. Firstly, if you're casting between two types in completely different inheritance hierarchies then the compiler will know you're being silly and stop you:
String o = "str";
Integer str = (Integer)o; //Compilation fails here
Secondly, if they're in the same hierarchy but still an invalid cast then a ClassCastException
will be thrown at runtime:
Number o = new Integer(5);
Double n = (Double)o; //ClassCastException thrown here
This essentially means that you've violated the compiler's trust. You've told it you can guarantee the object is of a particular type, and it's not.
Why do you need casting? Well, to start with you only need it when going from a more general type to a more specific type. For instance, Integer
inherits from Number
, so if you want to store an Integer
as a Number
then that's ok (since all Integers are Numbers.) However, if you want to go the other way round you need a cast - not all Numbers are Integers (as well as Integer we have Double
, Float
, Byte
, Long
, etc.) And even if there's just one subclass in your project or the JDK, someone could easily create another and distribute that, so you've no guarantee even if you think it's a single, obvious choice!
Regarding use for casting, you still see the need for it in some libraries. Pre Java-5 it was used heavily in collections and various other classes, since all collections worked on adding objects and then casting the result that you got back out the collection. However, with the advent of generics much of the use for casting has gone away - it has been replaced by generics which provide a much safer alternative, without the potential for ClassCastExceptions (in fact if you use generics cleanly and it compiles with no warnings, you have a guarantee that you'll never get a ClassCastException.)
I prefer a mutex solution similar to the following. As this way it re-focuses on the app if it is already loaded
using System.Threading;
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
bool createdNew = true;
using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
{
if (createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
else
{
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
SetForegroundWindow(process.MainWindowHandle);
break;
}
}
}
}
}
Might take a look at the XSD tool in visual studio 2k8... I have created a relational dataset from an xsd and it might help your out somehow.
Inner join: Only show rows, when has it data from both of the tables.
Outer join: (left/right): Show the all result from the left / right table with the paired row(s), if it exists or not.
Object assign copies one or more source objects to the target object. So we could use Object.assign
here.
Syntax: Object.assign(target, ...sources)
var obj = {};_x000D_
_x000D_
Object.assign(obj, {"1":"aa", "2":"bb"})_x000D_
_x000D_
console.log(obj)
_x000D_
IOS 11.2 Swift 3.1- 4
let webView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "https://www.google.com") else { return }
webView.frame = view.bounds
webView.navigationDelegate = self
webView.load(URLRequest(url: url))
webView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
view.addSubview(webView)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .linkActivated {
if let url = navigationAction.request.url,
let host = url.host, !host.hasPrefix("www.google.com"),
UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
print(url)
print("Redirected to browser. No need to open it locally")
decisionHandler(.cancel)
} else {
print("Open it locally")
decisionHandler(.allow)
}
} else {
print("not a user click")
decisionHandler(.allow)
}
}
You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.
For Finding All the ChildNodes you can use the below Snippet
List<WebElement> childs = MyCurrentWebElement.findElements(By.xpath("./child::*"));
for (WebElement e : childs)
{
System.out.println(e.getTagName());
}
Note that this will give all the Child Nodes at same level -> Like if you have structure like this :
<Html>
<body>
<div> ---suppose this is current WebElement
<a>
<a>
<img>
<a>
<img>
<a>
It will give me tag names of 3 anchor tags here only . If you want all the child Elements recursively , you can replace the above code with MyCurrentWebElement.findElements(By.xpath(".//*"));
Hope That Helps !!
I use superagent
, which is simliar to jQuery.
Here is the docs
And the demo like:
var sa = require('superagent');
sa.post('url')
.send({key: value})
.end(function(err, res) {
//TODO
});
(this answer was added to provide shorter and more generic examples to the question - without including all the case-specific details in the original question).
There are two distinct "problems" here, the first is if a table or subquery has no rows, the second is if there are NULL values in the query.
For all versions I've tested, postgres and mysql will ignore all NULL values when averaging, and it will return NULL if there is nothing to average over. This generally makes sense, as NULL is to be considered "unknown". If you want to override this you can use coalesce (as suggested by Luc M).
$ create table foo (bar int);
CREATE TABLE
$ select avg(bar) from foo;
avg
-----
(1 row)
$ select coalesce(avg(bar), 0) from foo;
coalesce
----------
0
(1 row)
$ insert into foo values (3);
INSERT 0 1
$ insert into foo values (9);
INSERT 0 1
$ insert into foo values (NULL);
INSERT 0 1
$ select coalesce(avg(bar), 0) from foo;
coalesce
--------------------
6.0000000000000000
(1 row)
of course, "from foo" can be replaced by "from (... any complicated logic here ...) as foo"
Now, should the NULL row in the table be counted as 0? Then coalesce has to be used inside the avg call.
$ select coalesce(avg(coalesce(bar, 0)), 0) from foo;
coalesce
--------------------
4.0000000000000000
(1 row)
Yes, there are 33 (mostly repetitive) answers already to this question.
Here is another approach to how to comment lines out in Vim: motions. The basic idea is to comment or uncomment lines out using the same method as yanking a paragraph by typing yip
or deleting 2 lines by typing dj
.
This approach will let you do things like:
ccj
to comment the next 2 lines out, and cuk
to uncomment them;
cci{
to comment a block out, and cui{
to uncomment it;
ccip
to comment a whole paragraph out, and cuip
to uncomment it.
ccG
to comment everything out down to the last line, and cugg
to uncomment everything up to the first line.
All you need are 2 functions that operate over motions, and 2 mappings for each function. First, the mappings:
nnoremap <silent> cc :set opfunc=CommentOut<cr>g@
vnoremap <silent> cc :<c-u>call CommentOut(visualmode(), 1)<cr>
nnoremap <silent> cu :set opfunc=Uncomment<cr>g@
vnoremap <silent> cu :<c-u>call Uncomment(visualmode(), 1)<cr>
(See the manual about the g@
operator and the operatorfunc
variable.)
And now the functions:
function! CommentOut(type, ...)
if a:0
silent exe "normal! :'<,'>s/^/#/\<cr>`<"
else
silent exe "normal! :'[,']s/^/#/\<cr>'["
endif
endfunction
function! Uncomment(type, ...)
if a:0
silent exe "normal! :'<,'>s/^\\(\\s*\\)#/\\1/\<cr>`<"
else
silent exe "normal! :'[,']s/^\\(\\s*\\)#/\\1/\<cr>`["
endif
endfunction
Modify the regular expressions above to suit your taste as to where the #
should be:
After running around in the Preferences dialog, the following is the location at which the highlight color for "occurrences" can be changed:
General -> Editors -> Text Editors -> Annotations
Look for Occurences
from the Annotation types list.
Then, be sure that Text as highlighted
is selected, then choose the desired color.
And, a picture is worth a thousand words...
(source: coobird.net)
(source: coobird.net)
Another option is to ensure that the full qualified host name (FQDN) is listed in /etc/hosts. This worked for me on Ubuntu v11.10 without having to change the default Apache configuration.
public static void replaceFileString(String old, String new) throws IOException {
String fileName = Settings.getValue("fileDirectory");
FileInputStream fis = new FileInputStream(fileName);
String content = IOUtils.toString(fis, Charset.defaultCharset());
content = content.replaceAll(old, new);
FileOutputStream fos = new FileOutputStream(fileName);
IOUtils.write(content, new FileOutputStream(fileName), Charset.defaultCharset());
fis.close();
fos.close();
}
above is my implementation of Meriton's example that works for me. The fileName is the directory (ie. D:\utilities\settings.txt). I'm not sure what character set should be used, but I ran this code on a Windows XP machine just now and it did the trick without doing that temporary file creation and renaming stuff.
Agile is mostly used technique in project development.In agile technology peoples are switches from one technology to other ..Main purpose is to remove dependancy. Like Peoples shifted from production to development,and development to testing. Thats why dependancy will remove on a single team or person..
Create a vectorized method
def calc_xb_minus_xa(df):
time_dict = {
'<Minute>': 'm',
'<Hour>': 'h',
'<Day>': 'D',
'<Week>': 'W',
'<Month>': 'M',
'<Year>': 'Y'
}
time_delta = df.at[df.index[0], 'end_time'] - df.at[df.index[0], 'open_time']
offset_base_name = str(to_offset(time_delta).base)
time_term = time_dict.get(offset_base_name)
result = (df.end_time - df.open_time) / np.timedelta64(1, time_term)
return result
Then in your df do:
df['x'] = calc_xb_minus_xa(df)
This will work for minutes, hours, days, weeks, month and Year. open_time and end_time need to change according your df
There's a couple of ways you can do this. If the onchange
listener is a function set via the element.onchange
property and you're not bothered about the event object or bubbling/propagation, the easiest method is to just call that function:
element.onchange();
If you need it to simulate the real event in full, or if you set the event via the html attribute or addEventListener
/attachEvent
, you need to do a bit of feature detection to correctly fire the event:
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);
}
else
element.fireEvent("onchange");
While Parallels is technically a VM it is capable of running games in high resolution at a high frame rate. If you run Parallels in Coherence mode it completely integrates Windows 7 into OS X and .Net framework is fully supported. So yes you can install Visual Studio on your Mac however the Apps you created would only run of windows computers unless they were web based.
When you extend FragmentActivity
or Activity
and not ListActivity
, you'll want to take a look at:
In bootstrap 4, you can use 'w-100' class (w as width, and 100 as 100%)
You can find documentation here: https://getbootstrap.com/docs/4.0/utilities/sizing/
On a side note, in PowerShell 3.0 you can use the Get-Content
cmdlet with the new Raw switch:
$text = Get-Content .\file.txt -Raw
You can use a regular expression: window.location.href.match(/^[^\#\?]+/)[0]
As @Sean said, fcntl()
is largely standardized, and therefore available across platforms. The ioctl()
function predates fcntl()
in Unix, but is not standardized at all. That the ioctl()
worked for you across all the platforms of relevance to you is fortunate, but not guaranteed. In particular, the names used for the second argument are arcane and not reliable across platforms. Indeed, they are often unique to the particular device driver that the file descriptor references. (The ioctl()
calls used for a bit-mapped graphics device running on an ICL Perq running PNX (Perq Unix) of twenty years ago never translated to anything else anywhere else, for example.)
I got the same error when an imported library was trying to create a directory at path "./logs/".
It turns out that the library was trying to create it at the wrong location, i.e. inside the folder of my python interpreter instead of the base project directory. I solved the issue by setting the "Working directory" path to my project folder inside the "Run Configurations" menu of PyCharm. If instead you're using the terminal to run your code, maybe you just need to move inside the project folder before running it.
I had same issue. And I fix it with creating an app-password for Email application on Mac. You can find it at my account -> Security -> Signing in to Google -> App passwords. below is the link for it. https://myaccount.google.com/apppasswords?utm_source=google-account&utm_medium=web
It is very simple. You can use
.fill .map
{
min-height: 100vh;
}
You can change height according to your requirement.
I know this is an old thread but for anyone looking to retrieve a script after ssms crashes do the following
You can just give the glyphicon a font-size to your liking:
span.glyphicon-link {
font-size: 1.2em;
}
It's more convenient to use a session, this way you don't have to remember to set headers each time:
session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})
session.get('https://httpbin.org/headers')
By default, session also manages cookies for you. In case you want to disable that, see this question.
The combination of find
and ls
works well for
The solution:
find . -name "my-pattern" -print0 |
xargs -r -0 ls -1 -t |
head -1
Let's break it down:
With find
we can match all interesting files like this:
find . -name "my-pattern" ...
then using -print0
we can pass all filenames safely to the ls
like this:
find . -name "my-pattern" -print0 | xargs -r -0 ls -1 -t
additional find
search parameters and patterns can be added here
find . -name "my-pattern" ... -print0 | xargs -r -0 ls -1 -t
ls -t
will sort files by modification time (newest first) and print it one at a line. You can use -c
to sort by creation time. Note: this will break with filenames containing newlines.
Finally head -1
gets us the first file in the sorted list.
Note: xargs
use system limits to the size of the argument list. If this size exceeds, xargs
will call ls
multiple times. This will break the sorting and probably also the final output. Run
xargs --show-limits
to check the limits on you system.
Note 2: use find . -maxdepth 1 -name "my-pattern" -print0
if you don't want to search files through subfolders.
Note 3: As pointed out by @starfry - -r
argument for xargs
is preventing the call of ls -1 -t
, if no files were matched by the find
. Thank you for the suggesion.
You don't need to use
adb shell getevent -l
command, you just need to enable in Developer Options on the device [Show Touch data] to get X and Y.
Some more information can be found in my article here: https://mobileqablog.wordpress.com/2016/08/20/android-automatic-touchscreen-taps-adb-shell-input-touchscreen-tap/
No, Python does not support labels and goto, if that is what you're after. It's a (highly) structured programming language.
Going back to a really basic idea, we have 32 bits for our memory addresses. That works out to 2^32 unique combinations of addresses. By convention, each address points to 1 byte of data. Therefore, we can access up to a total 2^32 bytes of data.
In a 32 bit OS, each register stores 32 bits or 4 bytes. 32 bits (1 word) of information are processed per clock cycle. If you want to access a particular 1 byte, conceptually, we can "extract" the individual bytes (e.g. byte 0, byte 1, byte 2, byte 3 etc.) by doing bitwise logical operations.
E.g. to get "dddddddd", take "aaaaaaaabbbbbbbbccccccccdddddddd" and logical AND with "00000000000000000000000011111111".
For entity Framework Core 2.0 or above, the correct way to do this is:
var firstName = "John";
var id = 12;
ctx.Database.ExecuteSqlCommand($"Update [User] SET FirstName = {firstName} WHERE Id = {id}";
Note that Entity Framework will produce the two parameters for you, so you are protected from Sql Injection.
Also note that it is NOT:
var firstName = "John";
var id = 12;
var sql = $"Update [User] SET FirstName = {firstName} WHERE Id = {id}";
ctx.Database.ExecuteSqlCommand(sql);
because this does NOT protect you from Sql Injection, and no parameters are produced.
See this for more.
This solved my problem: Kotlin Code:
val fragmentTransaction = activity.supportFragmentManager.beginTransaction()
fragmentTransaction.add(dialogFragment, tag)
fragmentTransaction.commitAllowingStateLoss()
How is commitAllowingStateLoss()
is different than commit()
?
As per documentation:
Like commit()
but allows the commit to be executed after an activity's state is saved.
https://developer.android.com/reference/android/app/FragmentTransaction#commitAllowingStateLoss()
P.S: you can show Fragment Dialogs or can load fragments by this method. Applicable for both.
Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.
Here is a quick example using LocalDate from the Joda Time library:
LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();
Here you can follow a quick start tutorial.
There could be many reasons for Index not being used. Even after you specify hints, there are chances Oracle optimizer thinks otherwise and decide not to use Index. You need to go through the EXPLAIN PLAN part and see what is the cost of the statement with INDEX and without INDEX.
Assuming the Oracle uses CBO. Most often, if the optimizer thinks the cost is high with INDEX, even though you specify it in hints, the optimizer will ignore and continue for full table scan. Your first action should be checking DBA_INDEXES to know when the statistics are LAST_ANALYZED. If not analyzed, you can set table, index for analyze.
begin
DBMS_STATS.GATHER_INDEX_STATS ( OWNNAME=>user
, INDNAME=>IndexName);
end;
For table.
begin
DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME=>user
, TABNAME=>TableName);
end;
In extreme cases, you can try setting up the statistics on your own.
I agree that using the global/GLOBAL namespace for setting anything global is bad practice and don't use it at all in theory (in theory being the operative word). However (yes, the operative) I do use it for setting custom Error classes:
// Some global/configuration file that gets called in initialisation
global.MyError = [Function of MyError];
Yes, it is taboo here, but if your site/project uses custom errors throughout the place, you would basically need to define it everywhere, or at least somewhere to:
Defining my custom errors in the global namespace saves me the hassle of require'ing my customer error library. Imaging throwing a custom error where that custom error is undefined.
I think what the OP is looking for is:
with open('temp.json', 'w') as f:
f.write(df.to_json(orient='records', lines=True))
This should do the trick.
Your connection URL should look like the below,
jdbc:mysql://localhost:3306/Peoples?autoReconnect=true&useSSL=false
This will disable SSL and also suppress the SSL errors.
In java 8 you can use java.time.LocalDate
LocalDate parsedDate = LocalDate.parse("2015-10-30"); //Parse date from String
LocalDate addedDate = parsedDate.plusDays(1); //Add one to the day field
You can convert in into java.util.Date
object as follows.
Date date = Date.from(addedDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
You can formate LocalDate
into a String as follows.
String str = addedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
Use the following code for getting lat and long using php. Here are two methods:
<?php
// Get lat and long by address
$address = $dlocation; // Google HQ
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$latitude = $output->results[0]->geometry->location->lat;
$longitude = $output->results[0]->geometry->location->lng;
?>
edit - Google Maps requests must be over https
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(50.804400, -1.147250);
var mapOptions = {
zoom: 6,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas12'), mapOptions);
}
function codeAddress(address,tutorname,url,distance,prise,postcode) {
var address = address;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var infowindow = new google.maps.InfoWindow({
content: 'Tutor Name: '+tutorname+'<br>Price Guide: '+prise+'<br>Distance: '+distance+' Miles from you('+postcode+')<br> <a href="'+url+'" target="blank">View Tutor profile</a> '
});
infowindow.open(map,marker);
} /*else {
alert('Geocode was not successful for the following reason: ' + status);
}*/
});
}
google.maps.event.addDomListener(window, 'load', initialize);
window.onload = function(){
initialize();
// your code here
<?php foreach($addr as $add) {
?>
codeAddress('<?php echo $add['address']; ?>','<?php echo $add['tutorname']; ?>','<?php echo $add['url']; ?>','<?php echo $add['distance']; ?>','<?php echo $add['prise']; ?>','<?php echo substr( $postcode1,0,4); ?>');
<?php } ?>
};
</script>
<div id="map-canvas12"></div>
I have figured out how this is done for Sony devices.
I've blogged about it here. I've also posted a seperate SO question about this here.
Sony devices use a class named BadgeReciever
.
Declare the com.sonyericsson.home.permission.BROADCAST_BADGE
permission in your manifest file:
Broadcast an Intent
to the BadgeReceiver
:
Intent intent = new Intent();
intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", "com.yourdomain.yourapp.MainActivity");
intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", true);
intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", "99");
intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", "com.yourdomain.yourapp");
sendBroadcast(intent);
Done. Once this Intent
is broadcast the launcher should show a badge on your application icon.
To remove the badge again, simply send a new broadcast, this time with SHOW_MESSAGE
set to false:
intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", false);
I've excluded details on how I found this to keep the answer short, but it's all available in the blog. Might be an interesting read for someone.
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
Do it the other way around:
$a = "1,435";
$b = str_replace( ',', '', $a );
if( is_numeric( $b ) ) {
$a = $b;
}
The easiest would be:
$var = intval(preg_replace('/[^\d.]/', '', $var));
or if you need float:
$var = floatval(preg_replace('/[^\d.]/', '', $var));
One think you should change is the call $state.go()
. As described here:
The param passed should be the state name
$scope.create = function() {
// instead of this
//$state.go("/tab/newpost");
// we should use this
$state.go("tab.newpost");
};
Some cite from doc (the first parameter to of the [$state.go(to \[, toParams\] \[, options\]
):
String Absolute State Name or Relative State Path
The name of the state that will be transitioned to or a relative state path. If the path starts with ^ or . then it is relative, otherwise it is absolute.
Some examples:
$state.go('contact.detail') will go to the 'contact.detail' state
$state.go('^') will go to a parent state.
$state.go('^.sibling') will go to a sibling state.
$state.go('.child.grandchild') will go to a grandchild state.
No, you cannot do that. That's just the way Python has its syntax. Once you exit a try-block because of an exception, there is no way back in.
What about a for-loop though?
funcs = do_smth1, do_smth2
for func in funcs:
try:
func()
except Exception:
pass # or you could use 'continue'
Note however that it is considered a bad practice to have a bare except
. You should catch for a specific exception instead. I captured for Exception
because that's as good as I can do without knowing what exceptions the methods might throw.
I solved my problem doing the following:
First of all, I am a windows user, but i have faced similar issue. So, I am posting my solution here.
There is one simple reason why sometimes the .gitignore doesn`t work like it is supposed to. It is due to the EOL conversion behavior.
Here is a quick fix for that
Edit > EOL Conversion > Windows Format > Save
You can blame your text editor settings for that.
For example:
As i am a windows developer, I typically use Notepad++ for editing my text unlike Vim users.
So what happens is, when i open my .gitignore file using Notepad++, it looks something like this:
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# See https://help.github.com/ignore-files/ for more about ignoring files.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
*.dll
*.force
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
If i open the same file using the default Notepad, this is what i get
## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # See https://help.github.com/ignore-files/ for more about ignoring files. # User-specific files *.suo *.user *.userosscache
So, you might have already guessed by looking at the output. Everything in the .gitignore has become a one liner, and since there is a ## in the start, it acts as if everything is commented.
The way to fix this is simple: Just open your .gitignore file with Notepad++ , then do the following
Edit > EOL Conversion > Windows Format > Save
The next time you open the same file with the windows default notepad, everything should be properly formatted. Try it and see if this works for you.
You can use import nbimporter
then import notebookName
To disable certain items:
MenuItem item = menu.findItem(R.id.ID_ASSING_TO_THE_ITEM_IN_MENU_XML);
item.setEnabled(false);
thanks, try this instead
Select
STR(account_code) as account_code_Numeric,
descr
from account
where STR(account_code) = 1
I'm happy to help you
If you have a valid dtd file for the xml then you can easily transform json to xml and xml to json using the eclipselink jar binary.
Refer this: http://www.cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html
The article also has a sample project (including the supporting third party jars) as a zip file which can be downloaded for reference purpose.
Use defaultdict instead:
from collections import defaultdict
data = defaultdict(list)
data[1].append('hello')
This way you don't have to initialize all the keys you want to use to lists beforehand.
What is happening in your example is that you use one (mutable) list:
alist = [1]
data = dict.fromkeys(range(2), alist)
alist.append(2)
print data
would output {0: [1, 2], 1: [1, 2]}
.
I gathered all what others have suggested and created following function which has 3 arguments, the number and the base which that number has come from and the base which that number is going to be on:
changeBase(1101000, 2, 10) => 104
Run Code Snippet to try it yourself:
function changeBase(number, fromBase, toBase) {_x000D_
if (fromBase == 10)_x000D_
return (parseInt(number)).toString(toBase)_x000D_
else if (toBase == 10)_x000D_
return parseInt(number, fromBase);_x000D_
else{_x000D_
var numberInDecimal = parseInt(number, fromBase);_x000D_
return (parseInt(numberInDecimal)).toString(toBase);_x000D_
}_x000D_
}_x000D_
_x000D_
$("#btnConvert").click(function(){_x000D_
var number = $("#txtNumber").val(),_x000D_
fromBase = $("#txtFromBase").val(),_x000D_
toBase = $("#txtToBase").val();_x000D_
$("#lblResult").text(changeBase(number, fromBase, toBase));_x000D_
});
_x000D_
#lblResult{_x000D_
padding: 20px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="txtNumber" type="text" placeholder="Number" />_x000D_
<input id="txtFromBase" type="text" placeholder="From Base" />_x000D_
<input id="txtToBase" type="text" placeholder="To Base" />_x000D_
<input id="btnConvert" type="button" value="Convert" />_x000D_
<span id="lblResult"></span>_x000D_
_x000D_
<p>Hint: <br />_x000D_
Try 110, 2, 10 and it will return 6; (110)<sub>2</sub> = 6<br />_x000D_
_x000D_
or 2d, 16, 10 => 45 meaning: (2d)<sub>16</sub> = 45<br />_x000D_
or 45, 10, 16 => 2d meaning: 45 = (2d)<sub>16</sub><br />_x000D_
or 2d, 2, 16 => 2d meaning: (101101)<sub>2</sub> = (2d)<sub>16</sub><br />_x000D_
</p>
_x000D_
FYI: If you want to pass 2d as hex number, you need to send it as a string so it goes like this:
changeBase('2d', 16, 10)
Import namespace :
using System.Configuration;
Create ConfigurationElement Company :
public class Company : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return this["name"] as string;
}
}
[ConfigurationProperty("code", IsRequired = true)]
public string Code
{
get
{
return this["code"] as string;
}
}
}
ConfigurationElementCollection:
public class Companies
: ConfigurationElementCollection
{
public Company this[int index]
{
get
{
return base.BaseGet(index) as Company ;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
public new Company this[string responseString]
{
get { return (Company) BaseGet(responseString); }
set
{
if(BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new Company();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{
return ((Company)element).Name;
}
}
and ConfigurationSection:
public class RegisterCompaniesConfig
: ConfigurationSection
{
public static RegisterCompaniesConfig GetConfig()
{
return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
}
[System.Configuration.ConfigurationProperty("Companies")]
[ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
public Companies Companies
{
get
{
object o = this["Companies"];
return o as Companies ;
}
}
}
and you must also register your new configuration section in web.config (app.config):
<configuration>
<configSections>
<section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>
then you load your config with
var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
do something ..
}
You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.
SELECT * FROM <table_name> WHERE id = 1
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';
If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':
hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')
1) Direct Answer: Try this:
sudo updatedb
locate OpenCVConfig.cmake
For me, I get:
/home/pkarasev3/source/opencv/build/OpenCVConfig.cmake
To see the version, you can try:
cat /home/pkarasev3/source/opencv/build/OpenCVConfig.cmake
giving
....
SET(OpenCV_VERSION 2.3.1)
....
2) Better Answer:
"sudo make install" is your enemy, don't do that when you need to compile/update the library often and possibly debug step through it's internal functions. Notice how my config file is in a local build directory, not in /usr/something. You will avoid this confusion in the future, and can maintain several different versions even (debug and release, for example).
Edit: the reason this questions seems to arise often for OpenCV as opposed to other libraries is that it changes rather dramatically and fast between versions, and many of the operations are not so well-defined / well-constrained so you can't just rely on it to be a black-box like you do for something like libpng or libjpeg. Thus, better to not install it at all really, but just compile and link to the build folder.
@IBAction func back(_ sender: Any) {
self.dismiss(animated: false, completion: nil)
}
I faced this issue in my code. I only put this code in my app.module.ts.
import { HttpModule } from '@angular/http';
@NgModule({
imports: [ BrowserModule, HttpModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
If you need to call plot multiply times, you can also use the "label" argument:
ax = df1.plot(label='df1', y='y_var')
ax = df2.plot(label='df2', y='y_var')
While this is not the case in the OP question, this can be helpful if the DataFrame
is in long format and you use groupby
before plotting.
The main idea is
Stash the changes in a dirty working directory away
So Basicallly Stash command keep your some changes that you don't need them or want them at the moment; but you may need them.
Use git stash when you want to record the current state of the working directory and the index, but want to go back to a clean working directory. The command saves your local modifications away and reverts the working directory to match the HEAD commit.
I had the error when using gpg-agent as my ssh-agent and using a gpg subkey as my ssh key https://wiki.archlinux.org/index.php/GnuPG#gpg-agent.
I suspect that the problem was caused by having an invalid pin entry tty for gpg caused by my sleep+lock command used in my sway config
bindsym $mod+Shift+l exec "sh -c 'gpg-connect-agent reloadagent /bye>/dev/null; systemctl suspend; swaylock'"
or just the sleep/suspend
Reset the pin entry tty to fix the problem
gpg-connect-agent updatestartuptty /bye > /dev/null
and the fix for my sway sleep+lock command:
bindsym $mod+Shift+l exec "sh -c 'gpg-connect-agent reloadagent /bye>/dev/null; systemctl suspend; swaylock; gpg-connect-agent updatestartuptty /bye > /dev/null'"
Just add header('Content-type: application/xml');
before your echo of the XML response and you will see an XML page.
This is an improvement to a previous answer. It adds support for values with varying lengths and rows with a varying number of cells. For example:
+------------------------------------------------------------------------------+
¦Identifier¦ Type¦ Description¦ CPU Credit Use¦Hours¦Balance¦
+----------+---------+--------------------------+----------------+-----+-------+
¦ i-1234154¦ t2.small¦ This is an example.¦ 3263.75¦ 360¦
+----------+---------+--------------------------+----------------+-----+
¦ i-1231412¦ t2.small¦ This is another example.¦ 3089.93¦
+----------------------------------------------------------------+
Here is the code:
public class ArrayPrinter
{
const string TOP_LEFT_JOINT = "+";
const string TOP_RIGHT_JOINT = "+";
const string BOTTOM_LEFT_JOINT = "+";
const string BOTTOM_RIGHT_JOINT = "+";
const string TOP_JOINT = "-";
const string BOTTOM_JOINT = "-";
const string LEFT_JOINT = "+";
const string JOINT = "+";
const string RIGHT_JOINT = "¦";
const char HORIZONTAL_LINE = '-';
const char PADDING = ' ';
const string VERTICAL_LINE = "¦";
private static int[] GetMaxCellWidths(List<string[]> table)
{
int maximumCells = 0;
foreach (Array row in table)
{
if (row.Length > maximumCells)
maximumCells = row.Length;
}
int[] maximumCellWidths = new int[maximumCells];
for (int i = 0; i < maximumCellWidths.Length; i++)
maximumCellWidths[i] = 0;
foreach (Array row in table)
{
for (int i = 0; i < row.Length; i++)
{
if (row.GetValue(i).ToString().Length > maximumCellWidths[i])
maximumCellWidths[i] = row.GetValue(i).ToString().Length;
}
}
return maximumCellWidths;
}
public static string GetDataInTableFormat(List<string[]> table)
{
StringBuilder formattedTable = new StringBuilder();
Array nextRow = table.FirstOrDefault();
Array previousRow = table.FirstOrDefault();
if (table == null || nextRow == null)
return String.Empty;
// FIRST LINE:
int[] maximumCellWidths = GetMaxCellWidths(table);
for (int i = 0; i < nextRow.Length; i++)
{
if (i == 0 && i == nextRow.Length - 1)
formattedTable.Append(String.Format("{0}{1}{2}", TOP_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
else if (i == 0)
formattedTable.Append(String.Format("{0}{1}", TOP_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
else if (i == nextRow.Length - 1)
formattedTable.AppendLine(String.Format("{0}{1}{2}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
else
formattedTable.Append(String.Format("{0}{1}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
}
int rowIndex = 0;
int lastRowIndex = table.Count - 1;
foreach (Array thisRow in table)
{
// LINE WITH VALUES:
int cellIndex = 0;
int lastCellIndex = thisRow.Length - 1;
foreach (object thisCell in thisRow)
{
string thisValue = thisCell.ToString().PadLeft(maximumCellWidths[cellIndex], PADDING);
if (cellIndex == 0 && cellIndex == lastCellIndex)
formattedTable.AppendLine(String.Format("{0}{1}{2}", VERTICAL_LINE, thisValue, VERTICAL_LINE));
else if (cellIndex == 0)
formattedTable.Append(String.Format("{0}{1}", VERTICAL_LINE, thisValue));
else if (cellIndex == lastCellIndex)
formattedTable.AppendLine(String.Format("{0}{1}{2}", VERTICAL_LINE, thisValue, VERTICAL_LINE));
else
formattedTable.Append(String.Format("{0}{1}", VERTICAL_LINE, thisValue));
cellIndex++;
}
previousRow = thisRow;
// SEPARATING LINE:
if (rowIndex != lastRowIndex)
{
nextRow = table[rowIndex + 1];
int maximumCells = Math.Max(previousRow.Length, nextRow.Length);
for (int i = 0; i < maximumCells; i++)
{
if (i == 0 && i == maximumCells - 1)
{
formattedTable.Append(String.Format("{0}{1}{2}", LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), RIGHT_JOINT));
}
else if (i == 0)
{
formattedTable.Append(String.Format("{0}{1}", LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
}
else if (i == maximumCells - 1)
{
if (i > previousRow.Length)
formattedTable.AppendLine(String.Format("{0}{1}{2}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
else if (i > nextRow.Length)
formattedTable.AppendLine(String.Format("{0}{1}{2}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
else if (i > previousRow.Length - 1)
formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
else if (i > nextRow.Length - 1)
formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
else
formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), RIGHT_JOINT));
}
else
{
if (i > previousRow.Length)
formattedTable.Append(String.Format("{0}{1}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
else if (i > nextRow.Length)
formattedTable.Append(String.Format("{0}{1}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
else
formattedTable.Append(String.Format("{0}{1}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
}
}
}
rowIndex++;
}
// LAST LINE:
for (int i = 0; i < previousRow.Length; i++)
{
if (i == 0)
formattedTable.Append(String.Format("{0}{1}", BOTTOM_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
else if (i == previousRow.Length - 1)
formattedTable.AppendLine(String.Format("{0}{1}{2}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
else
formattedTable.Append(String.Format("{0}{1}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
}
return formattedTable.ToString();
}
}
You can easily do this by:
::variableName.isInitialized
or
this::variableName.isInitialized
But if you are inside a listener or inner class, do this:
this@OuterClassName::variableName.isInitialized
Note: The above statements work fine if you are writing them in the same file(same class or inner class) where the variable is declared but this will not work if you want to check the variable of other class (which could be a superclass or any other class which is instantiated), for ex:
class Test {
lateinit var str:String
}
And to check if str is initialized:
What we are doing here: checking isInitialized
for field str
of Test
class in Test2
class.
And we get an error backing field of var is not accessible at this point.
Check a question already raised about this.
In my opinion, the best way to check the nil and empty string is to take the string count.
var nilString : String?
print(nilString.count) // count is nil
var emptyString = ""
print(emptyString.count) // count is 0
// combine both conditions for optional string variable
if string?.count == nil || string?.count == 0 {
print("Your string is either empty or nil")
}
I am using a com.google.android.material.bottomnavigation.BottomNavigationView
(not the same as OP's) and I tried a variety of the suggested solutions above, but the only thing that worked was setting app:itemBackground
and app:itemIconTint
to my selector color worked for me.
<com.google.android.material.bottomnavigation.BottomNavigationView
style="@style/BottomNavigationView"
android:foreground="?attr/selectableItemBackground"
android:theme="@style/BottomNavigationView"
app:itemBackground="@color/tab_color"
app:itemIconTint="@color/tab_color"
app:itemTextColor="@color/bottom_navigation_text_color"
app:labelVisibilityMode="labeled"
app:menu="@menu/bottom_navigation" />
My color/tab_color.xml
uses android:state_checked
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/grassSelected" android:state_checked="true" />
<item android:color="@color/grassBackground" />
</selector>
and I am also using a selected state color for color/bottom_navigation_text_color.xml
Not totally relevant here but for full transparency, my BottomNavigationView
style is as follows:
<style name="BottomNavigationView" parent="Widget.Design.BottomNavigationView">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">@dimen/bottom_navigation_height</item>
<item name="android:layout_gravity">bottom</item>
<item name="android:textSize">@dimen/bottom_navigation_text_size</item>
</style>
You can also convert by creating a dictionary of elements and then directly converting to a data frame:
import xml.etree.ElementTree as ET
import pandas as pd
# Contents of test.xml
# <?xml version="1.0" encoding="utf-8"?> <tags> <row Id="1" TagName="bayesian" Count="4699" ExcerptPostId="20258" WikiPostId="20257" /> <row Id="2" TagName="prior" Count="598" ExcerptPostId="62158" WikiPostId="62157" /> <row Id="3" TagName="elicitation" Count="10" /> <row Id="5" TagName="open-source" Count="16" /> </tags>
root = ET.parse('test.xml').getroot()
tags = {"tags":[]}
for elem in root:
tag = {}
tag["Id"] = elem.attrib['Id']
tag["TagName"] = elem.attrib['TagName']
tag["Count"] = elem.attrib['Count']
tags["tags"]. append(tag)
df_users = pd.DataFrame(tags["tags"])
df_users.head()
I'm going to answer my own question.
Therefore, the following works for me
$qb->select('c')
->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
->where('c.username = :username');
or
$qb->select('c')
->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
->where('c.username = :username');
x.transpose[6][3..8]
or x[3..8].map {|r| r [6]}
would give what you want.
Example:
a = [ [1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[21, 22, 23, 24, 25]
]
#a[1..2][2] -> [8,13]
puts a.transpose[2][1..2].inspect # [8,13]
puts a[1..2].map {|r| r[2]}.inspect # [8,13]
<?php _x000D_
$con = mysqli_connect("localhost","root","root","EmpDB") or die(mysqli_error($con));_x000D_
if(isset($_POST[add]))_x000D_
{_x000D_
$sno = mysqli_real_escape_string($con,$_POST[sno]);_x000D_
$name = mysqli_real_escape_string($con,$_POST[sname]);_x000D_
$course = mysqli_real_escape_string($con,$_POST[course]);_x000D_
_x000D_
$query = "insert into students(sno,name,course) values($sno,'$name','$course')";_x000D_
//echo $query;_x000D_
$result = mysqli_query($con,$query);_x000D_
printf ("New Record has id %d.\n", mysqli_insert_id($con));_x000D_
mysqli_close($con);_x000D_
_x000D_
} _x000D_
?>_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<title>mysql_insert_id Example</title>_x000D_
</head>_x000D_
<body>_x000D_
<form action="" method="POST">_x000D_
Enter S.NO: <input type="text" name="sno"/><br/>_x000D_
Enter Student Name: <input type="text" name="sname"/><br/>_x000D_
Enter Course: <input type="text" name="course"/><br/>_x000D_
<input type="submit" name="add" value="Add Student"/>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
Sometime we have the column name is below format in SQLServer or MySQL table
Ex : Account Number,customer number
But Hive tables do not support column name containing spaces, so please use below solution to rename your old column names.
Solution:
val renamedColumns = df.columns.map(c => df(c).as(c.replaceAll(" ", "_").toLowerCase()))
df = df.select(renamedColumns: _*)
You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.
Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.
Do you need the object itself or do you just need to know if there is an object that satisfies. If the former then yes: use find:
found_object = my_array.find { |e| e.satisfies_condition? }
otherwise you can use any?
found_it = my_array.any? { |e| e.satisfies_condition? }
The latter will bail with "true" when it finds one that satisfies the condition. The former will do the same, but return the object.
In order to remotely access a PostgreSQL database, you must set the two main PostgreSQL configuration files:
postgresql.conf
pg_hba.conf
Here is a brief description about how you can set them (note that the following description is purely indicative: To configure a machine safely, you must be familiar with all the parameters and their meanings)
First of all configure PostgreSQL service to listen on port 5432 on all network interfaces in Windows 7 machine:
open the file postgresql.conf
(usually located in C:\Program Files\PostgreSQL\9.2\data) and sets the parameter
listen_addresses = '*'
Check the network address of WindowsXP virtual machine, and sets parameters in pg_hba.conf file (located in the same directory of postgresql.conf) so that postgresql can accept connections from virtual machine hosts.
For example, if the machine with Windows XP have 192.168.56.2 IP address, add in the pg_hba.conf
file:
host all all 192.168.56.1/24 md5
this way, PostgreSQL will accept connections from all hosts on the network 192.168.1.XXX.
Restart the PostgreSQL service in Windows 7 (Services-> PosgreSQL 9.2: right click and restart sevice). Install pgAdmin on windows XP machine and try to connect to PostgreSQL.
In Eclipse,
When you use JDBC in your servlet, the driver jar must be placed in the WEB-INF/lib directory of your project.
In my case the solution was this on an Ubuntu based OS:
adb kill-server
sudo cp ~/Android/Sdk/platform-tools/adb /usr/bin/adb
sudo chmod +x /usr/bin/adb
adb start-server
Try it.
<?php
$timestamp=1333342365;
echo gmdate("Y-m-d\TH:i:s\Z", $timestamp);
?>
The opposite of the ==
compare operator is !=
.
In Linux you can do something similar, for example, if your locked file is development.db:
$ fuser development.db This command will show what process is locking the file:
development.db: 5430 Just kill the process...
kill -9 5430 ...And your database will be unlocked.
The exception occurs due to this statement,
called_from.equalsIgnoreCase("add")
It seem that the previous statement
String called_from = getIntent().getStringExtra("called");
returned a null reference.
You can check whether the intent to start this activity contains such a key "called".
Please Search Google given to the world by Larry Page and Sergey Brin.
BufferedWriter out = null;
try {
FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
out = new BufferedWriter(fstream);
out.write("\nsue");
}
catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
finally {
if(out != null) {
out.close();
}
}
Well, you could use nohup to run whatever you are running on 'non-blocking mode'. So you can just keep checking if whatever it was supposed to run, ran, otherwise exit.
nohup ./my-script-that-may-take-long-to-finish.sh & ./check-if-previous-script-ran-or-exit.sh
echo "Script ended on Feb 15, 2011, 9:20AM" > /tmp/done.txt
So in the second one you just check if the file exists.
You have to implement KeyListener
,take a look here:
http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyListener.html
More details on how to use it: http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
You may want to do this all the time by default. I've been struggling to wrap the jquery function or jquery.fn.init method to do this without error, but you can make a simple change to the jquery source to do this. Included are some surrounding lines you can search for. I recommend searching jquery source for The jQuery object is actually just the init constructor 'enhanced'
var
version = "3.3.1",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
var result = new jQuery.fn.init( selector, context );
if ( result.length === 0 ) {
if (window.console && console.warn && context !== 'failsafe') {
if (selector != null) {
console.warn(
new Error('$(\''+selector+'\') selected nothing. Do $(sel, "failsafe") to silence warning. Context:'+context)
);
}
}
}
return result;
},
// Support: Android <=4.0 only
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
jQuery.fn = jQuery.prototype = {
Last but not least, you can get the uncompressed jquery source code here: http://code.jquery.com/
Alternatively to usleep()
, which is not defined in POSIX 2008 (though it was defined up to POSIX 2004, and it is evidently available on Linux and other platforms with a history of POSIX compliance), the POSIX 2008 standard defines nanosleep()
:
nanosleep
- high resolution sleep#include <time.h> int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
The
nanosleep()
function shall cause the current thread to be suspended from execution until either the time interval specified by therqtp
argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified byrqtp
, as measured by the system clock CLOCK_REALTIME.The use of the
nanosleep()
function has no effect on the action or blockage of any signal.
(you have cv::Mat old)
IplImage copy = old;
IplImage* new_image = ©
you work with new as an originally declared IplImage*.
One of the ways to use git diff is:
git diff <commit> <path>
And a common way to refer one commit of the last commit is as a relative path to the actual HEAD. You can reference previous commits as HEAD^ (in your example this will be 123abc) or HEAD^^ (456def in your example), etc ...
So the answer to your question is:
git diff HEAD^^ myfile
The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.
According to this Google blogpost:
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.
There are some default colors defined in android.R.color
int c = getResources().getColor(android.R.color.primary_text_dark);
You are missing the dot on the selector, and you can use toggleClass method on jquery:
$(".result").hover(
function () {
$(this).toggleClass("result_hover")
}
);
Here is an option with only a single comparison.
// return true if in range, otherwise false
function inRange(x, min, max) {
return ((x-min)*(x-max) <= 0);
}
console.log(inRange(5, 1, 10)); // true
console.log(inRange(-5, 1, 10)); // false
console.log(inRange(20, 1, 10)); // false
The required file can be accessed as below from resource folder in scala
val file = scala.io.Source.fromFile(s"src/main/resources/app.config").getLines().mkString
On Unix systems, for several projects, I added these lines into the CMakeLists.txt and it was compiling successfully because base (/usr/include) and local includes (/usr/local/include) go into separated directories:
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I/usr/local/include -L/usr/local/lib")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/usr/local/include")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L/usr/local/lib")
It appends the correct directory, including paths for the C and C++ compiler flags and the correct directory path for the linker flags.
Note: C++ compiler (c++) doesn't support -L, so we have to use CMAKE_EXE_LINKER_FLAGS
I am glad to help you.
To make a sudo command follow the steps :-
Hope this will help you
As stated in an article by Slicehost:
User setup
So let's start by adding the main user to the Apache user group:
sudo usermod -a -G www-data demo
That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.
You will need to log out and log back in again to enable the group change.
Check the groups now:
groups ... # demo www-data
So now I am a member of two groups: My own (demo) and the Apache group (www-data).
Folder setup
Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).
Let's set that up:
sudo chgrp -R www-data /home/demo/public_html
As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.
If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.
Setgid
Good so far, but remember the command we just gave only affects existing folders. What about anything new?
We can set the ownership so anything new is also in the 'www-data' group.
The first command will change the permissions for the public_html directory to include the "setgid" bit:
sudo chmod 2750 /home/demo/public_html
That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.
If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:
sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads
The permissions only need to be set once as new files will automatically be assigned the correct ownership.
I find it easier to remember to just read it and then write it.
For example:
with open('file') as f:
data = f.read()
with open('file', 'w') as f:
f.write('hello')
After reading all of the solutions, I looked for a component and I found one which does exactly what the original question asked for: scrolling to anchor links. https://www.npmjs.com/package/ng2-scroll-to
When you install it, you use syntax like:
// app.awesome.component.ts
@Component({
...
template: `...
<a scrollTo href="#main-section">Scroll to main section</a>
<button scrollTo scrollTargetSelector="#test-section">Scroll to test section</a>
<button scrollTo scrollableElementSelector="#container" scrollYTarget="0">Go top</a>
<!-- Further content here -->
<div id="container">
<section id="main-section">Bla bla bla</section>
<section id="test-section">Bla bla bla</section>
<div>
...`,
})
export class AwesomeComponent {
}
It has worked really well for me.
I had the similar issue. But the following commands saved me.
cd /usr/local/Cellar
sudo chown _mysql mysql
If you use numpy
, this is easy:
slice = arr[:2,:2]
or if you want the 0's,
slice = arr[0:2,0:2]
You'll get the same result.
*note that slice
is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".
Another way, if you're working with lists of lists*:
slice = [arr[i][0:2] for i in range(0,2)]
(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)]
would also work.).
What I did here is that I take each desired row 1 at a time (arr[i]
). I then slice the columns I want out of that row and add it to the list that I'm building.
If you naively try: arr[0:2]
You get the first 2 rows which if you then slice again arr[0:2][0:2]
, you're just slicing the first two rows over again.
*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.