The only editor I know of that has syntax highlighting and a fallback to a textarea is Mozilla Bespin. Google around for embedding Bespin to see how to embed the editor. The only site I know of that uses this right now is the very alpha Mozilla Jetpack Gallery (in the submit a Jetpack page) and you may want to see how they include it.
There's also a blog post on embedding and reusing the Bespin editor that may help you.
Most of my needs were satisfied by this answer https://stackoverflow.com/a/2989277/3001007 by krzysztof. But one issue with that code (i faced was), the binding won't work with multiple controls. So I changed _recursionProtection
with a Guid
based implementation. So it's working for Multiple controls in same window as well.
public class RichTextBoxHelper : DependencyObject
{
private static List<Guid> _recursionProtection = new List<Guid>();
public static string GetDocumentXaml(DependencyObject obj)
{
return (string)obj.GetValue(DocumentXamlProperty);
}
public static void SetDocumentXaml(DependencyObject obj, string value)
{
var fw1 = (FrameworkElement)obj;
if (fw1.Tag == null || (Guid)fw1.Tag == Guid.Empty)
fw1.Tag = Guid.NewGuid();
_recursionProtection.Add((Guid)fw1.Tag);
obj.SetValue(DocumentXamlProperty, value);
_recursionProtection.Remove((Guid)fw1.Tag);
}
public static readonly DependencyProperty DocumentXamlProperty = DependencyProperty.RegisterAttached(
"DocumentXaml",
typeof(string),
typeof(RichTextBoxHelper),
new FrameworkPropertyMetadata(
"",
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
(obj, e) =>
{
var richTextBox = (RichTextBox)obj;
if (richTextBox.Tag != null && _recursionProtection.Contains((Guid)richTextBox.Tag))
return;
// Parse the XAML to a document (or use XamlReader.Parse())
try
{
string docXaml = GetDocumentXaml(richTextBox);
var stream = new MemoryStream(Encoding.UTF8.GetBytes(docXaml));
FlowDocument doc;
if (!string.IsNullOrEmpty(docXaml))
{
doc = (FlowDocument)XamlReader.Load(stream);
}
else
{
doc = new FlowDocument();
}
// Set the document
richTextBox.Document = doc;
}
catch (Exception)
{
richTextBox.Document = new FlowDocument();
}
// When the document changes update the source
richTextBox.TextChanged += (obj2, e2) =>
{
RichTextBox richTextBox2 = obj2 as RichTextBox;
if (richTextBox2 != null)
{
SetDocumentXaml(richTextBox, XamlWriter.Save(richTextBox2.Document));
}
};
}
)
);
}
For completeness sake, let me add few more lines from original answer https://stackoverflow.com/a/2641774/3001007 by ray-burns. This is how to use the helper.
<RichTextBox local:RichTextBoxHelper.DocumentXaml="{Binding Autobiography}" />
private void Log(string s , Color? c = null)
{
richTextBox.SelectionStart = richTextBox.TextLength;
richTextBox.SelectionLength = 0;
richTextBox.SelectionColor = c ?? Color.Black;
richTextBox.AppendText((richTextBox.Lines.Count() == 0 ? "" : Environment.NewLine) + DateTime.Now + "\t" + s);
richTextBox.SelectionColor = Color.Black;
}
RichTextBox rtf = new RichTextBox();
System.IO.MemoryStream stream = new System.IO.MemoryStream(ASCIIEncoding.Default.GetBytes(yourText));
rtf.Selection.Load(stream, DataFormats.Rtf);
OR
rtf.Selection.Text = yourText;
This is not elegant, but you might be able to use the RichTextBox.GetCharIndexFromPosition method to return to you the index of the character that the mouse is currently over, and then use that index to figure out if it's over a link, hotspot, or any other special area. If it is, show your tooltip (and you'd probably want to pass the mouse coordinates into the tooltip's Show method, instead of just passing in the textbox, so that the tooltip can be positioned next to the link).
Example here: http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.getcharindexfromposition(VS.80).aspx
The easiest way to achieve is by applying width to view.
width: '80%'
As of the second half of 2020, there is a much easier way to do this.
Excluding requesting permissions (which I will include at the bottom for devs newer to this), below is the code.
Just remember, you need to include at least this version of the library in your dependencies (in the app's build.gradle
):
implementation 'com.google.android.gms:play-services-location:17.1.0'
... and of course the fine permission in your manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Kotlin (first the setup):
private val fusedLocationClient: FusedLocationProviderClient by lazy {
LocationServices.getFusedLocationProviderClient(applicationContext)
}
private var cancellationTokenSource = CancellationTokenSource()
Then the main code (for FINE_LOCATION):
private fun requestCurrentLocation() {
// Check Fine permission
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
// Main code
val currentLocationTask: Task<Location> = fusedLocationClient.getCurrentLocation(
PRIORITY_HIGH_ACCURACY,
cancellationTokenSource.token
)
currentLocationTask.addOnCompleteListener { task: Task<Location> ->
val result = if (task.isSuccessful) {
val result: Location = task.result
"Location (success): ${result.latitude}, ${result.longitude}"
} else {
val exception = task.exception
"Location (failure): $exception"
}
Log.d(TAG, "getCurrentLocation() result: $result")
}
} else {
// Request fine location permission (full code below).
}
If you prefer Java, it looks like this:
public class JavaVersion extends AppCompatActivity {
private final String TAG = "MainActivity";
// The Fused Location Provider provides access to location APIs.
private FusedLocationProviderClient fusedLocationClient;
// Allows class to cancel the location request if it exits the activity.
// Typically, you use one cancellation source per lifecycle.
private final CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
...
private void requestCurrentLocation() {
Log.d(TAG, "requestCurrentLocation()");
// Request permission
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
// Main code
Task<Location> currentLocationTask = fusedLocationClient.getCurrentLocation(
PRIORITY_HIGH_ACCURACY,
cancellationTokenSource.getToken()
);
currentLocationTask.addOnCompleteListener((new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
String result = "";
if (task.isSuccessful()) {
// Task completed successfully
Location location = task.getResult();
result = "Location (success): " +
location.getLatitude() +
", " +
location.getLongitude();
} else {
// Task failed with an exception
Exception exception = task.getException();
result = "Exception thrown: " + exception;
}
Log.d(TAG, "getCurrentLocation() result: " + result);
}
}));
} else {
// TODO: Request fine location permission
Log.d(TAG, "Request fine location permission.");
}
}
...
}
The arguments:
Example (Kotlin):
override fun onStop() {
super.onStop()
// Cancels location request (if in flight).
cancellationTokenSource.cancel()
}
That's it.
Now, this does use the FusedLocationProviderClient which is a Google Play Services APIs.
That means this works on all Android devices with the Google Play Store (which is a lot of them). However, for devices in China without the Play Store, this won't work, so take that into account.
For developers who are a little newer to this, you need to request the fine (or coarse) location permission if the user hasn't approved it yet, so in the code above, I would request the location permission.
Below is the full code (in Kotlin).
I hope that helps (and makes your live's a little easier)!
/**
* Demonstrates how to easily get the current location via the [FusedLocationProviderClient.getCurrentLocation].
* The main code is in this class's requestCurrentLocation() method.
*/
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
// The Fused Location Provider provides access to location APIs.
private val fusedLocationClient: FusedLocationProviderClient by lazy {
LocationServices.getFusedLocationProviderClient(applicationContext)
}
// Allows class to cancel the location request if it exits the activity.
// Typically, you use one cancellation source per lifecycle.
private var cancellationTokenSource = CancellationTokenSource()
// If the user denied a previous permission request, but didn't check "Don't ask again", this
// Snackbar provides an explanation for why user should approve, i.e., the additional rationale.
private val fineLocationRationalSnackbar by lazy {
Snackbar.make(
binding.container,
R.string.fine_location_permission_rationale,
Snackbar.LENGTH_LONG
).setAction(R.string.ok) {
requestPermissions(
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
REQUEST_FINE_LOCATION_PERMISSIONS_REQUEST_CODE
)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
}
override fun onStop() {
super.onStop()
// Cancels location request (if in flight).
cancellationTokenSource.cancel()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
Log.d(TAG, "onRequestPermissionResult()")
if (requestCode == REQUEST_FINE_LOCATION_PERMISSIONS_REQUEST_CODE) {
when {
grantResults.isEmpty() ->
// If user interaction was interrupted, the permission request
// is cancelled and you receive an empty array.
Log.d(TAG, "User interaction was cancelled.")
grantResults[0] == PackageManager.PERMISSION_GRANTED ->
Snackbar.make(
binding.container,
R.string.permission_approved_explanation,
Snackbar.LENGTH_LONG
)
.show()
else -> {
Snackbar.make(
binding.container,
R.string.fine_permission_denied_explanation,
Snackbar.LENGTH_LONG
)
.setAction(R.string.settings) {
// Build intent that displays the App settings screen.
val intent = Intent()
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
val uri = Uri.fromParts(
"package",
BuildConfig.APPLICATION_ID,
null
)
intent.data = uri
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
}
.show()
}
}
}
}
fun locationRequestOnClick(view: View) {
Log.d(TAG, "locationRequestOnClick()")
requestCurrentLocation()
}
/**
* Gets current location.
* Note: The code checks for permission before calling this method, that is, it's never called
* from a method with a missing permission. Also, I include a second check with my extension
* function in case devs just copy/paste this code.
*/
private fun requestCurrentLocation() {
Log.d(TAG, "requestCurrentLocation()")
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
// Returns a single current location fix on the device. Unlike getLastLocation() that
// returns a cached location, this method could cause active location computation on the
// device. A single fresh location will be returned if the device location can be
// determined within reasonable time (tens of seconds), otherwise null will be returned.
//
// Both arguments are required.
// PRIORITY type is self-explanatory. (Other options are PRIORITY_BALANCED_POWER_ACCURACY,
// PRIORITY_LOW_POWER, and PRIORITY_NO_POWER.)
// The second parameter, [CancellationToken] allows the activity to cancel the request
// before completion.
val currentLocationTask: Task<Location> = fusedLocationClient.getCurrentLocation(
PRIORITY_HIGH_ACCURACY,
cancellationTokenSource.token
)
currentLocationTask.addOnCompleteListener { task: Task<Location> ->
val result = if (task.isSuccessful) {
val result: Location = task.result
"Location (success): ${result.latitude}, ${result.longitude}"
} else {
val exception = task.exception
"Location (failure): $exception"
}
Log.d(TAG, "getCurrentLocation() result: $result")
logOutputToScreen(result)
}
} else {
val provideRationale = shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)
if (provideRationale) {
fineLocationRationalSnackbar.show()
} else {
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_FINE_LOCATION_PERMISSIONS_REQUEST_CODE)
}
}
}
private fun logOutputToScreen(outputString: String) {
val finalOutput = binding.outputTextView.text.toString() + "\n" + outputString
binding.outputTextView.text = finalOutput
}
companion object {
private const val TAG = "MainActivity"
private const val REQUEST_FINE_LOCATION_PERMISSIONS_REQUEST_CODE = 34
}
}
select inet_server_addr();
gives you the ip address of the server.
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
There are many way to do the string aggregation, but the easiest is a user defined function. Try this for a way that does not require a function. As a note, there is no simple way without the function.
This is the shortest route without a custom function: (it uses the ROW_NUMBER() and SYS_CONNECT_BY_PATH functions )
SELECT questionid,
LTRIM(MAX(SYS_CONNECT_BY_PATH(elementid,','))
KEEP (DENSE_RANK LAST ORDER BY curr),',') AS elements
FROM (SELECT questionid,
elementid,
ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) AS curr,
ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) -1 AS prev
FROM emp)
GROUP BY questionid
CONNECT BY prev = PRIOR curr AND questionid = PRIOR questionid
START WITH curr = 1;
Seems there is a CSS solution after all. The reason Safari waits for a second touch is because of the background image (or elements) you usually assign on the :hover event. If there is none to be shown - you won't have any problems. The solution is to target iOS platform with secondary CSS file (or style in case of a JS approach) which overrides :hover background to inherit for example and keep hidden the elements you were going to display on mouse over:
Here is an example CSS and HTML - a product block with a starred label on mouse over:
HTML:
<a href="#" class="s"><span class="s-star"></span>Some text here</a>
CSS:
.s {
background: url(some-image.png) no-repeat 0 0;
}
.s:hover {
background: url(some-image-r.png) no-repeat 0 0;
}
.s-star {
background: url(star.png) no-repeat 0 0;
height: 56px;
position: absolute;
width: 72px;
display:none;
}
.s:hover .s-star {
display:block;
}
Solution (secondary CSS):
/* CSS */
/* Keep hovers the same or hidden */
.s:hover {
background:inherit;
}
.s:hover .s-star {
display:none;
}
You might not have the ability to install Expect on the target server. This is often the case when one writes, say, a Jenkins job.
If so, I would consider something like the answer to the following on askubuntu.com:
https://askubuntu.com/questions/338857/automatically-enter-input-in-command-line
printf 'y\nyes\nno\nmaybe\n' | ./script_that_needs_user_input
Note that in some rare cases the command does not require the user to press enter after the character. in that case leave the newlines out:
printf 'yyy' | ./script_that_needs_user_input
For sake of completeness you can also use a here document:
./script_that_needs_user_input << EOF
y
y
y
EOF
Or if your shell supports it a here string:
./script <<< "y
y
y
"
Or you can create a file with one input per line:
./script < inputfile
Again, all credit for this answer goes to the author of the answer on askubuntu.com, lesmana.
The best way I've found to do this is with StrMethodFormatter
:
import matplotlib as mpl
ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
For example:
import pandas as pd
import requests
import matplotlib.pyplot as plt
import matplotlib as mpl
url = 'https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USDT&aggregate=1'
df = pd.DataFrame({'BTC/USD': [d['close'] for d in requests.get(url).json()['Data']]})
ax = df.plot()
ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
plt.show()
webview.loadDataWithBaseURL(null, text, "text/html", "UTF-8", null);
Check the android documentation. It's in fact not much different than standard java io file handling so you could also check that documentation.
An example from the android documentation:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
It seems only your DAO are using session. Thus a new session is open then close for each call to a DAO method. Thus the execution of the program can be resumed as:
// open a session, get the number of entity and close the session
int startingCount = sfdao.count();
// open a session, create a new entity and close the session
sfdao.create( sf );
// open a session, read an entity and close the session
SecurityFiling sf2 = sfdao.read( sf.getId() );
// open a session, delete an entity and close the session
sfdao.delete( sf );
etc...
By default, collection and association in an entity are lazy: they are loaded from the database on demand. Thus:
sf.getSfSubmissionType().equals( sf2.getSfSubmissionType() )
is throwing an exception because it request a new loading from the database, and the session associated with the loading of the entity has already been closed.
There is two approaches to resolve this problem:
create a session to enclosed all our code. Thus it would mean changing your DAO content to avoid opening a second session
create a session then update (i.e. reconnect) your entity to this session before the assertions.
session.update(object);
2013 August. Facebook doesn't allow to set domain with port for an App, as example "localhost:3000".
So you can use https://pagekite.net to tunnel your localhost:port
to proper domain.
Rails developers can use http://progrium.com/localtunnel/ for free.
.live()
is deprecated.When you want to use for delegated elements then use .on() wiht the following syntax
$(document).on('click', "a.tabclick", function() {
This syntax will work for delegated events
Fears of performance or bloat are not good reason to forgo C++. Every language has its potential pitfalls and trade offs - good programmers learn about these and where necessary develop coping strategies, poor programmers will fall foul and blame the language.
Interpreted Python is in many ways considered to be a "slow" language, but for non-trivial tasks a skilled Python programmer can easily produce code that executes faster than that of an inexperienced C developer.
In my industry, video games, we write high performance code in C++ by avoiding things such as RTTI, exceptions, or virtual-functions in inner loops. These can be extremely useful but have performance or bloat problems that it's desirable to avoid. If we were to go a step further and switch entirely to C we would gain little and lose the most useful constructs of C++.
The biggest practical reason for preferring C is that support is more widespread than C++. There are many platforms, particularly embedded ones, that do not even have C++ compilers.
There is also the matter of compatibility for vendors. While C has a stable and well-defined ABI (Application Binary Interface) C++ does not. The ABI in C++ is more complicated due to such things as vtables and constructurs/destructors so is implemented differently with every vendor, and even versions of a vendors toolchain.
In real-terms this means you cannot take a library generated by one compiler and link it with code or a library from another which creates a nightmare for distributed projects or middleware providers of binary libraries.
dim mydate = from cv in mydata.t1s
select cv.date1 asc
datetime mindata = mydate[0];
In swift 4 you can write it smarter:
let d = [ 1 : "hello", 2 : "bye", -1 : "foo" ]
d = [Int : String](uniqueKeysWithValues: d.sorted{ $0.key < $1.key })
example:
XML
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="country.xsl"?>
<country xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="country.xsd">
<countryName>Australia</countryName>
<capital>Canberra</capital>
<nationalLanguage>English</nationalLanguage>
<population>21000000</population>
<currency>Australian Dollar</currency>
<nationalIdentities>
<nationalAnthem>Advance Australia Fair</nationalAnthem>
<nationalDay>Australia Day (26 January)</nationalDay>
<nationalColour>Green and Gold</nationalColour>
<nationalGemstone>Opal</nationalGemstone>
<nationalFlower>Wattle (Acacia pycnantha)</nationalFlower>
</nationalIdentities>
<publicHolidays>
<newYearDay>1 January</newYearDay>
<australiaDay>26 January</australiaDay>
<anzacDay>25 April</anzacDay>
<christmasDay>25 December</christmasDay>
<boxingDay>26 December</boxingDay>
<laborDay>Variable Date</laborDay>
<easter>Variable Date</easter>
<queenBirthDay>21 April (Variable Date)</queenBirthDay>
</publicHolidays>
<states>
<stateName><Name>NSW - New South Wales</Name></stateName>
<stateName><Name>VIC - Victoria</Name></stateName>
<stateName><Name>QLD - Queensland</Name></stateName>
<stateName><Name>SA - South Australia</Name></stateName>
<stateName><Name>WA - Western Australia</Name></stateName>
<stateName><Name>TAS - Tasmania</Name></stateName>
</states>
<territories>
<territoryName>ACT - Australian Capital Territory</territoryName>
<territoryName>NT - Northern Territory</territoryName>
</territories>
</country>
XSD:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="country">
<xs:complexType>
<xs:sequence>
<xs:element name="countryName" type="xs:string"/>
<xs:element name="capital" type="xs:string"/>
<xs:element name="nationalLanguage" type="xs:string"/>
<xs:element name="population" type="xs:double"/>
<xs:element name="currency" type="xs:string"/>
<xs:element name="nationalIdentities">
<xs:complexType>
<xs:sequence>
<xs:element name="nationalAnthem" type="xs:string"/>
<xs:element name="nationalDay" type="xs:string"/>
<xs:element name="nationalColour" type="xs:string"/>
<xs:element name="nationalGemstone" type="xs:string"/>
<xs:element name="nationalFlower" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="publicHolidays">
<xs:complexType>
<xs:sequence>
<xs:element name="newYearDay" maxOccurs="1" type="xs:string"/>
<xs:element name="australiaDay" maxOccurs="1" type="xs:string"/>
<xs:element name="anzacDay" maxOccurs="1" type="xs:string"/>
<xs:element name="christmasDay" maxOccurs="1" type="xs:string"/>
<xs:element name="boxingDay" maxOccurs="1" type="xs:string"/>
<xs:element name="laborDay" maxOccurs="1" type="xs:string"/>
<xs:element name="easter" maxOccurs="1" type="xs:string"/>
<xs:element name="queenBirthDay" maxOccurs="1" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="states">
<xs:complexType>
<xs:sequence>
<xs:element name="stateName" minOccurs="1" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="Name" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="territories">
<xs:complexType>
<xs:sequence>
<xs:element name="territoryName" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
XSL:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html" indent="yes" version="4.0"/>
<xsl:template match="/">
<html>
<body>
<xsl:for-each select="country">
<xsl:value-of select="countryName"/><br/>
<xsl:value-of select="capital"/><br/>
<xsl:value-of select="nationalLanguage"/><br/>
<xsl:value-of select="population"/><br/>
<xsl:value-of select="currency"/><br/>
<xsl:for-each select="nationalIdentities">
<xsl:value-of select="nationalAnthem"/><br/>
<xsl:value-of select="nationalDay"/><br/>
<xsl:value-of select="nationalColour"/><br/>
<xsl:value-of select="nationalGemstone"/><br/>
<xsl:value-of select="nationalFlower"/><br/>
</xsl:for-each>
<xsl:for-each select="publicHolidays">
<xsl:value-of select="newYearDay"/><br/>
<xsl:value-of select="australiaDay"/><br/>
<xsl:value-of select="anzacDay"/><br/>
<xsl:value-of select="christmasDay"/><br/>
<xsl:value-of select="boxingDay"/><br/>
<xsl:value-of select="laborDay"/><br/>
<xsl:value-of select="easter"/><br/>
<xsl:value-of select="queenBirthDay"/><br/>
</xsl:for-each>
<xsl:for-each select="states/stateName">
<xsl:value-of select="Name"/><br/>
</xsl:for-each>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Result:
Australia
Canberra
English
21000000
Australian Dollar
Advance Australia Fair
Australia Day (26 January)
Green and Gold
Opal
Wattle (Acacia pycnantha)
1 January
26 January
25 April
25 December
26 December
Variable Date
Variable Date
21 April (Variable Date)
NSW - New South Wales
VIC - Victoria
QLD - Queensland
SA - South Australia
WA - Western Australia
TAS - Tasmania
select <column list> into <dest. table> from <source table>;
You could do this way.
SELECT windows_release, windows_service_pack_level,
windows_sku, os_language_version
into new_table_name
FROM sys.dm_os_windows_info OPTION (RECOMPILE);
I guess there's no such feature in postman as to run concurrent tests.
If i were you i would consider Apache jMeter which is used exactly for such scenarios.
Regarding Postman, the only thing that could more or less meet your needs is - Postman Runner. There you can specify the details:
The runs won't be concurrent, only consecutive.
Hope that helps. But do consider jMeter (you'll love it).
you can specify which column is an index in your csv file by using index_col parameter of from_csv function if this doesn't solve you problem please provide example of your data
Mac OSX 10.6.8 (Snow Leopard):
1) When you do pip install virtualenv
, the pip command is associated with one of your python versions, and virtualenv
gets installed into that version of python. You can do
$ which pip
to see what version of python that is. If you see something like:
$ which pip
/usr/local/bin/pip
then do:
$ ls -al /usr/local/bin/pip
lrwxrwxr-x 1 root admin 65 Apr 10 2015 /usr/local/bin/pip ->
../../../Library/Frameworks/Python.framework/Versions/2.7/bin/pip
You can see the python version in the output.
By default, that will be the version of python that is used for any new environment you create. However, you can specify any version of python installed on your computer to use inside a new environment with the -p flag
:
$ virtualenv -p python3.2 my_env
Running virtualenv with interpreter /usr/local/bin/python3.2
New python executable in my_env/bin/python
Installing setuptools, pip...done.
virtualenv my_env
will create a folder in the current directory which will contain the Python executable files, and a copy of the pip [command] which you can use to install other packages.
http://docs.python-guide.org/en/latest/dev/virtualenvs/
virtualenv
just copies python from a location on your computer into the newly created my_env/bin/ directory.
2) The system python is in /usr/bin
, while the various python versions I installed were, by default, installed into:
/usr/local/bin
3) The various pythons I installed have names like python2.7
or python3.2
, and I can use those names rather than full paths.
1) I had some problems getting virtualenvwrapper to work. This is what I ended up putting in ~/.bash_profile
:
export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/django_projects #Not very important -- mkproject command uses this
#Added the following based on:
#http://stackoverflow.com/questions/19665327/virtualenvwrapper-installation-snow-leopard-python
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python2.7
#source /usr/local/bin/virtualenvwrapper.sh
source /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh
2) The -p option
works differently with virtualenvwrapper: I have to specify the full path to the python interpreter to be used in the new environment(when I do not want to use the default python version):
$ mkvirtualenv -p /usr/local/bin/python3.2 my_env
Running virtualenv with interpreter /usr/local/bin/python3
New python executable in my_env/bin/python
Installing setuptools, pip...done.
Usage: source deactivate
removes the 'bin' directory of the environment activated with 'source
activate' from PATH.
Unlike virtualenv, virtualenvwrapper will create the environment at the location specified by the $WORKON_HOME environment variable. That keeps all your environments in one place.
Using this,
String s = "03/24/2013 21:54";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
try
{
Date date = simpleDateFormat.parse(s);
System.out.println("date : "+simpleDateFormat.format(date));
}
catch (ParseException ex)
{
System.out.println("Exception "+ex);
}
Java 9 has the following method to create an immutable list:
List<String> places = List.of("Buenos Aires", "Córdoba", "La Plata");
which is easily adapted to create a mutable list, if required:
List<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));
Similar methods are available for Set
and Map
.
Since PHP is dynamically weakly typed, you can pass any variable to the function and the function will try to do its best with it.
Therefore, you can indeed pass arrays as parameters.
In MySQL Workbench 6, commands have been repositioned as the "Server Administration" tab is gone.
You now find the option "Data Export" under the "Management" section when you open a standard server connection.
The SpecialCells Does not actually work as it needs to be continuous. I have solved this by adding a sort funtion in order to sort the data based on the coloumns i need.
Sorry for no comments on the code as i was not planning to share it:
Sub testtt()
arr = FilterAndGetData(Worksheets("Data").range("A:K"), Array(1, 9), Array("george", "WeeklyCash"), Array(1, 2, 3, 10, 11), 1)
Debug.Print sms(arr)
End Sub
Function FilterAndGetData(ByVal rng As Variant, ByVal fields As Variant, ByVal criterias As Variant, ByVal colstoreturn As Variant, ByVal headers As Boolean) As Variant
Dim SUset, EAset, CMset
If Application.ScreenUpdating Then Application.ScreenUpdating = False: SUset = False Else SUset = True
If Application.EnableEvents Then Application.EnableEvents = False: EAset = False Else EAset = True
If Application.Calculation = xlCalculationAutomatic Then Application.Calculation = xlCalculationManual: CMset = False Else CMset = True
For Each col In rng.Columns: col.Hidden = False: Next col
Dim oldsheet, scol, ecol, srow, hyesno As String
Dim i, counter As Integer
oldsheet = ActiveSheet.Name
Worksheets(rng.Worksheet.Name).Activate
Worksheets(rng.Worksheet.Name).AutoFilterMode = False
scol = Chr(rng.Column + 64)
ecol = Chr(rng.Columns.Count + rng.Column + 64 - 1)
srow = rng.row
If UBound(fields) - LBound(fields) <> UBound(criterias) - LBound(criterias) Then FilterAndGetData = "Fields&Crit. counts dont match": GoTo done
dd = sortrange(rng, colstoreturn, headers)
For i = LBound(fields) To UBound(fields)
rng.AutoFilter Field:=CStr(fields(i)), Criteria1:=CStr(criterias(i))
Next i
Dim rngg As Variant
rngg = rng.SpecialCells(xlCellTypeVisible)
Debug.Print ActiveSheet.AutoFilter.range.address
FilterAndGetData = ActiveSheet.AutoFilter.range.SpecialCells(xlCellTypeVisible).Value
For Each row In rng.Rows
If row.EntireRow.Hidden Then Debug.Print yes
Next row
done:
'Worksheets("Data").AutoFilterMode = False
Worksheets(oldsheet).Activate
If SUset Then Application.ScreenUpdating = True
If EAset Then Application.EnableEvents = True
If CMset Then Application.Calculation = xlCalculationAutomatic
End Function
Function sortrange(ByVal rng As Variant, ByVal colnumbers As Variant, ByVal headers As Boolean)
Dim SUset, EAset, CMset
If Application.ScreenUpdating Then Application.ScreenUpdating = False: SUset = False Else SUset = True
If Application.EnableEvents Then Application.EnableEvents = False: EAset = False Else EAset = True
If Application.Calculation = xlCalculationAutomatic Then Application.Calculation = xlCalculationManual: CMset = False Else CMset = True
For Each col In rng.Columns: col.Hidden = False: Next col
Dim oldsheet, scol, srow, sortcol, hyesno As String
Dim i, counter As Integer
oldsheet = ActiveSheet.Name
Worksheets(rng.Worksheet.Name).Activate
Worksheets(rng.Worksheet.Name).AutoFilterMode = False
scol = rng.Column
srow = rng.row
If headers Then hyesno = xlYes Else hyesno = xlNo
For i = LBound(colnumbers) To UBound(colnumbers)
rng.Sort key1:=range(Chr(scol + colnumbers(i) + 63) + CStr(srow)), order1:=xlAscending, Header:=hyesno
Next i
sortrange = "123"
done:
Worksheets(oldsheet).Activate
If SUset Then Application.ScreenUpdating = True
If EAset Then Application.EnableEvents = True
If CMset Then Application.Calculation = xlCalculationAutomatic
End Function
If the other answers fail, importing it as
import moment from 'moment/moment.js'
may work.
Note: all of the other answers here will fail if the two vectors have either the same direction (ex, (1, 0, 0)
, (1, 0, 0)
) or opposite directions (ex, (-1, 0, 0)
, (1, 0, 0)
).
Here is a function which will correctly handle these cases:
import numpy as np
def unit_vector(vector):
""" Returns the unit vector of the vector. """
return vector / np.linalg.norm(vector)
def angle_between(v1, v2):
""" Returns the angle in radians between vectors 'v1' and 'v2'::
>>> angle_between((1, 0, 0), (0, 1, 0))
1.5707963267948966
>>> angle_between((1, 0, 0), (1, 0, 0))
0.0
>>> angle_between((1, 0, 0), (-1, 0, 0))
3.141592653589793
"""
v1_u = unit_vector(v1)
v2_u = unit_vector(v2)
return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
regular view----->short name for a query,no additional space is used here
Materialised view---->similar to creating table whose data will refresh periodically based on data query used for creating the view
If can manage a limit in this mode
public List<ExampleModel> listExampleModel() {
return listExampleModel(null, null);
}
public List<ExampleModel> listExampleModel(Integer first, Integer count) {
Query tmp = getSession().createQuery("from ExampleModel");
if (first != null)
tmp.setFirstResult(first);
if (count != null)
tmp.setMaxResults(count);
return (List<ExampleModel>)tmp.list();
}
This is a really simple code to handle a limit or a list.
I've succeed with the following code:
url = "http://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"
x = read.csv(file=url)
Note that I've changed the protocol from https to http, since the first one doesn't seem to be supported in R.
This also works like a charm
<form>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio" checked>Option 1_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio">Option 2_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio">Option 3_x000D_
</label>_x000D_
</form>
_x000D_
Please use kafka-topics.sh --list --bootstrap-server localhost:9092
to list down all topics
Some shortcut is to create a NumberFormatInfo class, set its NumberDecimalSeparator property to "." and use the class as parameter to ToString() method whenever u need it.
using System.Globalization;
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ".";
value.ToString(nfi);
Just add an ID tag to the input element... ie:
and check the value of the element in you javascript:
document.getElementById("question").value
Oh ya, get get firefox/firebug. It's the only way to do javascript.
Python boolean keywords are True
and False
, notice the capital letters. So like this:
a = True;
b = True;
match_var = True if a == b else False
print match_var;
When compiled and run, this prints:
True
I would use something along these lines...
netstat -rn | grep "default" | awk '{print $2}'
I have combined the James', Howard's and Éder's solutions and created a more generic implementation:
The full code is written bellow (use "DEFINE_ENUM_CLASS_WITH_ToString_METHOD" for defining an enum) (online demo).
#include <boost/preprocessor.hpp>
#include <iostream>
// ADD_PARENTHESES_FOR_EACH_TUPLE_IN_SEQ implementation is taken from:
// http://lists.boost.org/boost-users/2012/09/76055.php
//
// This macro do the following:
// input:
// (Element1, "Element 1 string repr", 2) (Element2) (Element3, "Element 3 string repr")
// output:
// ((Element1, "Element 1 string repr", 2)) ((Element2)) ((Element3, "Element 3 string repr"))
#define HELPER1(...) ((__VA_ARGS__)) HELPER2
#define HELPER2(...) ((__VA_ARGS__)) HELPER1
#define HELPER1_END
#define HELPER2_END
#define ADD_PARENTHESES_FOR_EACH_TUPLE_IN_SEQ(sequence) BOOST_PP_CAT(HELPER1 sequence,_END)
// CREATE_ENUM_ELEMENT_IMPL works in the following way:
// if (elementTuple.GetSize() == 4) {
// GENERATE: elementTuple.GetElement(0) = elementTuple.GetElement(2)),
// } else {
// GENERATE: elementTuple.GetElement(0),
// }
// Example 1:
// CREATE_ENUM_ELEMENT_IMPL((Element1, "Element 1 string repr", 2, _))
// generates:
// Element1 = 2,
//
// Example 2:
// CREATE_ENUM_ELEMENT_IMPL((Element2, _))
// generates:
// Element1,
#define CREATE_ENUM_ELEMENT_IMPL(elementTuple) \
BOOST_PP_IF(BOOST_PP_EQUAL(BOOST_PP_TUPLE_SIZE(elementTuple), 4), \
BOOST_PP_TUPLE_ELEM(0, elementTuple) = BOOST_PP_TUPLE_ELEM(2, elementTuple), \
BOOST_PP_TUPLE_ELEM(0, elementTuple) \
),
// we have to add a dummy element at the end of a tuple in order to make
// BOOST_PP_TUPLE_ELEM macro work in case an initial tuple has only one element.
// if we have a tuple (Element1), BOOST_PP_TUPLE_ELEM(2, (Element1)) macro won't compile.
// It requires that a tuple with only one element looked like (Element1,).
// Unfortunately I couldn't find a way to make this transformation, so
// I just use BOOST_PP_TUPLE_PUSH_BACK macro to add a dummy element at the end
// of a tuple, in this case the initial tuple will look like (Element1, _) what
// makes it compatible with BOOST_PP_TUPLE_ELEM macro
#define CREATE_ENUM_ELEMENT(r, data, elementTuple) \
CREATE_ENUM_ELEMENT_IMPL(BOOST_PP_TUPLE_PUSH_BACK(elementTuple, _))
#define DEFINE_CASE_HAVING_ONLY_ENUM_ELEMENT_NAME(enumName, element) \
case enumName::element : return BOOST_PP_STRINGIZE(element);
#define DEFINE_CASE_HAVING_STRING_REPRESENTATION_FOR_ENUM_ELEMENT(enumName, element, stringRepresentation) \
case enumName::element : return stringRepresentation;
// GENERATE_CASE_FOR_SWITCH macro generates case for switch operator.
// Algorithm of working is the following
// if (elementTuple.GetSize() == 1) {
// DEFINE_CASE_HAVING_ONLY_ENUM_ELEMENT_NAME(enumName, elementTuple.GetElement(0))
// } else {
// DEFINE_CASE_HAVING_STRING_REPRESENTATION_FOR_ENUM_ELEMENT(enumName, elementTuple.GetElement(0), elementTuple.GetElement(1))
// }
//
// Example 1:
// GENERATE_CASE_FOR_SWITCH(_, EnumName, (Element1, "Element 1 string repr", 2))
// generates:
// case EnumName::Element1 : return "Element 1 string repr";
//
// Example 2:
// GENERATE_CASE_FOR_SWITCH(_, EnumName, (Element2))
// generates:
// case EnumName::Element2 : return "Element2";
#define GENERATE_CASE_FOR_SWITCH(r, enumName, elementTuple) \
BOOST_PP_IF(BOOST_PP_EQUAL(BOOST_PP_TUPLE_SIZE(elementTuple), 1), \
DEFINE_CASE_HAVING_ONLY_ENUM_ELEMENT_NAME(enumName, BOOST_PP_TUPLE_ELEM(0, elementTuple)), \
DEFINE_CASE_HAVING_STRING_REPRESENTATION_FOR_ENUM_ELEMENT(enumName, BOOST_PP_TUPLE_ELEM(0, elementTuple), BOOST_PP_TUPLE_ELEM(1, elementTuple)) \
)
// DEFINE_ENUM_CLASS_WITH_ToString_METHOD final macro witch do the job
#define DEFINE_ENUM_CLASS_WITH_ToString_METHOD(enumName, enumElements) \
enum class enumName { \
BOOST_PP_SEQ_FOR_EACH( \
CREATE_ENUM_ELEMENT, \
0, \
ADD_PARENTHESES_FOR_EACH_TUPLE_IN_SEQ(enumElements) \
) \
}; \
inline const char* ToString(const enumName element) { \
switch (element) { \
BOOST_PP_SEQ_FOR_EACH( \
GENERATE_CASE_FOR_SWITCH, \
enumName, \
ADD_PARENTHESES_FOR_EACH_TUPLE_IN_SEQ(enumElements) \
) \
default: return "[Unknown " BOOST_PP_STRINGIZE(enumName) "]"; \
} \
}
DEFINE_ENUM_CLASS_WITH_ToString_METHOD(Elements,
(Element1)
(Element2, "string representation for Element2 ")
(Element3, "Element3 string representation", 1000)
(Element4, "Element 4 string repr")
(Element5, "Element5", 1005)
(Element6, "Element6 ")
(Element7)
)
// Generates the following:
// enum class Elements {
// Element1, Element2, Element3 = 1000, Element4, Element5 = 1005, Element6,
// };
// inline const char* ToString(const Elements element) {
// switch (element) {
// case Elements::Element1: return "Element1";
// case Elements::Element2: return "string representation for Element2 ";
// case Elements::Element3: return "Element3 string representation";
// case Elements::Element4: return "Element 4 string repr";
// case Elements::Element5: return "Element5";
// case Elements::Element6: return "Element6 ";
// case Elements::Element7: return "Element7";
// default: return "[Unknown " "Elements" "]";
// }
// }
int main() {
std::cout << ToString(Elements::Element1) << std::endl;
std::cout << ToString(Elements::Element2) << std::endl;
std::cout << ToString(Elements::Element3) << std::endl;
std::cout << ToString(Elements::Element4) << std::endl;
std::cout << ToString(Elements::Element5) << std::endl;
std::cout << ToString(Elements::Element6) << std::endl;
std::cout << ToString(Elements::Element7) << std::endl;
return 0;
}
Notification Vibrate
mBuilder.setVibrate(new long[] { 1000, 1000});
Sound
mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may independently configure the process.env.PORT
variable for you; after all, your script runs in their environment.
Amazon's Elastic Beanstalk does this. If you try to set a static port value like 3000
instead of process.env.PORT || 3000
where 3000 is your static setting, then your application will result in a 500 gateway error because Amazon is configuring the port for you.
This is a minimal Express application that will deploy on Amazon's Elastic Beanstalk:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
// use port 3000 unless there exists a preconfigured port
var port = process.env.PORT || 3000;
app.listen(port);
When you say the first three columns, do you mean your SUM
columns? If so, add ELSE 0
to your CASE
statements. The SUM
of a NULL
value is NULL
.
sum(case when c.runstatus = 'Succeeded' then 1 else 0 end) as Succeeded,
sum(case when c.runstatus = 'Failed' then 1 else 0 end) as Failed,
sum(case when c.runstatus = 'Cancelled' then 1 else 0 end) as Cancelled,
UPDATE: By version 41 of Google Chrome, initMouseEvent
seemed to have a changed behavior.
this can be done by simulating ctrl
+ click
(or any other key/event combinations that open a background tab) on a dynamically generated a
element with its href
attribute set to the desired url
In action: fiddle
function openNewBackgroundTab(){
var a = document.createElement("a");
a.href = "http://www.google.com/";
var evt = document.createEvent("MouseEvents");
//the tenth parameter of initMouseEvent sets ctrl key
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
true, false, false, false, 0, null);
a.dispatchEvent(evt);
}
tested only on chrome
I had the same issue and i had it formatted into JSON as a String instead. Might be a bit of a hack but it's easy to implement.
private BigDecimal myValue = new BigDecimal("25.50");
...
public String getMyValue() {
return myValue.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
}
Absolutely, yes you can. This link contains details about how you can achieve that: https://api.jquery.com/jquery.noconflict/.
Under linux Ungzip your file using gunzip Edit your unzip sql file using
vi unzipsqlfile.sql
Remove the first binary line with esc dd go to the bottom of the file with esc shift g remove the last binary line with dd save the file esc x: Then reimport to mysql with :
mysql -u username -p new_database < unzipsqlfile.sql
I performed that with a 20go sql file from a jetbackup cpanel mysql backup. Be patient to wait vi doing the job for big files
I just had the same happen on me when I tried to run a python script from a shared folder in VirtualBox
within the new Ubuntu 20.04 LTS. Python bailed with Killed
while loading my own personal library. When I moved the folder to a local directory, the issue went away. It appears that the Killed
stop happened during the initial imports of my library as I got messages of missing libraries once I moved the folder over.
The issue went away after I restarted my computer.
Therefore, people may want to try moving the program to a local directory if its over a share of some kind or it could be a transient problem that just requires a reboot of the OS.
Demo:
In [255]: df = pd.DataFrame(np.random.rand(5, 6), columns=list('abcdef'))
In [256]: df
Out[256]:
a b c d e f
0 0.823638 0.767999 0.460358 0.034578 0.592420 0.776803
1 0.344320 0.754412 0.274944 0.545039 0.031752 0.784564
2 0.238826 0.610893 0.861127 0.189441 0.294646 0.557034
3 0.478562 0.571750 0.116209 0.534039 0.869545 0.855520
4 0.130601 0.678583 0.157052 0.899672 0.093976 0.268974
In [257]: dfs = np.split(df, [4], axis=1)
In [258]: dfs[0]
Out[258]:
a b c d
0 0.823638 0.767999 0.460358 0.034578
1 0.344320 0.754412 0.274944 0.545039
2 0.238826 0.610893 0.861127 0.189441
3 0.478562 0.571750 0.116209 0.534039
4 0.130601 0.678583 0.157052 0.899672
In [259]: dfs[1]
Out[259]:
e f
0 0.592420 0.776803
1 0.031752 0.784564
2 0.294646 0.557034
3 0.869545 0.855520
4 0.093976 0.268974
np.split()
is pretty flexible - let's split an original DF into 3 DFs at columns with indexes [2,3]
:
In [260]: dfs = np.split(df, [2,3], axis=1)
In [261]: dfs[0]
Out[261]:
a b
0 0.823638 0.767999
1 0.344320 0.754412
2 0.238826 0.610893
3 0.478562 0.571750
4 0.130601 0.678583
In [262]: dfs[1]
Out[262]:
c
0 0.460358
1 0.274944
2 0.861127
3 0.116209
4 0.157052
In [263]: dfs[2]
Out[263]:
d e f
0 0.034578 0.592420 0.776803
1 0.545039 0.031752 0.784564
2 0.189441 0.294646 0.557034
3 0.534039 0.869545 0.855520
4 0.899672 0.093976 0.268974
Finally I found a neat solution, thanks to Apache Commons:
package com.example;
import org.apache.commons.io.IOUtils;
public class FooTest {
@Test
public void shouldWork() throws Exception {
String xml = IOUtils.toString(
this.getClass().getResourceAsStream("abc.xml"),
"UTF-8"
);
}
}
Works perfectly. File src/test/resources/com/example/abc.xml
is loaded (I'm using Maven).
If you replace "abc.xml"
with, say, "/foo/test.xml"
, this resource will be loaded: src/test/resources/foo/test.xml
You can also use Cactoos:
package com.example;
import org.cactoos.io.ResourceOf;
import org.cactoos.io.TextOf;
public class FooTest {
@Test
public void shouldWork() throws Exception {
String xml = new TextOf(
new ResourceOf("/com/example/abc.xml") // absolute path always!
).asString();
}
}
If you use the Mongoose API and looking to pull a sub/child object: Read this document Don't forget to use save() when you're done editing otherwise the changes won't be saved to the database.
Code snippet for both recursive and non-recursive approaches:
//helper method to get the list of files from the HDFS path
public static List<String>
listFilesFromHDFSPath(Configuration hadoopConfiguration,
String hdfsPath,
boolean recursive) throws IOException,
IllegalArgumentException
{
//resulting list of files
List<String> filePaths = new ArrayList<String>();
//get path from string and then the filesystem
Path path = new Path(hdfsPath); //throws IllegalArgumentException
FileSystem fs = path.getFileSystem(hadoopConfiguration);
//if recursive approach is requested
if(recursive)
{
//(heap issues with recursive approach) => using a queue
Queue<Path> fileQueue = new LinkedList<Path>();
//add the obtained path to the queue
fileQueue.add(path);
//while the fileQueue is not empty
while (!fileQueue.isEmpty())
{
//get the file path from queue
Path filePath = fileQueue.remove();
//filePath refers to a file
if (fs.isFile(filePath))
{
filePaths.add(filePath.toString());
}
else //else filePath refers to a directory
{
//list paths in the directory and add to the queue
FileStatus[] fileStatuses = fs.listStatus(filePath);
for (FileStatus fileStatus : fileStatuses)
{
fileQueue.add(fileStatus.getPath());
} // for
} // else
} // while
} // if
else //non-recursive approach => no heap overhead
{
//if the given hdfsPath is actually directory
if(fs.isDirectory(path))
{
FileStatus[] fileStatuses = fs.listStatus(path);
//loop all file statuses
for(FileStatus fileStatus : fileStatuses)
{
//if the given status is a file, then update the resulting list
if(fileStatus.isFile())
filePaths.add(fileStatus.getPath().toString());
} // for
} // if
else //it is a file then
{
//return the one and only file path to the resulting list
filePaths.add(path.toString());
} // else
} // else
//close filesystem; no more operations
fs.close();
//return the resulting list
return filePaths;
} // listFilesFromHDFSPath
The apache commons lang package provides such a class which can be used to build up a default toString() method using reflection to get the values of fields. Just have a look at this.
Look, every answer above that proposes writing a string replacement by a constant string can only be wrong. Why? Because you don't respect the region settings of Windows! Windows assures the user to have the freedom to set whatever separator character s/he wants. S/He can open up the control panel, go into the region panel, click on advanced and change the character at any time. Even during your program run. Think of this. A good solution must be aware of this.
So, first you will have to ask yourself, where this number is coming from, that you want to parse. If it's coming from input in the .NET Framework no problem, because it will be in the same format. But maybe it was coming from outside, maybe from a external server, maybe from an old DB that only supports string properties. There, the db admin should have given a rule in which format the numbers are to be stored. If you know for example that it will be an US DB with US format you can use this piece of code:
CultureInfo usCulture = new CultureInfo("en-US");
NumberFormatInfo dbNumberFormat = usCulture.NumberFormat;
decimal number = decimal.Parse(db.numberString, dbNumberFormat);
This will work fine anywhere on the world. And please don't use 'Convert.ToXxxx'. The 'Convert' class is thought only as a base for conversions in any direction. Besides: You may use the similar mechanism for DateTimes too.
Find out which version of Python is installed by issuing the command python --version: $ python --version Python 2.7.10
If you see something like this, Python 2.7 is your default version. You can also see if you have Python 3 installed:
$ python3 --version
Python 3.7.2
If you also want to know the path where it is installed, you can issue the command "which" with python and python3:
$ which python
/usr/bin/python
$ which python3
/usr/local/bin/python3
I created an ExecutionTime class out of phihag answer that you can use out of box:
class ExecutionTime
{
private $startTime;
private $endTime;
public function start(){
$this->startTime = getrusage();
}
public function end(){
$this->endTime = getrusage();
}
private function runTime($ru, $rus, $index) {
return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
- ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
}
public function __toString(){
return "This process used " . $this->runTime($this->endTime, $this->startTime, "utime") .
" ms for its computations\nIt spent " . $this->runTime($this->endTime, $this->startTime, "stime") .
" ms in system calls\n";
}
}
usage:
$executionTime = new ExecutionTime();
$executionTime->start();
// code
$executionTime->end();
echo $executionTime;
Note: In PHP 5, the getrusage function only works in Unix-oid systems. Since PHP 7, it also works on Windows.
I've not seen this solution presented yet; this is my preference for its simpler readability:
select dateadd(month,-1,format(getutcdate(),'yyyy-MM-01'))
#########################################################
# Memory Aid
# environment HOME=$HOME SHELL=$SHELL LOGNAME=$LOGNAME PATH=$PATH
#########################################################
#
# string meaning
# ------ -------
# @reboot Run once, at startup.
# @yearly Run once a year, "0 0 1 1 *".
# @annually (same as @yearly)
# @monthly Run once a month, "0 0 1 * *".
# @weekly Run once a week, "0 0 * * 0".
# @daily Run once a day, "0 0 * * *".
# @midnight (same as @daily)
# @hourly Run once an hour, "0 * * * *".
#mm hh Mday Mon Dow CMD # minute, hour, month-day month DayofW CMD
#........................................Minute of the hour
#| .................................Hour in the day (0..23)
#| | .........................Day of month, 1..31 (mon,tue,wed)
#| | | .................Month (1.12) Jan, Feb.. Dec
#| | | | ........day of the week 0-6 7==0
#| | | | | |command to be executed
#V V V V V V
* * 28-31 * * [ `date -d +'1 day' +\%d` -eq 1 ] && echo "Tomorrow is the first today now is `date`" >> ~/message
1 0 1 * * rm -f ~/message
* * 28-31 * * [ `date -d +'1 day' +\%d` -eq 1 ] && echo "HOME=$HOME LOGNAME=$LOGNAME SHELL = $SHELL PATH=$PATH"
Follow these steps:
As for this date (February 2017), it seems that mailchimp has integrated something similar to what gbinflames suggests into their own javascript generated form.
You don't need any further intervention now as mailchimp will convert the form to an ajax submitted one when javascript is enabled.
All you need to do now is just paste the generated form from the embed menu into your html page and NOT modify or add any other code.
This simply works. Thanks MailChimp!
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
Quite easy... You're doing it wrong, because by that event the control is not there:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
// Here you will get the Control you need like:
DropDownList dl = (DropDownList)e.Row.FindControl("ddlPBXTypeNS");
}
}
That is, it will only be valid for a DataRow
(the actually row with data), and if it's in Edit mode... because you only edit one row at a time. The e.Row.FindControl("ddlPBXTypeNS")
will only find the control that you want.
Just to include new Python f String compatible functionality:
var_a = 10
f"""This is my quoted variable: "{var_a}". """
simple and easy
Locale locale = new Locale("en", "US");
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = locale;
res.updateConfiguration(conf, dm);
where "en" is language code and "US" is country code.
Don't have sql server around to test but I think it's just:
insert into newtable select * from oldtable;
Use Google Maps JavaScript API with places library to implement Google Maps Autocomplete search box in the webpage.
HTML
<input id="searchInput" class="controls" type="text" placeholder="Enter a location">
JavaScript
<script>
function initMap() {
var input = document.getElementById('searchInput');
var autocomplete = new google.maps.places.Autocomplete(input);
}
</script>
Complete guide, source code, and live demo can be found from here - Google Maps Autocomplete Search Box with Map and Info Window
Here is the code you can use for every browser:
<embed src="pdfFiles/interfaces.pdf" width="600" height="500" alt="pdf" pluginspage="http://www.adobe.com/products/acrobat/readstep2.html">
Tested on firefox and chrome
This response isn't about macro war, but producing error if no matching platform is found.
#ifdef LINUX_KEY_WORD
... // linux code goes here.
#elif WINDOWS_KEY_WORD
... // windows code goes here.
#else
#error Platform not supported
#endif
If #error
is not supported, you may use static_assert (C++0x) keyword. Or you may implement custom STATIC_ASSERT, or just declare an array of size 0, or have switch that has duplicate cases. In short, produce error at compile time and not at runtime
For those searching for a solution to the issue of the ripple effect not working on a programmatically created CardView (or in my case custom view which extends CardView) being shown in a RecyclerView, the following worked for me. Basically declaring the XML attributes mentioned in the other answers declaratively in the XML layout file doesn't seem to work for a programmatically created CardView, or one created from a custom layout (even if root view is CardView or merge element is used), so they have to be set programmatically like so:
private class MadeUpCardViewHolder extends RecyclerView.ViewHolder {
private MadeUpCardView cardView;
public MadeUpCardViewHolder(View v){
super(v);
this.cardView = (MadeUpCardView)v;
// Declaring in XML Layout doesn't seem to work in RecyclerViews
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int[] attrs = new int[]{R.attr.selectableItemBackground};
TypedArray typedArray = context.obtainStyledAttributes(attrs);
int selectableItemBackground = typedArray.getResourceId(0, 0);
typedArray.recycle();
this.cardView.setForeground(context.getDrawable(selectableItemBackground));
this.cardView.setClickable(true);
}
}
}
Where MadeupCardView extends CardView
Kudos to this answer for the TypedArray
part.
Answer is given in many ways. You can also use ofArgb(startColor,endColor)
of ValueAnimator
.
for API > 21:
int cyanColorBg = ContextCompat.getColor(this,R.color.cyan_bg);
int purpleColorBg = ContextCompat.getColor(this,R.color.purple_bg);
ValueAnimator valueAnimator = ValueAnimator.ofArgb(cyanColorBg,purpleColorBg);
valueAnimator.setDuration(500);
valueAnimator.setInterpolator(new LinearInterpolator());
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
relativeLayout.setBackgroundColor((Integer)valueAnimator.getAnimatedValue());
}
});
valueAnimator.start();
To expand a bit on why the error happened: A forward slash at the beginning of a path means "start from the root of the filesystem, and look for the given path". No forward slash means "start from the current working directory, and look for the given path".
The path
/tmp/test.jpg
thus translates to looking for the file test.jpg in the tmp folder at the root of the filesystem (e.g. c:\ on windows, / on *nix), instead of the webapp folder. Adding a period (.) in front of the path explicitly changes this to read "start from the current working directory", but is basically the same as leaving the forward slash out completely.
./tmp/test.jpg = tmp/test.jpg
Now that pandas' indexes support string operations, arguably the simplest and best way to select columns beginning with 'foo' is just:
df.loc[:, df.columns.str.startswith('foo')]
Alternatively, you can filter column (or row) labels with df.filter()
. To specify a regular expression to match the names beginning with foo.
:
>>> df.filter(regex=r'^foo\.', axis=1)
foo.aa foo.bars foo.fighters foo.fox foo.manchu
0 1.0 0 0 2 NA
1 2.1 0 1 4 0
2 NaN 0 NaN 1 0
3 4.7 0 0 0 0
4 5.6 0 0 0 0
5 6.8 1 0 5 0
To select only the required rows (containing a 1
) and the columns, you can use loc
, selecting the columns using filter
(or any other method) and the rows using any
:
>>> df.loc[(df == 1).any(axis=1), df.filter(regex=r'^foo\.', axis=1).columns]
foo.aa foo.bars foo.fighters foo.fox foo.manchu
0 1.0 0 0 2 NA
1 2.1 0 1 4 0
2 NaN 0 NaN 1 0
5 6.8 1 0 5 0
In my case artifactory was down. npm install command is throwing below error.
npm ERR! registry error parsing json
In general URIs as defined by RFC 3986 (see Section 2: Characters) may contain any of the following 84 characters:
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=
Note that this list doesn't state where in the URI these characters may occur.
Any other character needs to be encoded with the percent-encoding (%
hh
). Each part of the URI has further restrictions about what characters need to be represented by an percent-encoded word.
If you want to confirm if focus is with an element then
if ($('#inputId').is(':focus')) {
//your code
}
Good morning.
I was have the same problem with upload of multiple images. Solution was more simple than I had imagined: include [] in the name field.
<input type="file" name="files[]" multiple>
I did not make any modification on FormData.
In R, you can assign your own operators using %[characters]%
. A trivial example:
'%p%' <- function(x, y){x^2 + y}
2 %p% 3 # result: 7
While I agree with BlueTrin that %%
is pretty standard, I have a suspicion %/%
may have something to do with the sort of operator definitions I showed above - perhaps it was easier to implement, and makes sense: %/%
means do a special sort of division (integer division)
Since you only want to remove the $ sign in all column names, you could just do:
df = df.rename(columns=lambda x: x.replace('$', ''))
OR
df.rename(columns=lambda x: x.replace('$', ''), inplace=True)
resource_url = 'http://localhost:8080/service/'
response = json.loads(urllib2.urlopen(resource_url).read())
df.domain.value_counts()
>>> df.domain.value_counts()
vk.com 5
twitter.com 2
google.com 1
facebook.com 1
Name: domain, dtype: int64
Swift 4
Based on https://stackoverflow.com/a/32513578/5391914
import UIKit
enum ViewBorder: String {
case Left = "borderLeft"
case Right = "borderRight"
case Top = "borderTop"
case Bottom = "borderBottom"
}
extension UIView {
func addBorder(vBorders: [ViewBorder], color: UIColor, width: CGFloat) {
vBorders.forEach { vBorder in
let border = CALayer()
border.backgroundColor = color.cgColor
border.name = vBorder.rawValue
switch vBorder {
case .Left:
border.frame = CGRect(x: 0, y: 0, width: width, height: self.frame.size.height)
case .Right:
border.frame = CGRect(x:self.frame.size.width - width, y: 0, width: width, height: self.frame.size.height)
case .Top:
border.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: width)
case .Bottom:
border.frame = CGRect(x: 0, y: self.frame.size.height - width , width: self.frame.size.width, height: width)
}
self.layer.addSublayer(border)
}
}
}
You should use Linking
.
Example from the docs:
class OpenURLButton extends React.Component {
static propTypes = { url: React.PropTypes.string };
handleClick = () => {
Linking.canOpenURL(this.props.url).then(supported => {
if (supported) {
Linking.openURL(this.props.url);
} else {
console.log("Don't know how to open URI: " + this.props.url);
}
});
};
render() {
return (
<TouchableOpacity onPress={this.handleClick}>
{" "}
<View style={styles.button}>
{" "}<Text style={styles.text}>Open {this.props.url}</Text>{" "}
</View>
{" "}
</TouchableOpacity>
);
}
}
Here's an example you can try on Expo Snack:
import React, { Component } from 'react';
import { View, StyleSheet, Button, Linking } from 'react-native';
import { Constants } from 'expo';
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Button title="Click me" onPress={ ()=>{ Linking.openURL('https://google.com')}} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
});
I see .btn:focus
has an outline
on it:
.btn:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
Try changing this to:
.btn:focus {
outline: none !important;
}
Basically, look for any instances of outline
on :focus
ed elements — that's what's causing it.
Update - For Bootstrap v4:
.btn:focus {
box-shadow: none;
}
!!(24%1) // false
!!(24.2%1) // true
I found the best way: I always check the latest branch created by this way
git for-each-ref --sort=-committerdate refs/heads/
Copied from http://technet.microsoft.com/en-us/library/cc750354.aspx
What's FAT?
FAT may sound like a strange name for a file system, but it's actually an acronym for File Allocation Table. Introduced in 1981, FAT is ancient in computer terms. Because of its age, most operating systems, including Microsoft Windows NT®, Windows 98, the Macintosh OS, and some versions of UNIX, offer support for FAT.
The FAT file system limits filenames to the 8.3 naming convention, meaning that a filename can have no more than eight characters before the period and no more than three after. Filenames in a FAT file system must also begin with a letter or number, and they can't contain spaces. Filenames aren't case sensitive.
What About VFAT?
Perhaps you've also heard of a file system called VFAT. VFAT is an extension of the FAT file system and was introduced with Windows 95. VFAT maintains backward compatibility with FAT but relaxes the rules. For example, VFAT filenames can contain up to 255 characters, spaces, and multiple periods. Although VFAT preserves the case of filenames, it's not considered case sensitive.
When you create a long filename (longer than 8.3) with VFAT, the file system actually creates two different filenames. One is the actual long filename. This name is visible to Windows 95, Windows 98, and Windows NT (4.0 and later). The second filename is called an MS-DOS® alias. An MS-DOS alias is an abbreviated form of the long filename. The file system creates the MS-DOS alias by taking the first six characters of the long filename (not counting spaces), followed by the tilde [~] and a numeric trailer. For example, the filename Brien's Document.txt would have an alias of BRIEN'~1.txt.
An interesting side effect results from the way VFAT stores its long filenames. When you create a long filename with VFAT, it uses one directory entry for the MS-DOS alias and another entry for every 13 characters of the long filename. In theory, a single long filename could occupy up to 21 directory entries. The root directory has a limit of 512 files, but if you were to use the maximum length long filenames in the root directory, you could cut this limit to a mere 24 files. Therefore, you should use long filenames very sparingly in the root directory. Other directories aren't affected by this limit.
You may be wondering why we're discussing VFAT. The reason is it's becoming more common than FAT, but aside from the differences I mentioned above, VFAT has the same limitations. When you tell Windows NT to format a partition as FAT, it actually formats the partition as VFAT. The only time you'll have a true FAT partition under Windows NT 4.0 is when you use another operating system, such as MS-DOS, to format the partition.
FAT32
FAT32 is actually an extension of FAT and VFAT, first introduced with Windows 95 OEM Service Release 2 (OSR2). FAT32 greatly enhances the VFAT file system but it does have its drawbacks.
The greatest advantage to FAT32 is that it dramatically increases the amount of free hard disk space. To illustrate this point, consider that a FAT partition (also known as a FAT16 partition) allows only a certain number of clusters per partition. Therefore, as your partition size increases, the cluster size must also increase. For example, a 512-MB FAT partition has a cluster size of 8K, while a 2-GB partition has a cluster size of 32K.
This may not sound like a big deal until you consider that the FAT file system only works in single cluster increments. For example, on a 2-GB partition, a 1-byte file will occupy the entire cluster, thereby consuming 32K, or roughly 32,000 times the amount of space that the file should consume. This rule applies to every file on your hard disk, so you can see how much space can be wasted.
Converting a partition to FAT32 reduces the cluster size (and overcomes the 2-GB partition size limit). For partitions 8 GB and smaller, the cluster size is reduced to a mere 4K. As you can imagine, it's not uncommon to gain back hundreds of megabytes by converting a partition to FAT32, especially if the partition contains a lot of small files.
Note: This section of the quote/ article (1999) is out of date. Updated info quote below.
As I mentioned, FAT32 does have limitations. Unfortunately, it isn't compatible with any operating system other than Windows 98 and the OSR2 version of Windows 95. However, Windows 2000 will be able to read FAT32 partitions.
The other disadvantage is that your disk utilities and antivirus software must be FAT32-aware. Otherwise, they could interpret the new file structure as an error and try to correct it, thus destroying data in the process.
Finally, I should mention that converting to FAT32 is a one-way process. Once you've converted to FAT32, you can't convert the partition back to FAT16. Therefore, before converting to FAT32, you need to consider whether the computer will ever be used in a dual-boot environment. I should also point out that although other operating systems such as Windows NT can't directly read a FAT32 partition, they can read it across the network. Therefore, it's no problem to share information stored on a FAT32 partition with other computers on a network that run older operating systems.
Updated mentioned in comment by Doktor-J (assimilated to update out of date answer in case comment is ever lost):
I'd just like to point out that most modern operating systems (WinXP/Vista/7/8, MacOS X, most if not all Linux variants) can read FAT32, contrary to what the second-to-last paragraph suggests.
The original article was written in 1999, and being posted on a Microsoft website, probably wasn't concerned with non-Microsoft operating systems anyways.
The operating systems "excluded" by that paragraph are probably the original Windows 95, Windows NT 4.0, Windows 3.1, DOS, etc.
In my case the /var/www/html in not a directory but a symbolic link to the /var/app/current, so you should change the real directoy ie /var/app/current:
sudo chown -R ec2-user /var/app/current
sudo chmod -R 755 /var/app/current
I hope this save some of your times :)
I've seen many variants of this problem. One of the main differences (that determines the difficulty) is whether there is some centralized attempt to have a "smart and efficient system" that would have load balancing (e.g., send more idle elevators to lobby in morning). If that is the case, the design will include a whole subsystem with really fun design.
A full design is obviously too much to present here and there are many altenatives. The breadth is also not clear. In an interview, they'll try to figure out how you would think. However, these are some of the things you would need:
Representation of the central controller (assuming there is one).
Representations of elevators
Representations of the interface units of the elevator (these may be different from elevator to elevator). Obviously also call buttons on every floor, etc.
Representations of the arrows or indicators on each floor (almost a "view" of the elevator model).
Representation of a human and cargo (may be important for factoring in maximal loads)
Representation of the building (in some cases, as certain floors may be blocked at times, etc.)
On Windows, with PowerShell, I had to close and reopen the console and then reactive the virtual environment.
I like André Kramer Orten's answer, very elegant, I particularly like how it avoids loops, I thought of another way to handle it also avoiding loops.
It uses integer division and modulo on the input to select the correct index from a hard-coded set of string arrays for each unit type.
The nice thing here is you can specify exact conversions depending on if you want the additive or subtractive numeral form i.e. IIII vs IV. Here I use the the "subtractive form" for all numbers in the form 5x-1 (4,9,14,19,40,90,etc)
It would also be trivial to extend this to allow for larger numbers by simply extending the thousands array with further additive or subtractive forms, i.e. "IV", "V" or "MMMM", "MMMMM"
For bonus points I actually make sure the number parameter is within the given range for the problem.
public class RomanNumeralGenerator {
static final int MIN_VALUE = 1;
static final int MAX_VALUE = 3999;
static final String[] RN_M = {"", "M", "MM", "MMM"};
static final String[] RN_C = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
static final String[] RN_X = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
static final String[] RN_I = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
public String generate(int number) {
if (number < MIN_VALUE || number > MAX_VALUE) {
throw new IllegalArgumentException(
String.format(
"The number must be in the range [%d, %d]",
MIN_VALUE,
MAX_VALUE
)
);
}
return new StringBuilder()
.append(RN_M[number / 1000])
.append(RN_C[number % 1000 / 100])
.append(RN_X[number % 100 / 10])
.append(RN_I[number % 10])
.toString();
}
}
You need to append your variables to the echoed string. For example:
echo 'This is a string '.$PHPvariable.' and this is more string';
When your browser redirects the user to Google's oAuth page, are you passing as a parameter the redirect URI you want Google's server to return to with the token response? Setting a redirect URI in the console is not a way of telling Google where to go when a login attempt comes in, but rather it's a way of telling Google what the allowed redirect URIs are (so if someone else writes a web app with your client ID but a different redirect URI it will be disallowed); your web app should, when someone clicks the "login" button, send the browser to:
https://accounts.google.com/o/oauth2/auth?client_id=XXXXX&redirect_uri=http://localhost:8080/WEBAPP/youtube-callback.html&response_type=code&scope=https://www.googleapis.com/auth/youtube.upload
(the callback URI passed as a parameter must be url-encoded, btw).
When Google's server gets authorization from the user, then, it'll redirect the browser to whatever you sent in as the redirect_uri
. It'll include in that request the token as a parameter, so your callback page can then validate the token, get an access token, and move on to the other parts of your app.
If you visit:
http://code.google.com/p/google-api-java-client/wiki/OAuth2#Authorization_Code_Flow
You can see better samples of the java client there, demonstrating that you have to override the getRedirectUri
method to specify your callback path so the default isn't used.
The redirect URIs are in the client_secrets.json
file for multiple reasons ... one big one is so that the oAuth flow can verify that the redirect your app specifies matches what your app allows.
If you visit https://developers.google.com/api-client-library/java/apis/youtube/v3 You can generate a sample application for yourself that's based directly off your app in the console, in which (again) the getRedirectUri method is overwritten to use your specific callbacks.
int space = 40;
printf("%*s", space, "Hello");
This statement will reserve a row of 40 characters, print string at the end of the row (removing extra spaces such that the total row length is constant at 40). Same can be used for characters and integers as follows:
printf("%*d", space, 10);
printf("%*c", space, 'x');
This method using a parameter to determine spaces is useful where a variable number of spaces is required. These statements will still work with integer literals as follows:
printf("%*d", 10, 10);
printf("%*c", 20, 'x');
printf("%*s", 30, "Hello");
Hope this helps someone like me in future.
For Ionic 4 Just
$ cordova clean
Helped me then run
$ ionic cordova run android --device
Scaffold(
appBar: AppBar(
title: Text('BMI CALCULATOR'),
),
body: Container(
height: 200,
width: 170,
margin: EdgeInsets.all(15),
decoration: BoxDecoration(
color: Color(
0xFF1D1E33,
),
borderRadius: BorderRadius.circular(5),
),
),
);
Technically this FQL query should work, but for some reason Facebook disallows it because of a missing index. Not sure if that is because of policy or they just forgot.
SELECT uid FROM page_fans WHERE page_id="YOUR_PAGE_ID"
void transfer(double x) {
unsigned long long* p = (unsigned long long*)&x;
for (int i = sizeof(unsigned long long) * 8 - 1; i >= 0; i--) {cout<< ((*p) >>i & 1);}}
One thing I found is the path of your image must be relative to wherever the notebook was originally loaded from. if you cd to a different directory, such as Pictures your Markdown path is still relative to the original loading directory.
If anyone want to use only number from 0 to 9 with imeOptions
enable then use below line in your EditText
android:inputType="number|none"
This will only allow number and if you click on done/next button of keyboard your focus will move to next field.
Try this. It's works for me well.
function clicked(item) {
alert($(item).attr("id"));
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-rtl/3.4.0/css/bootstrap-rtl.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<button onclick="clicked(this);" id="modalME">Click me</button>
<!-- Modal -->
<div class="modal" id="modalME" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-header">
<h2>Modal in CSS</h2>
<a href="#close" class="btn-close" aria-hidden="true">×</a> <!--CHANGED TO "#close"-->
</div>
<div class="modal-body">
<p>One modal example here.</p>
</div>
<div class="modal-footer">
<a href="#close" class="btn">Nice!</a> <!--CHANGED TO "#close"-->
</div>
</div>
</div>
</div>
<!-- /Modal -->
_x000D_
DEMO: http://jsfiddle.net/kF2uK/2/
function buttonState(){
$("input").each(function(){
$('#register').attr('disabled', 'disabled');
if($(this).val() == "" ) return false;
$('#register').attr('disabled', '');
})
}
$(function(){
$('#register').attr('disabled', 'disabled');
$('input').change(buttonState);
})
type sqlplus/"as sysdba" in cmd for connection in cmd prompt
Final working solution using @Arrigo response and @Samitha Chathuranga comment, I'll put all together to build a full response for this question:
Open Git CMD console and type command 1 from second picture(go to your project folder on your PC)
Type command git init
Type command git add --all
Type command 2 from second picture (git remote add origin YOUR_LINK_TO_REPO
)
Type command git commit -m "my first commit"
Type command git push -u origin master
Note: if you get error unable to detect email or name, just type following commands after 5th step:
git config --global user.email "yourEmail" #your email at Bitbucket
git config --global user.name "yourName" #your name at Bitbucket
The current release of SharpDevelop (3.1.1) has a nice integrated profiler. It's quite fast, and integrates very well into the SharpDevelop IDE and its NUnit runner. Results are displayed in a flexible Tree/List style (use LINQ to create your own selection). Doubleclicking the displayed method jumps directly into the source code.
Another approach is using Self Organizing Maps (SOP) to find optimal number of clusters. The SOM (Self-Organizing Map) is an unsupervised neural network methodology, which needs only the input is used to clustering for problem solving. This approach used in a paper about customer segmentation.
The reference of the paper is
Abdellah Amine et al., Customer Segmentation Model in E-commerce Using Clustering Techniques and LRFM Model: The Case of Online Stores in Morocco, World Academy of Science, Engineering and Technology International Journal of Computer and Information Engineering Vol:9, No:8, 2015, 1999 - 2010
Sometimes plain arrays are preferred to Generic Lists, since they are more convenient (Better performance for costly computation -Numerical Algebra Applications for example, or for exchanging Data with Statistics software like R or Matlab)
In this case you may use the ToArray() method after initiating your List dynamically
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
string[] array = list.ToArray();
Of course, this has sense only if the size of the array is never known nor fixed ex-ante. if you already know the size of your array at some point of the program it is better to initiate it as a fixed length array. (If you retrieve data from a ResultSet for example, you could count its size and initiate an array of that size, dynamically)
There is also a nice implementation described here by McEwan and @StefanGustavson that looks like Perlin noise, but "does not require any setup, i.e. not textures nor uniform arrays. Just add it to your shader source code and call it wherever you want".
That's very handy, especially given that Gustavson's earlier implementation, which @dep linked to, uses a 1D texture, which is not supported in GLSL ES (the shader language of WebGL).
Why not loop through the inputs and then add onclick handlers to each?
You don't have to do this in HTML, but you can add a handler to each button like:
button.onclick = function(){ DoStuff(this.value); return false; } // return false; so that form does not submit
Then your function could "do stuff" according to whichever value you passed:
function DoStuff(val) {
if( val === "Val 1" ) {
// Do some stuff
}
// Do other stuff
}
You are better off running the command in the console to get a better idea on what is wrong with the settings. In my case, when I ran gradlew check
it actually tells me which referenced project was missing.
* What went wrong:
Could not determine the dependencies of task ':test'.
Could not resolve all task dependencies for configuration ':testRuntimeClasspath'.
Could not resolve project :lib-blah.
Required by:
project :
> Unable to find a matching configuration of project :lib-blah: None of the consumable configurations have attributes.
The annoying thing was that, it would not show any meaningful error message during the import failure. And if I commented out all the project references, sure it let me import it, but then once I uncomment it out, it would only print that ambiguous message and not tell you what is wrong.
Sometimes if you only needs the values to be enumerated, use the dictionary's value collection:
foreach(var value in dictionary.Values)
{
// do something with entry.Value only
}
Reported by this post which states it is the fastest method: http://alexpinsker.blogspot.hk/2010/02/c-fastest-way-to-iterate-over.html
The Splatting Operator
To create an array, we create a variable and assign the array. Arrays are noted by the "@" symbol. Let's take the discussion above and use an array to connect to multiple remote computers:
$strComputers = @("Server1", "Server2", "Server3")<enter>
They are used for arrays and hashes.
ADD:
LIMIT n,1
That will limit the results to one result starting at result n.
Try this
<div *ngFor="let piece of allPieces; let i=index">
{{i}} // this will give index
</div>
Hopefully, this will be of value to someone out there - I went through half a dozen stackoverflow posts trying to figure out relative imports similar to whats posted above here. I set up everything as suggested but I was still hitting ModuleNotFoundError: No module named 'my_module_name'
Since I was just developing locally and playing around, I hadn't created/run a setup.py
file. I also hadn't apparently set my PYTHONPATH
.
I realized that when I ran my code as I had been when the tests were in the same directory as the module, I couldn't find my module:
$ python3 test/my_module/module_test.py 2.4.0
Traceback (most recent call last):
File "test/my_module/module_test.py", line 6, in <module>
from my_module.module import *
ModuleNotFoundError: No module named 'my_module'
However, when I explicitly specified the path things started to work:
$ PYTHONPATH=. python3 test/my_module/module_test.py 2.4.0
...........
----------------------------------------------------------------------
Ran 11 tests in 0.001s
OK
So, in the event that anyone has tried a few suggestions, believes their code is structured correctly and still finds themselves in a similar situation as myself try either of the following if you don't export the current directory to your PYTHONPATH:
$ PYTHONPATH=. python3 test/my_module/module_test.py
PYTHONPATH=.
, create a setup.py
file with contents like the following and run python setup.py development
to add packages to the path:# setup.py from setuptools import setup, find_packages setup( name='sample', packages=find_packages() )
Had a similar problem when find an object by id... All i did was to use the fully qualified name in the class name. That is Before it was :
find("Class",id)
Object so it became like this :
find("assemblyName.Class",id)
The method you are looking for is .limit.
Returns a new Dataset by taking the first n rows. The difference between this function and head is that head returns an array while limit returns a new Dataset.
Example usage:
df.limit(1000)
Go to command prompt and enter the command,
net user <username>
Will show your local group memberships.
If you're on a domain, use localgroup instead:
net localgroup Administrators or net localgroup [Admin group name]
Check the list of local groups with localgroup on its own.
net localgroup
Update the central repository of Maven and use https instead of http.
<repositories>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
You will need a custom class loader for this, have a look at One Jar.
One-JAR lets you package a Java application together with its dependency Jars into a single executable Jar file.
It has an ant task which can simplify the building of it as well.
REFERENCE (from background)
Most developers reasonably assume that putting a dependency Jar file into their own Jar file, and adding a Class-Path attribute to the META-INF/MANIFEST will do the trick:
jarname.jar
| /META-INF
| | MANIFEST.MF
| | Main-Class: com.mydomain.mypackage.Main
| | Class-Path: commons-logging.jar
| /com/mydomain/mypackage
| | Main.class
| commons-logging.jar
Unfortunately this is does not work. The Java
Launcher$AppClassLoader
does not know how to load classes from a Jar inside a Jar with this kind ofClass-Path
. Trying to usejar:file:jarname.jar!/commons-logging.jar
also leads down a dead-end. This approach will only work if you install (i.e. scatter) the supporting Jar files into the directory where the jarname.jar file is installed.
Old thread, but learned something new, hope this might help someone.
If you want to change the background color but retain other styles, then below might help.
button.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.colorAccent), PorterDuff.Mode.MULTIPLY);
WAMP Server may turn orange for various reason as it is not working. This is also a another type of issue. that can be due to webservices is running in services.msc This is explained in the below blog. Please try it. How to resolve HTTP Error 404 and launch localhost with WAMP Server for PHP & MySql?
Also; auto it = std::next(v.begin(), index);
Update: Needs a C++11x compliant compiler
You could use a variable to make the calculation and use toFixed
when you set the #diskamountUnit
element value:
var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));
You can also do that in one step, in the val
method call but IMO the first way is more readable:
$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));
I know three ways to swap variables, but a, b = b, a
is the simplest. There is
x = x ^ y
y = y ^ x
x = x ^ y
Or concisely,
x ^= y
y ^= x
x ^= y
w = x
x = y
y = w
del w
x, y = y, x
how about:
while(locations.Any())
{
list.Add(locations.Take(nSize).ToList());
locations= locations.Skip(nSize).ToList();
}
To find the AWS_SECRET_ACCESS_KEY Its better to create new create "IAM" user Here is the steps https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html 1. Sign in to the AWS Management Console and open the IAM console at https://console.aws.amazon.com/iam/.
Total no of Binary Trees are =
Summing over i gives the total number of binary search trees with n nodes.
The base case is t(0) = 1 and t(1) = 1, i.e. there is one empty BST and there is one BST with one node.
So, In general you can compute total no of Binary Search Trees using above formula. I was asked a question in Google interview related on this formula. Question was how many total no of Binary Search Trees are possible with 6 vertices. So Answer is t(6) = 132
I think that I gave you some idea...
also, to get the right arrow, right click and "Add as Library".
That's:
SELECT * FROM Header
WHERE (userID LIKE '%''%')
This will occur in SQL Server as well if you don't run all of the statements at once. If you are highlighting a set of statements and executing the following:
DECLARE @LoopVar INT
SET @LoopVar = (SELECT COUNT(*) FROM SomeTable)
And then try to highlight another set of statements such as:
PRINT 'LoopVar is: ' + CONVERT(NVARCHAR(255), @LoopVar)
You will receive this error.
The excellent (free trial) IcoFX allows you to create and edit icons, including multiple sizes up to 256x256, PNG compression, and transparency. I highly recommend it over most of the alternates.
Get your copy here: http://icofx.ro/ . It supports Windows XP onwards.
Windows automatically chooses the proper icon from the file, depending on where it is to be displayed.
For more information on icon design and the sizes/bit depths you should include, see these references:
I ended up using GitKraken . I've installed, auth and connected to my repo in 30 seconds.
From the selectors specification:
Attribute values must be CSS identifiers or strings.
Identifiers cannot start with a number. Strings must be quoted.
1
is therefore neither a valid identifier nor a string.
Use "1"
(which is a string) instead.
var a = document.querySelector('a[data-a="1"]');
I tried svn rm --force /path/to/dir
to no avail but ended up just running svn up
and it fixed it for me.
If you are dealing with more dynamic screen resolution/sizes, instead of hardcoding the size in pixels you can change the width to a percentage of the media width as such
@media (min-width: 1200px) {
.container{
max-width: 70%;
}
}
In Informix, you can use:
RENAME COLUMN TableName.OldName TO NewName;
This was implemented before the SQL standard addressed the issue - if it is addressed in the SQL standard. My copy of the SQL 9075:2003 standard does not show it as being standard (amongst other things, RENAME is not one of the keywords). I don't know whether it is actually in SQL 9075:2008.
Adding to the top voted answer and many ones above stressing the "more generic, better", I would like to dig a little bit more.
Map
is the structure contract while HashMap
is an implementation providing its own methods to deal with different real problems: how to calculate index, what is the capacity and how to increment it, how to insert, how to keep the index unique, etc.
Let's look into the source code:
In Map
we have the method of containsKey(Object key)
:
boolean containsKey(Object key);
JavaDoc:
boolean java.util.Map.containsValue(Object value)
Returns true if this map maps one or more keys to the specified value. More formally, returns true if and only if this map contains at least one mapping to a value
v
such that(value==null ? v==null : value.equals(v))
. This operation will probably require time linear in the map size for most implementations of the Map interface.Parameters:value
value whose presence in this map is to betested
Returns:true
if this map maps one or more keys to the specified
valueThrows:
ClassCastException - if the value is of an inappropriate type for this map (optional)
NullPointerException - if the specified value is null and this map does not permit null values (optional)
It requires its implementations to implement it, but the "how to" is at its freedom, only to ensure it returns correct.
In HashMap
:
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
It turns out that HashMap
uses hashcode to test if this map contains the key. So it has the benefit of hash algorithm.
You can also check the .Any()
method:
if (!YourResult.Any())
Just a note that .Any
will still retrieve the records from the database; doing a .FirstOrDefault()/.Where()
will be just as much overhead but you would then be able to catch the object(s) returned from the query
In addition to the "it is a value" answer, one specific scenario for using structs is when you know that you have a set of data that is causing garbage collection issues, and you have lots of objects. For example, a large list/array of Person instances. The natural metaphor here is a class, but if you have large number of long-lived Person instance, they can end up clogging GEN-2 and causing GC stalls. If the scenario warrants it, one potential approach here is to use an array (not list) of Person structs, i.e. Person[]
. Now, instead of having millions of objects in GEN-2, you have a single chunk on the LOH (I'm assuming no strings etc here - i.e. a pure value without any references). This has very little GC impact.
Working with this data is awkward, as the data is probably over-sized for a struct, and you don't want to copy fat values all the time. However, accessing it directly in an array does not copy the struct - it is in-place (contrast to a list indexer, which does copy). This means lots of work with indexes:
int index = ...
int id = peopleArray[index].Id;
Note that keeping the values themselves immutable will help here. For more complex logic, use a method with a by-ref parameter:
void Foo(ref Person person) {...}
...
Foo(ref peopleArray[index]);
Again, this is in-place - we have not copied the value.
In very specific scenarios, this tactic can be very successful; however, it is a fairly advanced scernario that should be attempted only if you know what you are doing and why. The default here would be a class.
Not all controls that can be included in a page must be run at the server. For example:
<INPUT type="submit" runat=server />
This is essentially the same as:
<asp:Button runat=server />
Remove the runat=server tag from the first one and you have a standard HTML button that runs in the browser. There are reasons for and against running a particular control at the server, and there is no way for ASP.NET to "assume" what you want based on the HTML markup you include. It might be possible to "infer" the runat=server for the <asp:XXX />
family of controls, but my guess is that Microsoft would consider that a hack to the markup syntax and ASP.NET engine.
request.input("name", sql.Decimal, 155.33) // decimal(18, 0)
request.input("name", sql.Decimal(10), 155.33) // decimal(10, 0)
request.input("name", sql.Decimal(10, 2), 155.33) // decimal(10, 2)
I've found more elegant solution here. Adapted to the question it may look like:
$neededObject = array_filter(
$arrayOfObjects,
function ($e) use ($searchedValue) {
return $e->id == $searchedValue;
}
);
To add primary key in the column.
ALTER TABLE table_name ADD PRIMARY KEY (column_name);
To remove primary key from the table.
ALTER TABLE table_name DROP PRIMARY KEY;
Create a custom authorization attribute based on AuthorizeAttribute and override OnAuthorization to perform the check how you want it done. Normally, AuthorizeAttribute will set the filter result to HttpUnauthorizedResult if the authorization check fails. You could have it set it to a ViewResult (of your Error view) instead.
EDIT: I have a couple of blog posts that go into more detail:
Example:
[AttributeUsage( AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false )]
public class MasterEventAuthorizationAttribute : AuthorizeAttribute
{
/// <summary>
/// The name of the master page or view to use when rendering the view on authorization failure. Default
/// is null, indicating to use the master page of the specified view.
/// </summary>
public virtual string MasterName { get; set; }
/// <summary>
/// The name of the view to render on authorization failure. Default is "Error".
/// </summary>
public virtual string ViewName { get; set; }
public MasterEventAuthorizationAttribute()
: base()
{
this.ViewName = "Error";
}
protected void CacheValidateHandler( HttpContext context, object data, ref HttpValidationStatus validationStatus )
{
validationStatus = OnCacheAuthorization( new HttpContextWrapper( context ) );
}
public override void OnAuthorization( AuthorizationContext filterContext )
{
if (filterContext == null)
{
throw new ArgumentNullException( "filterContext" );
}
if (AuthorizeCore( filterContext.HttpContext ))
{
SetCachePolicy( filterContext );
}
else if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
// auth failed, redirect to login page
filterContext.Result = new HttpUnauthorizedResult();
}
else if (filterContext.HttpContext.User.IsInRole( "SuperUser" ))
{
// is authenticated and is in the SuperUser role
SetCachePolicy( filterContext );
}
else
{
ViewDataDictionary viewData = new ViewDataDictionary();
viewData.Add( "Message", "You do not have sufficient privileges for this operation." );
filterContext.Result = new ViewResult { MasterName = this.MasterName, ViewName = this.ViewName, ViewData = viewData };
}
}
protected void SetCachePolicy( AuthorizationContext filterContext )
{
// ** IMPORTANT **
// Since we're performing authorization at the action level, the authorization code runs
// after the output caching module. In the worst case this could allow an authorized user
// to cause the page to be cached, then an unauthorized user would later be served the
// cached page. We work around this by telling proxies not to cache the sensitive page,
// then we hook our custom authorization code into the caching mechanism so that we have
// the final say on whether a page should be served from the cache.
HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
cachePolicy.SetProxyMaxAge( new TimeSpan( 0 ) );
cachePolicy.AddValidationCallback( CacheValidateHandler, null /* data */);
}
}
There's now an EMPTY
constant and an empty
function.
import { Observable, empty, of } from 'rxjs';
var delay = empty().pipe(delay(1000));
var delay2 = EMPTY.pipe(delay(1000));
Observable.empty()
doesn't exist anymore.
Edit
A better way to do this is:
Create your own less file as a main less file ( like bootstrap.less ).
Import all bootstrap less files you need. (in this case, you just need to Import all responsive less files but responsive-1200px-min.less
)
If you need to modify anything in original bootstrap less file, you just need to write your own less to overwrite bootstrap's less code. (Just remember to put your less code/file after @import { /* bootstrap's less file */ };
).
Original
I have the same problem. This is how I fixed it.
Find the media query:
@media (max-width:1200px) ...
Remove it. (I mean the whole thing , not just @media (max-width:1200px)
)
Since the default width of Bootstrap is 940px, you don't need to do anything.
If you want to have your own max-width
, just modify the css rule in the media query that matches your desired width.
Just use inline if operation with tuple function:
query = "Select * from hr_employee WHERE id in " % tuple(employee_ids) if len(employee_ids) != 1 else "("+ str(employee_ids[0]) + ")"
TreeMap
is an example of a SortedMap
, which means that the order of the keys can be sorted, and when iterating over the keys, you can expect that they will be in order.
HashMap
on the other hand, makes no such guarantee. Therefore, when iterating over the keys of a HashMap
, you can't be sure what order they will be in.
HashMap
will be more efficient in general, so use it whenever you don't care about the order of the keys.
This depends not only on the operating system in question, but also on configuration, potentially real-time configuration.
For Linux:
cat /proc/sys/fs/file-max
will show the current maximum number of file descriptors total allowed to be opened simultaneously. Check out http://www.cs.uwaterloo.ca/~brecht/servers/openfiles.html
Without the combined child selector you would probably do something similar to this:
foo {
bar {
baz {
color: red;
}
}
}
If you want to reproduce the same syntax with >
, you could to this:
foo {
> bar {
> baz {
color: red;
}
}
}
This compiles to this:
foo > bar > baz {
color: red;
}
Or in sass:
foo
> bar
> baz
color: red
I found the error because i was new to git you must check whether you have entered the correct syntax
i made a mistake and wrote
git commit
and got the same error
use
git commit -m 'some comment'
and you wont be seeing the page with
[^0-9][+-]?[0-9]{1,10}[^0-9]
In words: Optional + or - followed by a digit, repeated one up to ten times. Note that most libraries have a shortcut for a digit: \d
, hence the above could also be written as: \d{1,10}
.
I did not see this exact syntax posted yet, and it worked for me in an ES6/Webpack environment:
import $ from "jquery";
Taken directly from jQuery's NPM page. Hope this helps someone.
Note that if you've got your filesystem mounted with noatime for performance reasons, then the atime will likely show the creation time. Given that noatime results in a massive performance boost (by removing a disk write for every time a file is read), it may be a sensible configuration option that also gives you the results you want.
use new JavaScriptSerializer().Deserialize<object>(jsonString)
You need System.Web.Extensions dll and import the following namespace.
Namespace: System.Web.Script.Serialization
for more info MSDN
Quotes, but I prefer them on the just the value:
url: "http://www.example.com/"
Putting them across the whole line looks like it might cause problems.
Try like below with Gson
Library.
Earlier Conversion List format were:
[Product [Id=1, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=32 inches, Price=33500.5, Stock=17.0], Product [Id=2, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=42 inches, Price=41850.0, Stock=9.0]]
and here the conversion source begins.
//** Note I have created the method toString() in Product class.
//Creating and initializing a java.util.List of Product objects
List<Product> productList = (List<Product>)productRepository.findAll();
//Creating a blank List of Gson library JsonObject
List<JsonObject> entities = new ArrayList<JsonObject>();
//Simply printing productList size
System.out.println("Size of productList is : " + productList.size());
//Creating a Iterator for productList
Iterator<Product> iterator = productList.iterator();
//Run while loop till Product Object exists.
while(iterator.hasNext()){
//Creating a fresh Gson Object
Gson gs = new Gson();
//Converting our Product Object to JsonElement
//Object by passing the Product Object String value (iterator.next())
JsonElement element = gs.fromJson (gs.toJson(iterator.next()), JsonElement.class);
//Creating JsonObject from JsonElement
JsonObject jsonObject = element.getAsJsonObject();
//Collecting the JsonObject to List
entities.add(jsonObject);
}
//Do what you want to do with Array of JsonObject
System.out.println(entities);
Converted Json Result is :
[{"Id":1,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"32 inches","Price":33500.5,"Stock":17.0}, {"Id":2,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"42 inches","Price":41850.0,"Stock":9.0}]
Hope this would help many guys!
Write the code in your viewDidLoad()
self.view.layer.borderColor = anyColor().CGColor
And you can set Color
with RGB
func anyColor() -> UIColor {
return UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
}
Learn something about CALayer
in UIKit
I know it has been quite sometime that you asked this but, if someone else needs, I did what was saying here " How to upload a project to Github " and after the top answer of this question right here. And after was the top answer was saying here "git error: failed to push some refs to" I don't know what exactly made everything work. But now is working.
The foo.bar
reference should not contain the braces:
<p ng-hide="foo.bar">I could be shown, or I could be hidden</p>
<p ng-show="foo.bar">I could be shown, or I could be hidden</p>
Angular expressions need to be within the curly-brace bindings, where as Angular directives do not.
See also Understanding Angular Templates.
If you use enterprise computer and unable to access system environments
use RapidEE to edit user variables then add to path these
%AppData%\npm
or
%USERPROFILE%\AppData\Roaming\npm
it worked for me on windows
Minor variation of phillfri's answer which was already a variation of Geoff's answer: I added the ability to handle completely empty tables that contain no data for the Array Code.
Sub AddDataRow(tableName As String, NewData As Variant)
Dim sheet As Worksheet
Dim table As ListObject
Dim col As Integer
Dim lastRow As Range
Set sheet = Range(tableName).Parent
Set table = sheet.ListObjects.Item(tableName)
'First check if the last row is empty; if not, add a row
If table.ListRows.Count > 0 Then
Set lastRow = table.ListRows(table.ListRows.Count).Range
If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
table.ListRows.Add
End If
End If
'Iterate through the last row and populate it with the entries from values()
If table.ListRows.Count = 0 Then 'If table is totally empty, set lastRow as first entry
table.ListRows.Add Position:=1
Set lastRow = table.ListRows(1).Range
Else
Set lastRow = table.ListRows(table.ListRows.Count).Range
End If
For col = 1 To lastRow.Columns.Count
If col <= UBound(NewData) + 1 Then lastRow.Cells(1, col) = NewData(col - 1)
Next col
End Sub
Maven already has a solution to do what you want:
Get MavenProject from just the POM.xml - pom parser?
btw: first hit at google search ;)
Model model = null;
FileReader reader = null;
MavenXpp3Reader mavenreader = new MavenXpp3Reader();
try {
reader = new FileReader(pomfile); // <-- pomfile is your pom.xml
model = mavenreader.read(reader);
model.setPomFile(pomfile);
}catch(Exception ex){
// do something better here
ex.printStackTrace()
}
MavenProject project = new MavenProject(model);
project.getProperties() // <-- thats what you need
JavaScript is a client-side language and your MySQL database is going to be running on a server.
So you have to rename your file to index.php
for example (.php is important) so you can use php code for that. It is not very difficult, but not directly possible with html.
(Somehow you can tell your server to let the html files behave like php files, but this is not the best solution.)
So after you renamed your file, go to the very top, before <html>
or <!DOCTYPE html>
and type:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
/*Creating variables*/
$name = $_POST["name"];
$address = $_POST["address"];
$age = $_POST["age"];
$dbhost = "localhost"; /*most of the time it's localhost*/
$username = "yourusername";
$password = "yourpassword";
$dbname = "mydatabase";
$mysql = mysqli_connect($dbhost, $username, $password, $dbname); //It connects
$query = "INSERT INTO yourtable (name,address,age) VALUES $name, $address, $age";
mysqli_query($mysql, $query);
}
?>
<!DOCTYPE html>
<html>
<head>.......
....
<form method="post">
<input name="name" type="text"/>
<input name="address" type="text"/>
<input name="age" type="text"/>
</form>
....
Your best bet is a tool that is specifically geared towards your problem. If it's processing text files, then Sed, Awk and Perl are the top contenders. Python is a general-purpose dynamic language. As with any general purpose language, there's support for file-manipulation, but that isn't what it's core purpose is. I would consider Python or Ruby if I had a requirement for a dynamic language in particular.
In short, learn Sed and Awk really well, plus all the other goodies that come with your flavour of *nix (All the Bash built-ins, grep, tr and so forth). If it's text file processing you're interested in, you're already using the right stuff.
I use a slightly modified version of kolbyjack's second approach with ~
instead of ~*
.
location ~ ^/service/ {
proxy_pass http://apache/$uri$is_args$args;
}
As mentioned in many posts, this is not directly possible, but an easy and successful way is as follows: First, we put a form in the body of our html page, which does not have any buttons for the submit, and also its inputs are hidden. Then we use a javascript function to get the data and ,send the form. One of the advantages of this method is to redirect to other pages, which depends on the server-side code. The code is as follows: and now in anywhere you need an to be in "POST" method:
<script type="text/javascript" language="javascript">
function post_link(data){
$('#post_form').find('#form_input').val(data);
$('#post_form').submit();
};
</script>
<form id="post_form" action="anywhere/you/want/" method="POST">
{% csrf_token %}
<input id="form_input" type="hidden" value="" name="form_input">
</form>
<a href="javascript:{}" onclick="javascript:post_link('data');">post link is ready</a>
You need to add C:\Python27
to your system PATH variable, not a new variable named "python".
Find the system PATH environment variable, and append to it a ;
(which is the delimiter) and the path to the directory containing python.exe (e.g. C:\Python27
). See below for exact steps.
The PATH environment variable lists all the locations that Windows (and cmd.exe
) will check when given the name of a command, e.g. "python" (it also uses the PATHEXT variable for a list of executable file extensions to try). The first executable file it finds on the PATH with that name is the one it starts.
Note that after changing this variable, there is no need to restart Windows, but only new instances of cmd.exe
will have the updated PATH. You can type set PATH
at the command prompt to see what the current value is.
Exact steps for adding Python to the path on Windows 7+:
Environment variables...
button (in the Advanced tab);C:\Python27
to the end (substitute your Python version)Use FirstOrDefault insted of SingleOrDefault..
SingleOrDefault returns a SINGLE element or null if no element is found. If 2 elements are found in your Enumerable then it throws the exception you are seeing
FirstOrDefault returns the FIRST element it finds or null if no element is found. so if there are 2 elements that match your predicate the second one is ignored
public int GetPackage(int id,int emp)
{
int getpackages=Convert.ToInt32(EmployerSubscriptionPackage.GetAllData().Where(x
=> x.SubscriptionPackageID ==`enter code here` id && x.EmployerID==emp ).FirstOrDefault().ID);
return getpackages;
}
1. var EmployerId = Convert.ToInt32(Session["EmployerId"]);
var getpackage = GetPackage(employerSubscription.ID, EmployerId);
Not exactly php, but you could exec a program from php to convert the pdf to a temporary html file and then parse the resulting file with php. I've done something similar for a project of mine and this is the program I used:
The resulting HTML wraps text elements in < div > tags with absolute position coordinates. It seems like this is exactly what you are trying to do.
Yes this topic is a bit old but i wanted to share the solution that worked for me for those who might need it anyway
As Ali said, try to locate your program using the following from terminal :
sudo python3
import serial
print(serial.__file__)
--> Copy
CTRL+D #(to get out of python)
sudo python3
-->paste/__init__.py
Activating __init__.py
will say to your program "ok i'm going to use Serial from python3". My problem was that my python3 program was using Serial from python 2.7
Other solution: remove other python versions
Cao
Tryhard
An issue with the answer from Michal Foksa is that it adds the query parameters first, and then expands the path variables. If query parameter contains parenthesis, e.g. {foobar}
, this will cause an exception.
The safe way is to expand the path variables first, and then add the query parameters:
String url = "http://test.com/Services/rest/{id}/Identifier";
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1234");
URI uri = UriComponentsBuilder.fromUriString(url)
.buildAndExpand(params)
.toUri();
uri = UriComponentsBuilder
.fromUri(uri)
.queryParam("name", "myName")
.build()
.toUri();
restTemplate.exchange(uri , HttpMethod.PUT, requestEntity, class_p);
If you use Integrated Security, you might want to know that you simply need to use -E
like this:
sqlcmd -S Serverinstance -E -i import_file.sql
And if you do that very often, you could use a ViewSwitcher or a ViewFlipper to ease view substitution.
no need for the padding or the corners.
here's a sample:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
<gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
android:angle="270"/>
</shape>
based on :
When you use count = count + 3 or count = count + 9 instead of count = count + 1, the value of count will never be 100, and hence it enters an infinite loop.
You could use the following code for your condition to work
while count < 100:
Now the loop will terminate when count >= 100.
answer with id:
$('#selectBoxId').find('option:eq(0)').attr('selected', true);
Check out the static java.util.Arrays.equals()
family of methods. There's one that does exactly what you want.
Here there are two different concepts that are merged togather in your question.
First : Add Integer array into List. Code is as follows.
List<Integer[]> list = new ArrayList<>();
Integer[] intArray1 = new Integer[] {2, 4};
Integer[] intArray2 = new Integer[] {2, 5};
Integer[] intArray3 = new Integer[] {3, 3};
Collections.addAll(list, intArray1, intArray2, intArray3);
Second : Add integer value in list.
List<Integer> list = new ArrayList<>();
int x = 5
list.add(x);
Check that right version is referenced in your project. E.g. the dll it is complaining about, could be from an older version and that's why there could be a version mismatch.
For Bootstrap 4 simply remove the 'data-ride="carousel"' from the carousel div. This removes auto play at load time.
To enable the auto play again you would still have to use the "play" call in javascript.
As toolkit mentions above, Apache Commons IO is the way to go, specifically FileUtils.copyFile(); it handles all the heavy lifting for you.
And as a postscript, note that recent versions of FileUtils (such as the 2.0.1 release) have added the use of NIO for copying files; NIO can significantly increase file-copying performance, in a large part because the NIO routines defer copying directly to the OS/filesystem rather than handle it by reading and writing bytes through the Java layer. So if you're looking for performance, it might be worth checking that you are using a recent version of FileUtils.
This is an old question, but I just had a similar situation where I needed to check on the status of jobs on SQL Server. A lot of people mentioned the sysjobactivity table and pointed to the MSDN documentation which is great. However, I'd also like to highlight the Job Activity Monitor which provides the status on all jobs that are defined on your server.
Try this:
// Code For IMEI AND IMSI NUMBER
String serviceName = Context.TELEPHONY_SERVICE;
TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);
String IMEI,IMSI;
IMEI = m_telephonyManager.getDeviceId();
IMSI = m_telephonyManager.getSubscriberId();
On any other element, I would use the scrollHeight
of the DOM object and set the height accordingly. I don't know if this would work on an iframe (because they're a bit kooky about everything) but it's certainly worth a try.
Edit: Having had a look around, the popular consensus is setting the height from within the iframe using the offsetHeight
:
function setHeight() {
parent.document.getElementById('the-iframe-id').style.height = document['body'].offsetHeight + 'px';
}
And attach that to run with the iframe-body's onLoad
event.
Lookarounds can be nested.
So this regex matches "drupal-6.14/" that is not followed by "sites" that is not followed by "/all" or "/default".
Confusing? Using different words, we can say it matches "drupal-6.14/" that is not followed by "sites" unless that is further followed by "/all" or "/default"
Just ran into this problem myself. OSx Lion hides scrollbars while not in use to make it seem more "slick", but at the same time the issue you addressed comes up: people sometimes cannot see whether a div has a scroll feature or not.
The fix: In your css include -
::-webkit-scrollbar {
-webkit-appearance: none;
width: 7px;
}
::-webkit-scrollbar-thumb {
border-radius: 4px;
background-color: rgba(0, 0, 0, .5);
box-shadow: 0 0 1px rgba(255, 255, 255, .5);
}
/* always show scrollbars */_x000D_
_x000D_
::-webkit-scrollbar {_x000D_
-webkit-appearance: none;_x000D_
width: 7px;_x000D_
}_x000D_
_x000D_
::-webkit-scrollbar-thumb {_x000D_
border-radius: 4px;_x000D_
background-color: rgba(0, 0, 0, .5);_x000D_
box-shadow: 0 0 1px rgba(255, 255, 255, .5);_x000D_
}_x000D_
_x000D_
_x000D_
/* css for demo */_x000D_
_x000D_
#container {_x000D_
height: 4em;_x000D_
/* shorter than the child */_x000D_
overflow-y: scroll;_x000D_
/* clip height to 4em and scroll to show the rest */_x000D_
}_x000D_
_x000D_
#child {_x000D_
height: 12em;_x000D_
/* taller than the parent to force scrolling */_x000D_
}_x000D_
_x000D_
_x000D_
/* === ignore stuff below, it's just to help with the visual. === */_x000D_
_x000D_
#container {_x000D_
background-color: #ffc;_x000D_
}_x000D_
_x000D_
#child {_x000D_
margin: 30px;_x000D_
background-color: #eee;_x000D_
text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="child">Example</div>_x000D_
</div>
_x000D_
customize the apperance as needed. Source
My problem is that when i use https for the remote URL, it doesn't work, so I use http instead. This allows me to publish/sync with GitHub from Team Explorer instantly.
This is possible in Java 9.
Stream.generate(() -> null)
.takeWhile(x -> iterator.hasNext())
.map(n -> iterator.next())
.forEach(System.out::println);
iterating using iterator is not fail-safe for example if you add element to the collection after iterator's creation then it will throw concurrentmodificaionexception. Also it's not thread safe, you have to make it thread safe externally.
So it's better to use for-each structure of for loop. It's atleast fail-safe.
Try running this as a TSQL Script
SELECT 1
RETURN
SELECT 2
SELECT 3
The return ends the execution.
Exits unconditionally from a query or procedure. RETURN is immediate and complete and can be used at any point to exit from a procedure, batch, or statement block. Statements that follow RETURN are not executed.
Using mysqli i've created following function. Asuming you have an mysqli instance called $con.
function table_exist($table){
global $con;
$table = $con->real_escape_string($table);
$sql = "show tables like '".$table."'";
$res = $con->query($sql);
return ($res->num_rows > 0);
}
Hope it helps.
Warning: as sugested by @jcaron this function could be vulnerable to sqlinjection attacs, so make sure your $table
var is clean or even better use parameterised queries.
If like me, you are using some micro VM lacking of memory, creating a swap file does the trick:
#Check free memory before
free -m
mkdir -p /var/_swap_
cd /var/_swap_
#Here, 1M * 2000 ~= 2GB of swap memory. Feel free to add MORE
dd if=/dev/zero of=swapfile bs=1M count=2000
chmod 600 swapfile
mkswap swapfile
swapon swapfile
#Automatically mount this swap partition at startup
echo "/var/_swap_/swapfile none swap sw 0 0" >> /etc/fstab
#Check free memory after
free -m
As several comments pointed out, don't forget to add sudo if you don't work as root.
btw, feel free to select another location/filename/size for the file.
/var
is probably not the best place, but I don't know which place would be, and rarely care since tiny servers are mostly used for testing purposes.
let's say you want a pointer to point at the address 0x28ff4402, the usual way is
uint32_t *ptr;
ptr = (uint32_t*) 0x28ff4402 //type-casting the address value to uint32_t pointer
*ptr |= (1<<13) | (1<<10); //access the address how ever you want
So the short way is to use a MACRO,
#define ptr *(uint32_t *) (0x28ff4402)
Regular Expression is the most efficient way to solve this problem. Look at the code below. Along validity, it also checks IP address class in which it belongs and whether it is reserved IP Address or not
Pattern ipPattern;
int[] arr=new int[4];
int i=0;
//Method to check validity
private String validateIpAddress(String ipAddress) {
Matcher ipMatcher=ipPattern.matcher(ipAddress);
//Condition to check input IP format
if(ipMatcher.matches()) {
//Split input IP Address on basis of .
String[] octate=ipAddress.split("[.]");
for(String x:octate) {
//Convert String number into integer
arr[i]=Integer.parseInt(x);
i++;
}
//Check whether input is Class A IP Address or not
if(arr[0]<=127) {
if(arr[0]==0||arr[0]==127)
return(" is Reserved IP Address of Class A");
else if(arr[1]==0&&arr[2]==0&&arr[3]==0)
return(" is Class A Network address");
else if(arr[1]==255&&arr[2]==255&&arr[3]==255)
return( " is Class A Broadcast address");
else
return(" is valid IP Address of Class A");
}
//Check whether input is Class B IP Address or not
else if(arr[0]>=128&&arr[0]<=191) {
if(arr[2]==0&&arr[3]==0)
return(" is Class B Network address");
else if(arr[2]==255&&arr[3]==255)
return(" is Class B Broadcast address");
else
return(" is valid IP Address of Class B");
}
//Check whether input is Class C IP Address or not
else if(arr[0]>=192&&arr[0]<=223) {
if(arr[3]==0)
return(" is Class C Network address");
else if(arr[3]==255)
return(" is Class C Broadcast address");
else
return( " is valid IP Address of Class C");
}
//Check whether input is Class D IP Address or not
else if(arr[0]>=224&&arr[0]<=239) {
return(" is Class D IP Address Reserved for multicasting");
}
//Execute if input is Class E IP Address
else {
return(" is Class E IP Address Reserved for Research and Development by DOD");
}
}
//Input not matched with IP Address pattern
else
return(" is Invalid IP Address");
}
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Enter IP Address: ");
//Input IP Address from user
String ipAddress=scan.nextLine();
scan.close();
IPAddress obj=new IPAddress();
//Regex for IP Address
obj.ipPattern=Pattern.compile("((([0-1]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([0-1]?\\d\\d?|2[0-4]\\d|25[0-5]))");
//Display output
System.out.println(ipAddress+ obj.validateIpAddress(ipAddress));
}
vector<char> toVector( const std::string& s ) {
string s = "apple";
vector<char> v(s.size()+1);
memcpy( &v.front(), s.c_str(), s.size() + 1 );
return v;
}
vector<char> v = toVector(std::string("apple"));
// what you were looking for (mutable)
char* c = v.data();
.c_str() works for immutable. The vector will manage the memory for you.
Check if exist, put all files in array, preg grep all JPG files, echo new array For all images could try this:
$images=preg_grep('/\.(jpg|jpeg|png|gif)(?:[\?\#].*)?$/i', $files);
if ($handle = opendir('/path/to/folder')) {
while (false !== ($entry = readdir($handle))) {
$files[] = $entry;
}
$images=preg_grep('/\.jpg$/i', $files);
foreach($images as $image)
{
echo $image;
}
closedir($handle);
}
JPG and JPEG stand both for an image format proposed and supported by the Joint Photographic Experts Group. The two terms have the same meaning and are interchangeable.
To read on, check out Difference between JPG and JPEG.
The reason for the different file extensions dates back to the early versions of Windows. The original file extension for the Joint Photographic Expert Group File Format was ‘.jpeg’; however in Windows all files required a three letter file extension. So, the file extension was shortened to ‘.jpg’. However, Macintosh was not limited to three letter file extensions, so Mac users used ‘.jpeg’. Eventually, with upgrades Windows also began to accept ‘.jpeg’. However, many users were already used to ‘.jpg’, so both the three letter file extension and the four letter extension began to be commonly used, and still is.
Today, the most commonly accepted and used form is the ‘.jpg’, as many users were Windows users. Imaging applications, such as Adobe Photoshop, save all JPEG files with a ".jpg" extension on both Mac and Windows, in an attempt to avoid confusion. The Joint Photographic Expert Group File Format can also be saved with the upper-case ‘.JPEG’ and ‘.JPG’ file extensions, which are less common, but also accepted.
select
@selectoneCount = case @Temp
when 1 then (@selectoneCount+1)
when 2 then (@selectoneCount+1)
end
select @selectoneCount
A source of confusion may be the use of the word in two different contexts - data modelling and database query optimization.
In data modelling terms, cardinality is how one table relates to another.
There are also optional participation conditions to the above (where a row in one table doesn't have to relate to the other table at all).
See Wikipedia on Cardinality (data modelling).
When talking about database query optimization, cardinality refers to the data in a column of a table, specifically how many unique values are in it. This statistic helps with planning queries and optimizing the execution plans.
See Wikipedia on Cardinality (SQL statements).