you can simply use :
error_log("your message");
By default, the message will be send to the php system logger.
input = ['word1, 23, 12','word2, 10, 19','word3, 11, 15']
output = []
for item in input:
items = item.split(',')
output.append([items[0], int(items[1]), int(items[2])])
Here's a simple/sinister one via http://wiki.eclipse.org/Performance_Bloopers#String.substring.28.29.
public class StringLeaker
{
private final String muchSmallerString;
public StringLeaker()
{
// Imagine the whole Declaration of Independence here
String veryLongString = "We hold these truths to be self-evident...";
// The substring here maintains a reference to the internal char[]
// representation of the original string.
this.muchSmallerString = veryLongString.substring(0, 1);
}
}
Because the substring refers to the internal representation of the original, much longer string, the original stays in memory. Thus, as long as you have a StringLeaker in play, you have the whole original string in memory, too, even though you might think you're just holding on to a single-character string.
The way to avoid storing an unwanted reference to the original string is to do something like this:
...
this.muchSmallerString = new String(veryLongString.substring(0, 1));
...
For added badness, you might also .intern()
the substring:
...
this.muchSmallerString = veryLongString.substring(0, 1).intern();
...
Doing so will keep both the original long string and the derived substring in memory even after the StringLeaker instance has been discarded.
all above answers is correct but however
a = [];
len(list1) - 1 # where 0 - 1 = -1
to be more precisely
a = [];
index = len(a) - 1 if a else None;
if index == None : raise Exception("Empty Array")
since arrays is starting with 0
Yeah a CSS primer will not hurt here so you can do two things: 1 - within the tags of your html you can open a style tag like this:
<style type="text/css">
body {
margin: 0px;
}
/*
* this is the same as writing
* body { margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px;}
* I'm adding px here for clarity sake but the unit is not really needed if you have 0
* look into em, pt and % for other unit types
* the rules are always clockwise: top, right, bottom, left
*/
</style>
2- the above though will only work on the page you have this code embeded, so if if you wanted to reuse this in 10 files, then you will have to copy it over on all 10 files, and if you wanted to make a change let's say have a margin of 5px instead, you would have to open all those files and make the edit. That's why using an external style sheet is a golden rule in front end coding. So save the body declaration in a separate file named style.css for example and from your add this to your html instead:
<link rel="stylesheet" type="text/css" href="style.css"/>
Now you can put this in the of all pages that will benefit from these styles and whenever needed to change them you will only need to do so in one place. Hope it helps. Cheers
nproc
is what you are looking for.
More here : http://www.cyberciti.biz/faq/linux-get-number-of-cpus-core-command/
Post android Lollipop release android has changed the guidelines for displaying notification icons in the Notification bar. The official documentation says "Update or remove assets that involve color. The system ignores all non-alpha channels in action icons and in the main notification icon. You should assume that these icons will be alpha-only. The system draws notification icons in white and action icons in dark gray.” Now what that means in lay man terms is "Convert all parts of the image that you don’t want to show to transparent pixels. All colors and non transparent pixels are displayed in white"
You can see how to do this in detail with screenshots here https://blog.clevertap.com/fixing-notification-icon-for-android-lollipop-and-above/
Hope that helps
I have a similar code in my projects that works fine. Adapting my code to your function, a solution could be the following:
function xssRequest(url, callback)
{
var iFrameObj = document.createElement('IFRAME');
iFrameObj.id = 'myUniqueID';
document.body.appendChild(iFrameObj);
iFrameObj.src = url;
$(iFrameObj).load(function()
{
callback(window['myUniqueID'].document.body.innerHTML);
document.body.removeChild(iFrameObj);
});
}
Maybe you have an empty innerHTML because (one or both causes): 1. you should use it against the body element 2. you have removed the iframe from the your page DOM
SdkManager removes the API28 version and re-downloads the API28 version, setting the Flutter and Dart paths in AndroidStudio, and now it works fine. image
Calendar calendar = Calendar.getInstance();
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), R.style.DatePickerDialogTheme, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
String date = simpleDateFormat.format(newDate.getTime());
}
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
And use this style:
<style name="DatePickerDialogTheme" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">@color/colorPrimary</item>
</style>
>>> import numpy
>>> print numpy.power.__doc__
power(x1, x2[, out])
First array elements raised to powers from second array, element-wise.
Raise each base in `x1` to the positionally-corresponding power in
`x2`. `x1` and `x2` must be broadcastable to the same shape.
Parameters
----------
x1 : array_like
The bases.
x2 : array_like
The exponents.
Returns
-------
y : ndarray
The bases in `x1` raised to the exponents in `x2`.
Examples
--------
Cube each element in a list.
>>> x1 = range(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.power(x1, 3)
array([ 0, 1, 8, 27, 64, 125])
Raise the bases to different exponents.
>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.power(x1, x2)
array([ 0., 1., 8., 27., 16., 5.])
The effect of broadcasting.
>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
[1, 2, 3, 3, 2, 1]])
>>> np.power(x1, x2)
array([[ 0, 1, 8, 27, 16, 5],
[ 0, 1, 8, 27, 16, 5]])
>>>
As per the discussed observation on numerical precision as per @GarethRees objection in comments:
>>> a = numpy.ones( (3,3), dtype = numpy.float96 ) # yields exact output
>>> a[0,0] = 0.46002700024131926
>>> a
array([[ 0.460027, 1.0, 1.0],
[ 1.0, 1.0, 1.0],
[ 1.0, 1.0, 1.0]], dtype=float96)
>>> b = numpy.power( a, 2 )
>>> b
array([[ 0.21162484, 1.0, 1.0],
[ 1.0, 1.0, 1.0],
[ 1.0, 1.0, 1.0]], dtype=float96)
>>> a.dtype
dtype('float96')
>>> a[0,0]
0.46002700024131926
>>> b[0,0]
0.21162484095102677
>>> print b[0,0]
0.211624840951
>>> print a[0,0]
0.460027000241
>>> c = numpy.random.random( ( 1000, 1000 ) ).astype( numpy.float96 )
>>> import zmq
>>> aClk = zmq.Stopwatch()
>>> aClk.start(), c**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 5663L) # 5 663 [usec]
>>> aClk.start(), c*c, aClk.stop()
(None, array([[ ...]], dtype=float96), 6395L) # 6 395 [usec]
>>> aClk.start(), c[:,:]*c[:,:], aClk.stop()
(None, array([[ ...]], dtype=float96), 6930L) # 6 930 [usec]
>>> aClk.start(), c[:,:]**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 6285L) # 6 285 [usec]
>>> aClk.start(), numpy.power( c, 2 ), aClk.stop()
(None, array([[ ... ]], dtype=float96), 384515L) # 384 515 [usec]
Installing jdk1.8.0_211 and setting the below variable in product.conf (located in C:\Users\\AppData\Roaming\sqldeveloper\19.1.0) to JDK8 home worked for me
SetJavaHome D:\jdk1.8.0_211
Using java.nio.Files along with java.nio.file.StandardOpenOption
PrintWriter out = null;
BufferedWriter bufWriter;
try{
bufWriter =
Files.newBufferedWriter(
Paths.get("log.txt"),
Charset.forName("UTF8"),
StandardOpenOption.WRITE,
StandardOpenOption.APPEND,
StandardOpenOption.CREATE);
out = new PrintWriter(bufWriter, true);
}catch(IOException e){
//Oh, no! Failed to create PrintWriter
}
//After successful creation of PrintWriter
out.println("Text to be appended");
//After done writing, remember to close!
out.close();
This creates a BufferedWriter
using Files, which accepts StandardOpenOption
parameters, and an auto-flushing PrintWriter
from the resultant BufferedWriter
. PrintWriter
's println()
method, can then be called to write to the file.
The StandardOpenOption
parameters used in this code: opens the file for writing, only appends to the file, and creates the file if it does not exist.
Paths.get("path here")
can be replaced with new File("path here").toPath()
.
And Charset.forName("charset name")
can be modified to accommodate the desired Charset
.
string Location = "C:\\Program Files\\hello.txt";
string FileName = Location.Substring(Location.LastIndexOf('\\') +
1);
I've seen some terrible observer patterns here that cause memory leaks on large applications.
I might be a little late but it's as simple as this.
The watch function watches for reference changes (primitive types) if you want to watch something like array push simply use:
someArray.push(someObj); someArray = someArray.splice(0);
This will update the reference and update the watch from anywhere. Including a services getter method. Anything that's a primitive will be updated automatically.
The default solution is to install KB2999226 of Microsoft.
Install Service:-
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe"
"C:\Services\myservice.exe"
UnInstall Sevice:-
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe" -u "C:\Services\myservice.Service.exe"
Given a dataset
df <- data.frame( sex = c('M', 'M', 'F', 'F', 'M'),
occupation = c('analyst', 'dentist', 'dentist', 'analyst', 'cook') )
you can subset rows
df[df$sex == 'M',] # To get all males
df[df$occupation == 'analyst',] # All analysts
etc.
If you want to get number of rows, just call the function nrow
such as
nrow(df[df$sex == 'M',])
There seems to be no problem since the int to bool cast is done implicitly. This works in Microsoft Visual C++, GCC and Intel C++ compiler. No problem in either C or C++.
import java.io.IOException;
class ExamTest{
public static void main(String args[]) throws IOException{
int sn=System.in.read();
System.out.println(sn);
}
}
If you want get char input you have to cast like this: char sn=(char) System.in.read()
The value byte is returned as int in the range 0 to 255. However, unlike in other languages’ methods, System.in.read()
reads only a byte at a time.
well you can do this:
$(function(){
var $header = $('#header');
var $footer = $('#footer');
var $content = $('#content');
var $window = $(window).on('resize', function(){
var height = $(this).height() - $header.height() + $footer.height();
$content.height(height);
}).trigger('resize'); //on page load
});
see fiddle here: http://jsfiddle.net/maniator/JVKbR/
demo: http://jsfiddle.net/maniator/JVKbR/show/
As everyone else says, you can't from a simple programmatic way.
Consider these examples:
President "George Herbert Walker Bush" (First Middle Middle Last)
Presidential assassin "John Wilkes Booth" (First Middle Last)
Guitarist "Eddie Van Halen" (First Last Last)
And his mom probably calls him Edward Lodewijk Van Halen (First Middle Last Last)
Famed castaway "Mary Ann Summers" (First First Last)
New Mexico GOP chairman "Fernando C de Baca" (First Last Last Last)
I've used Miles Johnson's TypeConverter for this purpose. It's installable using Composer.
You could write something like this using it:
<?php
require 'vendor/autoload.php';
use mjohnson\utility\TypeConverter;
$xml = file_get_contents("file.xml");
$arr = TypeConverter::xmlToArray($xml, TypeConverter::XML_GROUP);
echo json_encode($arr);
I had this error, I looked into a log file C:\...\mysql\data\VM-IIS-Server.err and found this
2016-06-07 17:56:07 160c InnoDB: Error: unable to create temporary file; errno: 2
2016-06-07 17:56:07 3392 [ERROR] Plugin 'InnoDB' init function returned error.
2016-06-07 17:56:07 3392 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2016-06-07 17:56:07 3392 [ERROR] Unknown/unsupported storage engine: InnoDB
2016-06-07 17:56:07 3392 [ERROR] Aborting
The first line says "unable to create temporary file", it sounds like "insufficient privileges", first I tried to give access to mysql folder for my current user - no effect, then after some wandering around I came up to control panel->Administration->Services->Right Clicked MysqlService->Properties->Log On, switched to "This account", entered my username/password, clicked OK, and it woked!
You don't need the redirection, use only
* * * * * wget -qO /dev/null http://yoursite.com/tasks.php
Your solution is nearly correct. You could add DISTINCT:
SELECT
people.pe_name,
COUNT(distinct orders.ord_id) AS num_orders,
COUNT(items.item_id) AS num_items
FROM
people
INNER JOIN orders ON (orders.pe_id = people.pe_id)
INNER JOIN items ON items.pe_id = people.pe_id
GROUP BY
people.pe_id;
Identifying URLs is tricky because they are often surrounded by punctuation marks and because users frequently do not use the full form of the URL. Many JavaScript functions exist for replacing URLs with hyperlinks, but I was unable to find one that works as well as the urlize
filter in the Python-based web framework Django. I therefore ported Django's urlize
function to JavaScript:
An example:
urlize('Go to SO (stackoverflow.com) and ask. <grin>',
{nofollow: true, autoescape: true})
=> "Go to SO (<a href="http://stackoverflow.com" rel="nofollow">stackoverflow.com</a>) and ask. <grin>"
The second argument, if true, causes rel="nofollow"
to be inserted. The third argument, if true, escapes characters that have special meaning in HTML. See the README file.
Just delete key:
HKEY_CURRENT_USER/Software/Microsoft/VCExpress/9.0/Registration
Or run in command line:
reg delete HKCU\Software\Microsoft\VCExpress\9.0\Registration /f
I know this is old and whatnot (and not exactly sure if it's a question), but after searching, I had success with this command for --onefile
:
pyinstaller.exe --onefile --windowed --icon=app.ico app.py
Google led me to this page while I was searching for an answer on how to set an icon for my .exe, so maybe it will help someone else.
The information here was found at this site: https://mborgerson.com/creating-an-executable-from-a-python-script
I use jQuery BeautyTips to achieve the little bubble effect you are talking about. I don't use the Validation plugin so I can't really help much there, but it is very easy to style and show the BeautyTips. You should look into it. It's not as simple as just CSS rules, I'm afraid, as you need to use the canvas element and include an extra javascript file for IE to play nice with it.
It fails "when trying to execute the function manually
" because you have a different 'this'. This will refer not to the thing you have in mind when invoking the method manually, but something else, probably the window object, or whatever context object you have when invoking manually.
Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.
Since you're using Tortoise you may want to check out this link on LosTechies. It should be almost exactly what you are looking for.
Enabling Relation View in phpMyAdmin / MAMP
If you’re using MAMP for your database driven projects you’ll probably be using phpMyAdmin to administer your MySQL database if you’ve decided to go down that route. If you’re creating a database you might be wondering how to create relationships and foriegn keys for your tables.
Firstly you need to check that you have access to the Relation view. To do this open phpMyAdmin and select a database. You need to make sure your tables’ storage engine is set to use InnoDB. Click on a table within your database and choose the Operations tab. Make sure that the storage engine is set to use InnoDB and save your changes.
Now, go back to your table view and click the Structure tab. Depending on your version of phpMyAdmin you should see a link titled Relation view below the table structure. If you can see it you’re good to go. If you can’t you’ll need to follow the steps below to set phpMyAdmin to enable Relations view.
/Applications/MAMP/bin/phpMyAdmin/scripts/create_tables.sql
/Applications/MAMP/bin/phpMyAdmin/config.inc.php
Find the Server(s) configuration code block and replace/uncomment the following code and fill in the values. If you left everything default in the create_tables.sql file then you should just cut and paste the lines below.
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin'; $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; $cfg['Servers'][$i]['relation'] = 'pma_relation'; $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; $cfg['Servers'][$i]['history'] = 'pma_history';
Save the file and restart MAMP and refresh your phpMyAdmin console.
Go to your database and view one of your tables in Structure mode. You should now see the Relation view link.
Source: http://newvibes.com/blog/enabling-relation-view-in-phpmyadmin-mamp/
Select getdate() -- 2010-02-05 10:03:44.527
-- To get all date format
select CONVERT(VARCHAR(12),getdate(),100) +' '+ 'Date -100- MMM DD YYYY' -- Feb 5 2010
union
select CONVERT(VARCHAR(10),getdate(),101) +' '+ 'Date -101- MM/DDYYYY'
Union
select CONVERT(VARCHAR(10),getdate(),102) +' '+ 'Date -102- YYYY.MM.DD'
Union
select CONVERT(VARCHAR(10),getdate(),103) +' '+ 'Date -103- DD/MM/YYYY'
Union
select CONVERT(VARCHAR(10),getdate(),104) +' '+ 'Date -104- DD.MM.YYYY'
Union
select CONVERT(VARCHAR(10),getdate(),105) +' '+ 'Date -105- DD-MM-YYYY'
Union
select CONVERT(VARCHAR(11),getdate(),106) +' '+ 'Date -106- DD MMM YYYY' --ex: 03 Jan 2007
Union
select CONVERT(VARCHAR(12),getdate(),107) +' '+ 'Date -107- MMM DD,YYYY' --ex: Jan 03, 2007
union
select CONVERT(VARCHAR(12),getdate(),109) +' '+ 'Date -108- MMM DD YYYY' -- Feb 5 2010
union
select CONVERT(VARCHAR(12),getdate(),110) +' '+ 'Date -110- MM-DD-YYYY' --02-05-2010
union
select CONVERT(VARCHAR(10),getdate(),111) +' '+ 'Date -111- YYYY/MM/DD'
union
select CONVERT(VARCHAR(12),getdate(),112) +' '+ 'Date -112- YYYYMMDD' -- 20100205
union
select CONVERT(VARCHAR(12),getdate(),113) +' '+ 'Date -113- DD MMM YYYY' -- 05 Feb 2010
SELECT convert(varchar, getdate(), 20) -- 2010-02-05 10:25:14
SELECT convert(varchar, getdate(), 23) -- 2010-02-05
SELECT convert(varchar, getdate(), 24) -- 10:24:20
SELECT convert(varchar, getdate(), 25) -- 2010-02-05 10:24:34.913
SELECT convert(varchar, getdate(), 21) -- 2010-02-05 10:25:02.990
---==================================
-- To get the time
select CONVERT(VARCHAR(12),getdate(),108) +' '+ 'Date -108- HH:MM:SS' -- 10:05:53
select CONVERT(VARCHAR(12),getdate(),114) +' '+ 'Date -114- HH:MM:SS:MS' -- 10:09:46:223
SELECT convert(varchar, getdate(), 22) -- 02/05/10 10:23:11 AM
----=============================================
SELECT getdate()+1
SELECT month(getdate())+1
SELECT year(getdate())+1
If it's always going to be an even LHS/RHS split, you can also use the partition
method that's built into strings. It returns a 3-tuple as (LHS, separator, RHS)
if the separator is found, and (original_string, '', '')
if the separator wasn't present:
>>> "2.7.0_bf4fda703454".partition('_')
('2.7.0', '_', 'bf4fda703454')
>>> "shazam".partition("_")
('shazam', '', '')
You can use the init files. Check the MySQL official documentation on How to Reset the Root Password (including comments for alternative solutions).
So basically using init files, you can add any SQL queries that you need for fixing your access (such as GRAND
, CREATE
, FLUSH PRIVILEGES
, etc.) into init file (any file).
Here is my example of recovering root account:
echo "CREATE USER 'root'@'localhost' IDENTIFIED BY 'root';" > your_init_file.sql
echo "GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;" >> your_init_file.sql
echo "FLUSH PRIVILEGES;" >> your_init_file.sql
and after you've created your file, you can run:
killall mysqld
mysqld_safe --init-file=$PWD/your_init_file.sql
then to check if this worked, press Ctrl+Z and type: bg
to run the process from the foreground into the background, then verify your access by:
mysql -u root -proot
mysql> show grants;
+-------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost |
+-------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B' |
See also:
Layout:
<android.support.v7.widget.AppCompatButton
style="@style/MyButton"
...
/>
styles.xml:
<style name="MyButton" parent="Widget.AppCompat.Button.Colored">
<item name="backgroundTint">@color/button_background_selector</item>
<item name="android:textColor">@color/button_text_selector</item>
</style>
color/button_background_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="#555555"/>
<item android:color="#00ff00"/>
</selector>
color/button_text_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="#888888"/>
<item android:color="#ffffff"/>
</selector>
You're looking for the File
, StreamWriter
, and StreamReader
classes.
It depends on how you want to use it. Using a Join is one way. Another way of doing it is let the thread notify the caller of the thread by using an event. For instance when you have your graphical user interface (GUI) thread that calls a process which runs for a while and needs to update the GUI when it finishes, you can use the event to do this. This website gives you an idea about how to work with events:
http://msdn.microsoft.com/en-us/library/aa645739%28VS.71%29.aspx
Remember that it will result in cross-threading operations and in case you want to update the GUI from another thread, you will have to use the Invoke
method of the control which you want to update.
BATCH/CMD FILE like DateAndTime.cmd (not in CMD-Console)
Code:
SETLOCAL EnableDelayedExpansion
(set d=%date:~8,2%-%date:~3,2%-%date:~0,2%) & (set t=%time::=.%) & (set t=!t: =0!) & (set STAMP=!d!__!t!)
Create output:
echo %stamp%
Output:
2020-02-25__08.43.38.90
Or also possible in for lines in CMD-Console and BATCH/CMD File
set d=%date:~6,4%-%date:~3,2%-%date:~0,2%
set t=%time::=.%
set t=%t: =0%
set stamp=%d%__%t%
"Create output" and "Output" same as above
Complementing the above answers and also "Parroting" from the Windows Dev Center documentation,
The Winsock2.h header file internally includes core elements from the Windows.h header file, so there is not usually an #include line for the Windows.h header file in Winsock applications. If an #include line is needed for the Windows.h header file, this should be preceded with the #define WIN32_LEAN_AND_MEAN macro. For historical reasons, the Windows.h header defaults to including the Winsock.h header file for Windows Sockets 1.1. The declarations in the Winsock.h header file will conflict with the declarations in the Winsock2.h header file required by Windows Sockets 2.0. The WIN32_LEAN_AND_MEAN macro prevents the Winsock.h from being included by the Windows.h header ..
Using jQuery:
$(function() {
window.isActive = true;
$(window).focus(function() { this.isActive = true; });
$(window).blur(function() { this.isActive = false; });
showIsActive();
});
function showIsActive()
{
console.log(window.isActive)
window.setTimeout("showIsActive()", 2000);
}
function doWork()
{
if (window.isActive) { /* do CPU-intensive stuff */}
}
<?php echo substr("abcabcabc", 0, -3); ?>
Here's a method you can use to rotate an image in C#:
/// <summary>
/// method to rotate an image either clockwise or counter-clockwise
/// </summary>
/// <param name="img">the image to be rotated</param>
/// <param name="rotationAngle">the angle (in degrees).
/// NOTE:
/// Positive values will rotate clockwise
/// negative values will rotate counter-clockwise
/// </param>
/// <returns></returns>
public static Image RotateImage(Image img, float rotationAngle)
{
//create an empty Bitmap image
Bitmap bmp = new Bitmap(img.Width, img.Height);
//turn the Bitmap into a Graphics object
Graphics gfx = Graphics.FromImage(bmp);
//now we set the rotation point to the center of our image
gfx.TranslateTransform((float)bmp.Width / 2, (float)bmp.Height / 2);
//now rotate the image
gfx.RotateTransform(rotationAngle);
gfx.TranslateTransform(-(float)bmp.Width / 2, -(float)bmp.Height / 2);
//set the InterpolationMode to HighQualityBicubic so to ensure a high
//quality image once it is transformed to the specified size
gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
//now draw our new image onto the graphics object
gfx.DrawImage(img, new Point(0, 0));
//dispose of our Graphics object
gfx.Dispose();
//return the image
return bmp;
}
Just posted my implementation of IndexWhere() extension method (with unit tests):
http://snipplr.com/view/53625/linq-index-of-item--indexwhere/
Example usage:
int index = myList.IndexWhere(item => item.Something == someOtherThing);
Simple! Add at the end of dockerfile:
ENTRYPOINT service mysql start && /bin/bash
have you tried:
start "c:\program files\Microsoft Virtual PC\Virtual PC.exe" "-pc MY-PC -launch"
?
in my case i want getting timeZone of several country ,first install moment js
npm install moment --save
then install moment-timezone.js
npm install moment-timezone --save
then i import themn in my component like this
import moment from 'moment';
import timezone from 'moment-timezone'
then because iwant getting hour and minutes and second sepratly i do like this
<Clock minutes={moment().tz('Australia/Sydney').minute()} hour={moment().tz('Australia/Sydney').hours()} second={moment().tz('Australia/Sydney').second()}/>
If you just have the xml
file of the color scheme you can:
Go to Preferences
-> Editor
-> Color and Fonts
and use the Import
button.
This it what you are looking for:
<input type="checkbox" [(ngModel)]="isChecked" (change)="checkValue(isChecked?'A':'B')" />
Inside your class:
checkValue(event: any){
console.log(event);
}
Also include FormsModule in app.module.ts
to make ngModel work !
Hope it Helps!
If you use JSON properly, you can have nested object without any issue :
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));
If you’re running Jupyter on Python 3, you can set up a Python 2 kernel like this:
python2 -m pip install ipykernel
python2 -m ipykernel install --user
http://ipython.readthedocs.io/en/stable/install/kernel_install.html
This should be able to set to whatever keybindings you want for indent/outdent here:
Menu File → Preferences → Keyboard Shortcuts
editor.action.indentLines
editor.action.outdentLines
You should use a VARCHAR with an ASCII character encoding. URLs are percent encoded and international domain names use punycode so ASCII is enough to store them. This will use much less space than UTF8.
VARCHAR(512) CHARACTER SET 'ascii' COLLATE 'ascii_general_ci' NOT NULL
This is the disassembled code from .NET Reflector for Path.Combine method. Check IsPathRooted function. If the second path is rooted (starts with a DirectorySeparatorChar), return second path as it is.
public static string Combine(string path1, string path2)
{
if ((path1 == null) || (path2 == null))
{
throw new ArgumentNullException((path1 == null) ? "path1" : "path2");
}
CheckInvalidPathChars(path1);
CheckInvalidPathChars(path2);
if (path2.Length == 0)
{
return path1;
}
if (path1.Length == 0)
{
return path2;
}
if (IsPathRooted(path2))
{
return path2;
}
char ch = path1[path1.Length - 1];
if (((ch != DirectorySeparatorChar) &&
(ch != AltDirectorySeparatorChar)) &&
(ch != VolumeSeparatorChar))
{
return (path1 + DirectorySeparatorChar + path2);
}
return (path1 + path2);
}
public static bool IsPathRooted(string path)
{
if (path != null)
{
CheckInvalidPathChars(path);
int length = path.Length;
if (
(
(length >= 1) &&
(
(path[0] == DirectorySeparatorChar) ||
(path[0] == AltDirectorySeparatorChar)
)
)
||
((length >= 2) &&
(path[1] == VolumeSeparatorChar))
)
{
return true;
}
}
return false;
}
<location path="ControllerName/ActionName">
<system.web>
<httpRuntime executionTimeout="1000"/>
</system.web>
</location>
Probably it is better to set such values in web.config instead of controller. Hardcoding of configurable options is considered harmful.
Many programming languages, especially those derived from C, have support for the so-called Switch Fallthrough. I was searching for the best way to do the same in Ruby and thought it might be useful to others:
In C-like languages fallthrough typically looks like this:
switch (expression) {
case 'a':
case 'b':
case 'c':
// Do something for a, b or c
break;
case 'd':
case 'e':
// Do something else for d or e
break;
}
In Ruby, the same can be achieved in the following way:
case expression
when 'a', 'b', 'c'
# Do something for a, b or c
when 'd', 'e'
# Do something else for d or e
end
This is not strictly equivalent, because it's not possible to let 'a'
execute a block of code before falling through to 'b'
or 'c'
, but for the most part I find it similar enough to be useful in the same way.
first check with instanceof keyword . if true then cast it.
Just put hello()
somewhere below the function and it will execute when you do python your_file.py
For a neater solution you can use this:
if __name__ == '__main__':
hello()
That way the function will only be executed if you run the file, not when you import the file.
In my case the problem was the /var/log
disk full (check with df -h
)
Just deleted some log files and mysql started, no big deal!
Here is a version that JSLint likes:
/*jslint browser: true */
var GET = {};
(function (input) {
'use strict';
if (input.length > 1) {
var param = input.slice(1).replace(/\+/g, ' ').split('&'),
plength = param.length,
tmp,
p;
for (p = 0; p < plength; p += 1) {
tmp = param[p].split('=');
GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp[1]);
}
}
}(window.location.search));
window.alert(JSON.stringify(GET));
Or if you need support for several values for one key like eg. ?key=value1&key=value2 you can use this:
/*jslint browser: true */
var GET = {};
(function (input) {
'use strict';
if (input.length > 1) {
var params = input.slice(1).replace(/\+/g, ' ').split('&'),
plength = params.length,
tmp,
key,
val,
obj,
p;
for (p = 0; p < plength; p += 1) {
tmp = params[p].split('=');
key = decodeURIComponent(tmp[0]);
val = decodeURIComponent(tmp[1]);
if (GET.hasOwnProperty(key)) {
obj = GET[key];
if (obj.constructor === Array) {
obj.push(val);
} else {
GET[key] = [obj, val];
}
} else {
GET[key] = val;
}
}
}
}(window.location.search));
window.alert(JSON.stringify(GET));
// find the first select and bind a click handler
$('#column_select').bind('click', function(){
// retrieve the selected value
var value = $(this).val(),
// build a regular expression that does a head-match
expression = new RegExp('^' + value),
// find the second select
$select = $('#layout_select);
// hide all children (<option>s) of the second select,
// check each element's value agains the regular expression built from the first select's value
// show elements that match the expression
$select.children().hide().filter(function(){
return !!$(this).val().match(expression);
}).show();
});
(this is far from perfect, but should get you there…)
They are both basically same, there is no difference in performance of any sort, the recommended one however is the first case as it is more readable.
int[] array = new int[10];
FROM JLS:
The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both.
I have used the using Newtonsoft.Json as below. Create an object:
public class WorklistSortColumn
{
[JsonProperty(PropertyName = "field")]
public string Field { get; set; }
[JsonProperty(PropertyName = "dir")]
public string Direction { get; set; }
[JsonIgnore]
public string SortOrder { get; set; }
}
Now Call the below method to serialize to Json object as shown below.
string sortColumn = JsonConvert.SerializeObject(worklistSortColumn);
I've answered it here. How can I change font size in Eclipse for Java text editors?
For Eclipse Neon
To Increase Ctrl +
CSP helps you whitelisting sources that you trust. All other sources are not allowed access to. Read this Q&A carefully, and then make sure that you whitelist the fonts, socket connections and other sources if you trust them.
If you know what you are doing, you can comment out the meta
tag to test, probably everything works. But realise that you / your user is being protected here, so keeping the meta
tag is probably a good thing.
One you convert your image to gray-scale you cannot got back. You have gone from three channel to one, when you try to go back all three numbers will be the same. So the short answer is no you cannot go back. The reason your backtorgb function this throwing that error is because it needs to be in the format:
CvtColor(input, output, CV_GRAY2BGR)
OpenCV use BGR not RGB, so if you fix the ordering it should work, though your image will still be gray.
I was facing similar issue and found out that this error was due to incorrect rules set for read/write operations for real time database. By default google firebase nowadays loads cloud store not real time database. We need to switch to real time and apply the correct rules.
As we can see it says cloud Firestore not real time database, once switched to correct database apply below rules:
{
"rules": {
".read": true,
".write": true
}
}
Look at the fiddle here for a quick answer
data-ng-attr-title="{{d.age > 5 ? 'My age is greater than threshold': ''}}"
Uninstall Msysgit and install Cygwin + Git. Then global '.gitconfig' will be here: C:\cygwin(64)\home\[userName]\.gitconfig .
Now you don't have to worry about an environment variable which may be used by other programs. For example, my environment variable pointed me to a mapped drive in my work windows domain environment. I dont want my global .gitconfig sitting on my "home" mapped drive. I also don't know what might happen to other applications that might rely on that windows environment variable. Operations division might need that environment variable set to the mapped drive for a reason.
Also you don't have to worry about Mysysgit overwriting your 'profile' configuration settings if you specify a specific path to global '.gitconfig', using this method.
In general, save yourself and use cygwin bash shell in windows and be happier
You are looking for the command scandir.
$path = '/tmp';
$files = scandir($path);
Following code will remove .
and ..
from the returned array from scandir
:
$files = array_diff(scandir($path), array('.', '..'));
This should be faster.
while ($personCount < 10) {
$result .= "{$personCount} people ";
$personCount++;
}
echo $result;
According to official Jupyter Notebook Documentation Change
%USERPROFILE%
to your folder path
A protoype bean injected inside a singelton bean will behave like singelton untill expilictly called for creating a new instance by get bean.
context.getBean("Your Bean")
My guess is that you've got something in method1
which wraps one exception in another, and uses the toString()
of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.
Here's a short but complete program which demonstrates RuntimeException.getMessage()
behaving correctly:
public class Test {
public static void main(String[] args) {
try {
failingMethod();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private static void failingMethod() {
throw new RuntimeException("Just the message");
}
}
Output:
Error: Just the message
To expand a little further, here are some common examples. Starting with:
const [theArray, setTheArray] = useState(initialArray);
const [theObject, setTheObject] = useState(initialObject);
Push element at end of array
setTheArray(prevArray => [...prevArray, newValue])
Push/update element at end of object
setTheObject(prevState => ({ ...prevState, currentOrNewKey: newValue}));
Push/update element at end of array of objects
setTheArray(prevState => [...prevState, {currentOrNewKey: newValue}]);
Push element at end of object of arrays
let specificArrayInObject = theObject.array.slice();
specificArrayInObject.push(newValue);
const newObj = { ...theObject, [event.target.name]: specificArrayInObject };
theObject(newObj);
Here are some working examples too. https://codesandbox.io/s/reacthooks-push-r991u
I am a novice: after much running around this worked. Thought might be useful
String bufDt = bDOB.getText(); //data from form
DateFormat dF = new SimpleDateFormat("dd-MM-yyyy"); //data in form is in this format
Date bbdt = (Date)dF.parse(bufDt); // string data is converted into java util date
DateFormat dsF = new SimpleDateFormat("yyyy-MM-dd"); //converted date is reformatted for conversion to sql.date
String ndt = dsF.format(bbdt); // java util date is converted to compatible java sql date
java.sql.Date sqlDate= java.sql.Date.valueOf(ndt); // finally data from the form is convered to java sql. date for placing in database
It is only possible if you are able to send custom server-side response headers with the static content.
For a more detailed explanation see my answer here: Set P3P code in HTML
In case you are appending to the DOM, make sure the content is compatible:
modal.find ('div.modal-body').append (content) // check content
This is one of the simplest query for the same that I came across and we use it for monitoring as well:
SELECT TABLESPACE_NAME,SUM(BYTES)/1024/1024/1024 "FREE SPACE(GB)"
FROM DBA_FREE_SPACE GROUP BY TABLESPACE_NAME;
A complete article about Oracle Tablespace: Tablespace
You can use float:left in DIV or use SPAN tag, like
<div style="width:100px;float:left"> First </div>
<div> Second </div>
<br/>
or
<span style="width:100px;"> First </span>
<span> Second </span>
<br/>
The golden rule is to NOT under ANY circumstances lock your users browser. After that, I usually look at execution time, followed by memory usage (unless you're doing something crazy, in which case it could be a higher priority).
I've never heard of such a function, but it would be trivial enough to implement...
def die(msg)
puts msg
exit
end
Then, if this is defined in some .rb file that you include in all your scripts, you are golden.... just because it's not built in doesn't mean you can't do it yourself ;-)
With Bootstrap 4, there is a css class specifically for this. The below will center row content:
<div class="row justify-content-center">
...inner divs and content...
</div>
See: https://v4-alpha.getbootstrap.com/layout/grid/#horizontal-alignment, for more information.
In my case, I was getting error connecting to AWS Gov Postgres RDS. There is a separate link for GOV RDS CA certs- https://s3.us-gov-west-1.amazonaws.com/rds-downloads/rds-combined-ca-us-gov-bundle.pem
Add this pem certs to cacerts of java. You can use below script.
------WINDOWDS STEPS-------
Script code:
#!/usr/bin/env sh
OLDDIR="$PWD"
CACERTS_FILE=cacerts
cd /c/rds-ca
echo "Downloading RDS certificates..."
curl https://s3.us-gov-west-1.amazonaws.com/rds-downloads/rds-combined-ca-us-gov-bundle.pem > rds-combined-ca-bundle.pem
csplit -sk rds-combined-ca-bundle.pem "/-BEGIN CERTIFICATE-/" "{$(grep -c 'BEGIN CERTIFICATE' rds-combined-ca-bundle.pem | awk '{print $1 - 2}')}"
for CERT in xx*; do
# extract a human-readable alias from the cert
ALIAS=$(openssl x509 -noout -text -in $CERT |
perl -ne 'next unless /Subject:/; s/.*CN=//; print')
echo "importing $ALIAS"
keytool -import \
-keystore $CACERTS_FILE \
-storepass changeit -noprompt \
-alias "$ALIAS" -file $CERT
done
cd "$OLDDIR"
echo "$NEWDIR"
The shortest and fastest way ever. Only 1 line!
public static string StringSha256Hash(string text) =>
string.IsNullOrEmpty(text) ? string.Empty : BitConverter.ToString(new System.Security.Cryptography.SHA256Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(text))).Replace("-", string.Empty);
That's another solution (Spring Security 3):
public String getLoggedUser() throws Exception {
String name = SecurityContextHolder.getContext().getAuthentication().getName();
return (!name.equals("anonymousUser")) ? name : null;
}
Swift 5
//MARK:- if you are in UITabBarController
self.selectedIndex = 1
or
tabBarController?.selectedIndex = 1
Here is the simple ListView with different images. First of all you have to copy the different kinds of images and paste it to the res/drawable-hdpi in your project. Images should be (.png)file format. then copy this code.
In main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
create listview_layout.xml and paste this code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/hello"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:text="TextView1" />
<TextView
android:id="@+id/cur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp"
android:text="TextView2" />
</LinearLayout>
In your Activity
package com.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class SimpleListImageActivity extends Activity {
// Array of strings storing country names
String[] countries = new String[] {
"India",
"Pakistan",
"Sri Lanka",
"China",
"Bangladesh",
"Nepal",
"Afghanistan",
"North Korea",
"South Korea",
"Japan"
};
// Array of integers points to images stored in /res/drawable-hdpi/
//here you have to give image name which you already pasted it in /res/drawable-hdpi/
int[] flags = new int[]{
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
R.drawable.image6,
R.drawable.image7,
R.drawable.image8,
R.drawable.image9,
R.drawable.image10,
};
// Array of strings to store currencies
String[] currency = new String[]{
"Indian Rupee",
"Pakistani Rupee",
"Sri Lankan Rupee",
"Renminbi",
"Bangladeshi Taka",
"Nepalese Rupee",
"Afghani",
"North Korean Won",
"South Korean Won",
"Japanese Yen"
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<10;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", "Country : " + countries[i]);
hm.put("cur","Currency : " + currency[i]);
hm.put("flag", Integer.toString(flags[i]) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "flag","txt","cur" };
// Ids of views in listview_layout
int[] to = { R.id.flag,R.id.txt,R.id.cur};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listView = ( ListView ) findViewById(R.id.listview);
// Setting the adapter to the listView
listView.setAdapter(adapter);
}
}
This is the full code.you can make changes to your need... Comments are welcome
You'll need to add this to your server configuration:
AddType application/x-httpd-php .php
That is assuming you have installed PHP properly, which may not be the case since it doesn't work where it normally would immediately after installing.
It is entirely possible that you'll also have to add the php
.so/.dll file to your Apache configuration using a LoadModule
directive (usually in httpd.conf
).
In the given answers/examples the file is (most likely) uploaded with a HTML form or using the FormData API. The file is only a part of the data sent in the request, hence the multipart/form-data
Content-Type
header.
If you want to send the file as the only content then you can directly add it as the request body and you set the Content-Type
header to the MIME type of the file you are sending. The file name can be added in the Content-Disposition
header. You can upload like this:
var xmlHttpRequest = new XMLHttpRequest();
var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...
xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);
If you don't (want to) use forms and you are only interested in uploading one single file this is the easiest way to include your file in the request.
In, my case I followed this advice and changed this emmet setting in vscode to false
:
"emmet.triggerExpansionOnTab": false
I was receinving the error Cannot read property 'value' of null
. It solved the problem immediatelly.
Safe area extension For Objective-C
@implementation UIView (SafeArea)
- (NSLayoutAnchor *)safeTopAnchor{
if (@available(iOS 11.0, *)){
return self.safeAreaLayoutGuide.topAnchor;
} else {
return self.topAnchor;
}
}
- (NSLayoutAnchor *)safeBottomAnchor{
if (@available(iOS 11.0, *)) {
return self.safeAreaLayoutGuide.bottomAnchor;
} else {
return self.bottomAnchor;
}
}
@end
String interpolation is going to be included with Python 3.6 as specified in PEP 498. You will be able to do this:
name = 'Spongebob Squarepants'
print(f'Who lives in a Pineapple under the sea? \n{name}')
Note that I hate Spongebob, so writing this was slightly painful. :)
You must make your binding bidirectional :
<checkbox IsChecked="{Binding Path=MyProperty, Mode=TwoWay}"/>
Documentation for the method from the Apache Commons Lang (from here):
Checks whether the String a valid Java number.
Valid numbers include hexadecimal marked with the 0x qualifier, scientific notation and numbers marked with a type qualifier (e.g. 123L).
Null
and empty String will returnfalse
.Parameters:
`str` - the `String` to check
Returns:
`true` if the string is a correctly formatted number
isNumber
from java.org.apache.commons.lang3.math.NumberUtils:
public static boolean isNumber(final String str) {
if (StringUtils.isEmpty(str)) {
return false;
}
final char[] chars = str.toCharArray();
int sz = chars.length;
boolean hasExp = false;
boolean hasDecPoint = false;
boolean allowSigns = false;
boolean foundDigit = false;
// deal with any possible sign up front
final int start = (chars[0] == '-') ? 1 : 0;
if (sz > start + 1 && chars[start] == '0' && chars[start + 1] == 'x') {
int i = start + 2;
if (i == sz) {
return false; // str == "0x"
}
// checking hex (it can't be anything else)
for (; i < chars.length; i++) {
if ((chars[i] < '0' || chars[i] > '9')
&& (chars[i] < 'a' || chars[i] > 'f')
&& (chars[i] < 'A' || chars[i] > 'F')) {
return false;
}
}
return true;
}
sz--; // don't want to loop to the last char, check it afterwords
// for type qualifiers
int i = start;
// loop to the next to last char or to the last char if we need another digit to
// make a valid number (e.g. chars[0..5] = "1234E")
while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {
if (chars[i] >= '0' && chars[i] <= '9') {
foundDigit = true;
allowSigns = false;
} else if (chars[i] == '.') {
if (hasDecPoint || hasExp) {
// two decimal points or dec in exponent
return false;
}
hasDecPoint = true;
} else if (chars[i] == 'e' || chars[i] == 'E') {
// we've already taken care of hex.
if (hasExp) {
// two E's
return false;
}
if (!foundDigit) {
return false;
}
hasExp = true;
allowSigns = true;
} else if (chars[i] == '+' || chars[i] == '-') {
if (!allowSigns) {
return false;
}
allowSigns = false;
foundDigit = false; // we need a digit after the E
} else {
return false;
}
i++;
}
if (i < chars.length) {
if (chars[i] >= '0' && chars[i] <= '9') {
// no type qualifier, OK
return true;
}
if (chars[i] == 'e' || chars[i] == 'E') {
// can't have an E at the last byte
return false;
}
if (chars[i] == '.') {
if (hasDecPoint || hasExp) {
// two decimal points or dec in exponent
return false;
}
// single trailing decimal point after non-exponent is ok
return foundDigit;
}
if (!allowSigns
&& (chars[i] == 'd'
|| chars[i] == 'D'
|| chars[i] == 'f'
|| chars[i] == 'F')) {
return foundDigit;
}
if (chars[i] == 'l'
|| chars[i] == 'L') {
// not allowing L with an exponent or decimal point
return foundDigit && !hasExp && !hasDecPoint;
}
// last character is illegal
return false;
}
// allowSigns is true iff the val ends in 'E'
// found digit it to make sure weird stuff like '.' and '1E-' doesn't pass
return !allowSigns && foundDigit;
}
[code is under version 2 of the Apache License]
UPDATE `table_name` SET `test` = `number`
You can also do any mathematical changes in the process or use MySQL functions to modify the values.
Use an array to hold the state of the items
In the adapter use a Map or a SparseBooleanArray (which is similar to a map but is a key-value pair of int and boolean) to store the state of all the items in our list of items and then use the keys and values to compare when toggling the checked state
In the Adapter create a SparseBooleanArray
// sparse boolean array for checking the state of the items
private SparseBooleanArray itemStateArray= new SparseBooleanArray();
then in the item click handler onClick()
use the state of the items in the itemStateArray to check before toggling, here is an example
@Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
if (!itemStateArray.get(adapterPosition, false)) {
mCheckedTextView.setChecked(true);
itemStateArray.put(adapterPosition, true);
}
else {
mCheckedTextView.setChecked(false);
itemStateArray.put(adapterPosition, false);
}
}
also, use sparse boolean array to set the checked state when the view is bound
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(position);
}
@Override
public int getItemCount() {
if (items == null) {
return 0;
}
return items.size();
}
void loadItems(List<Model> tournaments) {
this.items = tournaments;
notifyDataSetChanged();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CheckedTextView mCheckedTextView;
ViewHolder(View itemView) {
super(itemView);
mCheckedTextView = (CheckedTextView) itemView.findViewById(R.id.checked_text_view);
itemView.setOnClickListener(this);
}
void bind(int position) {
// use the sparse boolean array to check
if (!itemStateArray.get(position, false)) {
mCheckedTextView.setChecked(false);}
else {
mCheckedTextView.setChecked(true);
}
}
and final adapter will be like this
Here's a Boolean thing:
if (not suffix == "flac" ) or (not suffix == "cue" ): # WRONG! FAILS
print filename + ' is not a flac or cue file'
but
if not (suffix == "flac" or suffix == "cue" ): # CORRECT!
print filename + ' is not a flac or cue file'
(not a) or (not b) == not ( a and b )
,
is false only if a and b are both true
not (a or b)
is true only if a and be are both false.
You can use case class to prepare sample dataset ...
which is optional for ex: you can get DataFrame
from hiveContext.sql
as well..
import org.apache.spark.sql.functions.col
case class Person(name: String, age: Int, personid : Int)
case class Profile(name: String, personid : Int , profileDescription: String)
val df1 = sqlContext.createDataFrame(
Person("Bindu",20, 2)
:: Person("Raphel",25, 5)
:: Person("Ram",40, 9):: Nil)
val df2 = sqlContext.createDataFrame(
Profile("Spark",2, "SparkSQLMaster")
:: Profile("Spark",5, "SparkGuru")
:: Profile("Spark",9, "DevHunter"):: Nil
)
// you can do alias to refer column name with aliases to increase readablity
val df_asPerson = df1.as("dfperson")
val df_asProfile = df2.as("dfprofile")
val joined_df = df_asPerson.join(
df_asProfile
, col("dfperson.personid") === col("dfprofile.personid")
, "inner")
joined_df.select(
col("dfperson.name")
, col("dfperson.age")
, col("dfprofile.name")
, col("dfprofile.profileDescription"))
.show
sample Temp table approach which I don't like personally...
df_asPerson.registerTempTable("dfperson");
df_asProfile.registerTempTable("dfprofile")
sqlContext.sql("""SELECT dfperson.name, dfperson.age, dfprofile.profileDescription
FROM dfperson JOIN dfprofile
ON dfperson.personid == dfprofile.personid""")
Note : 1) As mentioned by @RaphaelRoth ,
val resultDf = PersonDf.join(ProfileDf,Seq("personId"))
is good approach since it doesnt have duplicate columns from both sides if you are using inner join with same table.
2) Spark 2.x example updated in another answer with full set of join operations supported by spark 2.x with examples + result
Also, important thing in joins : broadcast function can help to give hint please see my answer
git checkout origin/[branch] .
git status
// Note dot (.) at the end. And all will be good
If the project is maven placed it in src/main/resources
, in the package phase it will copy it in ../WEB-INF/classes/hibernate.cfg.xml
for a 2-D tensor, you can get the number of rows and columns as int32 using the following code:
rows, columns = map(lambda i: i.value, tensor.get_shape())
Use the System.getenv(String)
method, passing the name of the variable to read.
First what you have to do, before changing web.xml is to make sure your ManagedBean implements Serializable
:
@ManagedBean
@ViewScoped
public class Login implements Serializable {
}
Especially if you use MyFaces
This is what I used
public static Toast displayCustomToast(FragmentActivity mAct, String toastText, String toastLength, String succTypeColor) {
final Toast toast;
if (toastLength.equals("short")) {
toast = Toast.makeText(mAct, toastText, Toast.LENGTH_SHORT);
} else {
toast = Toast.makeText(mAct, toastText, Toast.LENGTH_LONG);
}
View tView = toast.getView();
tView.setBackgroundColor(Color.parseColor("#053a4d"));
TextView mText = (TextView) tView.findViewById(android.R.id.message);
mText.setTypeface(applyFont(mAct));
mText.setShadowLayer(0, 0, 0, 0);
tView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toast.cancel();
}
});
tView.invalidate();
if (succTypeColor.equals("red")) {
mText.setTextColor(Color.parseColor("#debe33"));
tView.setBackground(mAct.getResources().getDrawable(R.drawable.toast_rounded_red));
// this is to show error message
}
if (succTypeColor.equals("green")) {
mText.setTextColor(Color.parseColor("#053a4d"));
tView.setBackground(mAct.getResources().getDrawable(R.drawable.toast_rounded_green));
// this is to show success message
}
return toast;
}
While calling just write below.
AllMethodsInOne.displayCustomToast(act, "This is custom toast", "long", "red").show();
For anyone having issues with this on https://forge.laravel.com, I managed to get this to work using a compilation of SO answers;
You will need the sudo password.
sudo nano /etc/nginx/conf.d/uploads.conf
Replace contents with the following;
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;
client_max_body_size 24M;
client_body_buffer_size 128k;
client_header_buffer_size 5120k;
large_client_header_buffers 16 5120k;
I used easyengine to set up my vultr cloud based server.
I found my bash file at /etc/bash.bashrc
.
So source /etc/bash.bashrc
did the trick for me!
update
When setting up a bare server (ubuntu 16.04), you can use the above info, when you have not yet set up a username, and are logging in via root.
It's best to create a user (with sudo privledges), and login as this username instead.
This will create a directory for your settings, including .profile and .bashrc files.
https://linuxize.com/post/how-to-create-a-sudo-user-on-ubuntu/
Now, you will edit and (and "source") the ~/.bashrc
file.
On my server, this was located at /home/your_username/.bashrc
(where your_username
is actually the new username you created above, and now login with)
try overflow hidden on the thing you don't want to scroll while touch event is happening. e.g set overflow hidden on Start and set it back to auto on end.
Did you try it ? I'd be interested to know if this would work.
document.addEventListener('ontouchstart', function(e) {
document.body.style.overflow = "hidden";
}, false);
document.addEventListener('ontouchmove', function(e) {
document.body.style.overflow = "auto";
}, false);
Apologies in advance for this lo-tech suggestion, but another option, which finally worked for me after battling NuGet for several hours, is to re-create a new empty project, Web API in my case, and just copy the guts of your old, now-broken project into the new one. Took me about 15 minutes.
Based on NilObject's code:
#include <sys/stat.h>
#include <sys/types.h>
off_t fsize(const char *filename) {
struct stat st;
if (stat(filename, &st) == 0)
return st.st_size;
return -1;
}
Changes:
const char
.struct stat
definition, which was missing the variable name.-1
on error instead of 0
, which would be ambiguous for an empty file. off_t
is a signed type so this is possible.If you want fsize()
to print a message on error, you can use this:
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
off_t fsize(const char *filename) {
struct stat st;
if (stat(filename, &st) == 0)
return st.st_size;
fprintf(stderr, "Cannot determine size of %s: %s\n",
filename, strerror(errno));
return -1;
}
On 32-bit systems you should compile this with the option -D_FILE_OFFSET_BITS=64
, otherwise off_t
will only hold values up to 2 GB. See the "Using LFS" section of Large File Support in Linux for details.
This is how I have done it, I have tested it in both Firefox and Chrome. This makes it possible to check the filename and line number of the place where the function is called from.
logFileAndLineNumber(new Error());
function logFileAndLineNumber(newErr)
{
if(navigator.userAgent.indexOf("Firefox") != -1)
{
var originPath = newErr.stack.split('\n')[0].split("/");
var fileNameAndLineNumber = originPath[originPath.length - 1].split(">")[0];
console.log(fileNameAndLineNumber);
}else if(navigator.userAgent.indexOf("Chrome") != -1)
{
var originFile = newErr.stack.split('\n')[1].split('/');
var fileName = originFile[originFile.length - 1].split(':')[0];
var lineNumber = originFile[originFile.length - 1].split(':')[1];
console.log(fileName+" line "+lineNumber);
}
}
Since the value of $var
is the empty string, this:
if [ $var == $var1 ]; then
expands to this:
if [ == abcd ]; then
which is a syntax error.
You need to quote the arguments:
if [ "$var" == "$var1" ]; then
You can also use =
rather than ==
; that's the original syntax, and it's a bit more portable.
If you're using bash, you can use the [[
syntax, which doesn't require the quotes:
if [[ $var = $var1 ]]; then
Even then, it doesn't hurt to quote the variable reference, and adding quotes:
if [[ "$var" = "$var1" ]]; then
might save a future reader a moment trying to remember whether [[
... ]]
requires them.
I use IntelliJ Idea, PHPStorm, and WebStorm. I thought WebStorm would be sufficient for PHP coding, but in reality it's great for editing but doesn't feel like it real-time-error-checks PHP as well as PHPStorm. This is just an observation, coming from a regular user of a JetBrains products.
If you're a student try taking advantage of the free license while attending school; it gives you a chance to explore different JetBrains IDE... Did I mention CLion? =]
I think using UPDATE ... WHERE
as explained here and here is a lean approach
Project.update(
{ title: 'a very different title no' } /* set attributes' value */,
{ where: { _id : 1 }} /* where criteria */
).then(function(affectedRows) {
Project.findAll().then(function(Projects) {
console.log(Projects)
})
Generally when I want to create a JSON or YAML string, I start out by building the Perl data structure, and then running a simple conversion on it. You could put a UI in front of the Perl data structure generation, e.g. a web form.
Converting a structure to JSON is very straightforward:
use strict;
use warnings;
use JSON::Any;
my $data = { arbitrary structure in here };
my $json_handler = JSON::Any->new(utf8=>1);
my $json_string = $json_handler->objToJson($data);
Put your script in a file foo.py
starting with
#!/usr/bin/python
Then give execute permission to that script using
chmod a+x foo.py
and use the full path of your foo.py
file in your crontab
.
See documentation of execve(2) which is handling the shebang.
You don't need to go level up and use ..
since all buttons are on the same level:
//button[contains(.,'Arcade Reader')]/preceding-sibling::button[@name='settings']
You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:
Set MyEmail=CreateObject("CDO.Message")
MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"
'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25
MyEmail.Configuration.Fields.Update
MyEmail.Send
set MyEmail=nothing
If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update
line:
'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username"
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"
More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm
You are probably storing the value 0xc0 in a char
variable, what is probably a signed type, and your value is negative (most significant bit set). Then, when printing, it is converted to int
, and to keep the semantical equivalence, the compiler pads the extra bytes with 0xff, so the negative int
will have the same numerical value of your negative char
. To fix this, just cast to unsigned char
when printing:
printf("%x", (unsigned char)variable);
I just wanted something really basic to move some files out of the main folder, like user2889485's reply, but his specific answer didnt work for me. I didnt care if they were in the same package or not.
My GOPATH workspace is c:\work\go
and under that I have
/src/pg/main.go (package main)
/src/pg/dbtypes.go (pakage dbtypes)
in main.go
I import "/pg/dbtypes"
Collections.singletonMap(left, rigth);
Why not write one? Something like this may satisfy your requirements:
def FixCase(st):
return ' '.join(''.join([w[0].upper(), w[1:].lower()]) for w in st.split())
If you just want to check the type, you can use jQuery's .is() function,
Like in my case I used below,
if($("#id").is("select")) {
alert('Select');
else if($("#id").is("input")) {
alert("input");
}
Using basename I used the following to achieve this:
for file in *; do
ext=${file##*.}
fname=`basename $file $ext`
# Do things with $fname
done;
This requires no a priori knowledge of the file extension and works even when you have a filename that has dots in it's filename (in front of it's extension); it does require the program basename
though, but this is part of the GNU coreutils so it should ship with any distro.
for what DB is the user? look at this example
mysql> create database databasename;
Query OK, 1 row affected (0.00 sec)
mysql> grant all on databasename.* to cmsuser@localhost identified by 'password';
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
so to return to you question the "%" operator means all computers in your network.
like aspesa shows I'm also sure that you have to create or update a user. look for all your mysql users:
SELECT user,password,host FROM user;
as soon as you got your user set up you should be able to connect like this:
mysql -h localhost -u gmeier -p
hope it helps
Great work Andreas. I created a bean version so the SessionFactory could be autowired.
import javax.persistence.EntityManagerFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
....
@Autowired
private EntityManagerFactory entityManagerFactory;
@Bean
public SessionFactory getSessionFactory() {
if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
throw new NullPointerException("factory is not a hibernate factory");
}
return entityManagerFactory.unwrap(SessionFactory.class);
}
The thing is that you are using the option -t
when running your container.
Could you check if enabling the tty
option (see reference) in your docker-compose.yml file the container keeps running?
version: '2'
services:
ubuntu:
build: .
container_name: ubuntu
volumes:
- ~/sph/laravel52:/www/laravel
ports:
- "80:80"
tty: true
My solution.
Before doing anything check:
if (!$this->entityManager->isOpen()) {
$this->entityManager = $this->entityManager->create(
$this->entityManager->getConnection(),
$this->entityManager->getConfiguration()
);
}
All entities will be saved. But it is handy for particular class or some cases. If you have some services with injected entitymanager, it still be closed.
if you need the batch file to schedule the backup, the SQL management tools have scheduled tasks built in...
For some reason none of these solutions worked for me. I've had the best success using transforms.
transform: translateX(-5.8%) translateY(-5%) scale(0.884);
@John Woo's answer helped me solve a similar problem. I've improved upon his answer by setting the correct ordering as well. This has worked for me:
SELECT a.*, c.*
FROM users a
INNER JOIN payments c
ON a.id = c.user_ID
INNER JOIN (
SELECT user_ID, MAX(date) as maxDate FROM
(
SELECT user_ID, date
FROM payments
ORDER BY date DESC
) d
GROUP BY user_ID
) b ON c.user_ID = b.user_ID AND
c.date = b.maxDate
WHERE a.package = 1
I'm not sure how efficient this is, though.
Regarding apply
vs map
:
pool.apply(f, args)
: f
is only executed in ONE of the workers of the pool. So ONE of the processes in the pool will run f(args)
.
pool.map(f, iterable)
: This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. So you take advantage of all the processes in the pool.
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
Basically JAVA_HOME
is use to set path of the java . it is use in windows. it's used for set path of the multiple software like as java EE
, ANT
and Maven
.
this is the steps to solve your problem:
only for core java to set path :
path :"C:\Program Files\Java\jre1.8.0_77\bin"
but when you are use multi built like as ANT
, core java then you are used JAVE_HOME
in environment .
follow the steps :
JAVA_HOME
:"C:\Program Files\Java\jre1.8.0_77\bin"
ANT_HOME
:"C:\ant\apache-ant-1.9.6"
Path: JAVA_HOME
, ANT_HOME
;
it is the systematic way to set the environment variable..
If you just want to view the changes to a particular file between the working copy and a particular commit using GitLens, the currently accepted answer can make it difficult to find the file you're interested in if many files have changed between the versions.
Instead, go to the file explorer in the side bar and right click on the file, go to Open Changes > Open Changes with Revision... (or Open Changes with Branch or Tag...).
I had the same problem.
The proper way would be setting the 'searchText' to be a property inside an object.
But what if I want to leave it as it is, a string? well, I tried every single method mentioned here, nothing worked.
But then I noticed that the problem is only in the initiation, so I've just set the value attribute and it worked.
<input type="text" ng-model="searchText" value={{searchText}} />
This way the value is just set to '$scope.searchText' value and it's being updated when the input value changes.
I know it's a workaround, but it worked for me..
You can use a lambda expression, e.g:
sales['time_hour'] = sales.timestamp.apply(lambda x: x.hour)
The problem is that you aren't correctly escaping the input string, try:
echo "\"member\":\"time\"" | grep -e "member\""
Alternatively, you can use unescaped double quotes within single quotes:
echo '"member":"time"' | grep -e 'member"'
It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd'
).
My solution was to add a space between the $ and the {.
For example:
@Value("${appclient.port:}")
becomes
@Value("$ {appclient.port:}")
Did you try passwd -d root
? Most likely, this will do what you want.
You can also manually edit /etc/shadow
: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to
root:$X$SK5xfLB1ZW:0:0...
There, delete the second field (everything between the first and second colon):
root::0:0...
Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)
root:*:0:0...
Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d
, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd
, and use mkpasswd
to create the second field for the /etc/shadow.)
myString.Length; //will get you your result
//alternatively, if you only want the count of letters:
myString.Count(char.IsLetter);
//however, if you want to display the words as ***_***** (where _ is a space)
//you can also use this:
//small note: that will fail with a repeated word, so check your repeats!
myString.Split(' ').ToDictionary(n => n, n => n.Length);
//or if you just want the strings and get the counts later:
myString.Split(' ');
//will not fail with repeats
//and neither will this, which will also get you the counts:
myString.Split(' ').Select(n => new KeyValuePair<string, int>(n, n.Length));
If you have the column and the sequence, you first need to populate a new key for all the existing rows. Assuming you don't care which key is assigned to which row
UPDATE table_name
SET new_pk_column = sequence_name.nextval;
Once that's done, you can create the primary key constraint (this assumes that either there is no existing primary key constraint or that you have already dropped the existing primary key constraint)
ALTER TABLE table_name
ADD CONSTRAINT pk_table_name PRIMARY KEY( new_pk_column )
If you want to generate the key automatically, you'd need to add a trigger
CREATE TRIGGER trigger_name
BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
:new.new_pk_column := sequence_name.nextval;
END;
If you are on an older version of Oracle, the syntax is a bit more cumbersome
CREATE TRIGGER trigger_name
BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
SELECT sequence_name.nextval
INTO :new.new_pk_column
FROM dual;
END;
This is an option:
dbContext.Entry(entity).State = EntityState.Detached;
CREATE VIEW [dbo].[ret_vwSalariedForReport]
AS
WITH temp1 AS (SELECT
salaried.*,
operationalUnits.Title as OperationalUnitTitle
FROM
ret_vwSalaried salaried LEFT JOIN
prs_operationalUnitFeatures operationalUnitFeatures on salaried.[Guid] = operationalUnitFeatures.[FeatureGuid] LEFT JOIN
prs_operationalUnits operationalUnits ON operationalUnits.id = operationalUnitFeatures.OperationalUnitID
),
temp2 AS (SELECT
t2.*,
STUFF ((SELECT ' - ' + t1.OperationalUnitTitle
FROM
temp1 t1
WHERE t1.[ID] = t2.[ID]
For XML PATH('')), 2, 2, '') OperationalUnitTitles from temp1 t2)
SELECT
[Guid],
ID,
Title,
PersonnelNo,
FirstName,
LastName,
FullName,
Active,
SSN,
DeathDate,
SalariedType,
OperationalUnitTitles
FROM
temp2
GROUP BY
[Guid],
ID,
Title,
PersonnelNo,
FirstName,
LastName,
FullName,
Active,
SSN,
DeathDate,
SalariedType,
OperationalUnitTitles
Adding to @Patrick's answer, you can use the following to drop multiple columns
columns_to_drop = ['id', 'id_copy']
df = df.drop(*columns_to_drop)
At the time this question was originally posted, people were understandably directing you to third-party base 64 libraries because of the lack of any native routines. But iOS 7 introduced base 64 encoding routines (which actually simply just exposes private methods iOS had going back to iOS 4).
So, you can use the NSData
method base64EncodedStringWithOptions:
to create a base-64 string from a NSData
.
NSString *string = [data base64EncodedStringWithOptions:kNilOptions];
And you can use initWithBase64EncodedString:options:
to convert a base-64 string back to a NSData
:
NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:kNilOptions];
Or, in Swift:
let string = data.base64EncodedString()
And
let data = Data(base64Encoded: string)
Not messing with IFS
Not calling external command
variable=abc,def,ghij
for i in ${variable//,/ }
do
# call your procedure/other scripts here below
echo "$i"
done
Using bash string manipulation http://www.tldp.org/LDP/abs/html/string-manipulation.html
I just want to point out that most of the answers here don't work, I am new to NodeJS and IDK if throughout time the "module.exports.yourClass" method changed, or if people just entered the wrong answer.
// MyClass
module.exports.Ninja = class Ninja{
test(){
console.log('TESTING 1... 2... 3...');
};
}
//Using MyClass in seprate File
const ninjaFw = require('./NinjaFw');
let ninja = new ninjaFw.Ninja();
ninja.test();
// Ninja Framework File
class Ninja{
test(){
console.log('TESTING 1... 2... 3...');
};
}
module.exports.Ninja = Ninja;
Solution using React functional components.
import React, { useState, useRef, useEffect } from 'react'
const Modal = ({ title, show, onButtonClick }) => {
const dialog = useRef({})
useEffect(() => { $(dialog.current).modal(show ? 'show' : 'hide') }, [show])
useEffect(() => { $(dialog.current).on('hide.bs.modal', () =>
onButtonClick('close')) }, [])
return (
<div className="modal fade" ref={dialog}
id="modalDialog" tabIndex="-1" role="dialog"
aria-labelledby="modalDialogLabel" aria-hidden="true"
>
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="modalDialogLabel">{title}</h5>
<button type="button" className="close" aria-label="Close"
onClick={() => onButtonClick('close')}
>
<span aria-hidden="true">×</span>
</button>
</div>
<div className="modal-body">
...
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary"
onClick={() => onButtonClick('close')}>Close</button>
<button type="button" className="btn btn-primary"
onClick={() => onButtonClick('save')}>Save</button>
</div>
</div>
</div>
</div>
)
}
const App = () => {
const [ showDialog, setShowDialog ] = useState(false)
return (
<div className="container">
<Modal
title="Modal Title"
show={showDialog}
onButtonClick={button => {
if(button == 'close') setShowDialog(false)
if(button == 'save') console.log('save button clicked')
}}
/>
<button className="btn btn-primary" onClick={() => {
setShowDialog(true)
}}>Show Dialog</button>
</div>
)
}
Use this commad when first connect to psql
=# psql <databaseName> <usernamePostgresql>
I have tried many different approaches and the best one for me is:
ps -p $$
It also works under Cygwin and cannot produce false positives as PID grepping. With some cleaning, it outputs just an executable name (under Cygwin with path):
ps -p $$ | tail -1 | awk '{print $NF}'
You can create a function so you don't have to memorize it:
# Print currently active shell
shell () {
ps -p $$ | tail -1 | awk '{print $NF}'
}
...and then just execute shell
.
It was tested under Debian and Cygwin.
Not really what you're looking for, but it may be useful to you. Face Detection/Computer Vision algorithms in MATLAB.
JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"].ToList<JToken>();
foreach (JToken attribute in attributes)
{
JProperty jProperty = attribute.ToObject<JProperty>();
string propertyName = jProperty.Name;
}
describes and desc command will give list of keyspaces in the cluster.Please find below output for more details.
cqlsh> describe keyspaces
reaper_db system_auth system_distributed
system_schema system system_traces
OR
cqlsh> desc keyspaces
reaper_db system_auth system_distributed
system_schema system system_traces
In the first case you are simply starting a new thread while in the second case you are entering in the thread pool.
The thread pool job is to share and recycle threads. It allows to avoid losing a few millisecond every time we need to create a new thread.
There are a several ways to enter the thread pool:
If you set the image in div, you also must set both height and width. This may cause the image to lose its proportion. In addition, you must set the image URL in CSS instead of HTML.
Instead, you can set the image using the IMG tag. In the container class you can only set the width in percent or pixel and the height will automatically maintain proportion.
This is also more effective for accessibility of search engines and reading engines to define an image using an IMG tag.
.container {_x000D_
margin: auto;_x000D_
width: 200px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
img {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.block {_x000D_
width: 100%;_x000D_
position: absolute;_x000D_
bottom: 0px;_x000D_
top: 0px;_x000D_
box-shadow: inset 0px 0px 10px 20px white;_x000D_
}
_x000D_
<div class="container">_x000D_
<img src="http://lorempixel.com/200/200/city">_x000D_
<div class="block"></div>_x000D_
</div>
_x000D_
With a <script>
right after the <style>
that applies the !important
things, you should be able to do something like this:
var lastStylesheet = document.styleSheets[document.styleSheets.length - 1];
lastStylesheet.disabled = true;
document.write('<style type="text/css">');
// Call fixBackground for each element that needs fixing
document.write('</style>');
lastStylesheet.disabled = false;
function fixBackground(el) {
document.write('html #' + el.id + ' { background-image: ' +
document.defaultView.getComputedStyle(el).backgroundImage +
' !important; }');
}
This probably depends on what kind of browser compatibility you need, though.
That's my workaround.
@property
def language(self):
return self._language
@language.setter
def language(self, value):
# WORKAROUND to get a "getter-only" behavior
# set the value only if the attribute does not exist
try:
if self.language == value:
pass
print("WARNING: Cannot set attribute \'language\'.")
except AttributeError:
self._language = value
This is to answer the part:
I was trying to understand whether dimension tables can be fact table as well or not?
The short answer (INMO) is No.That is because the 2 types of tables are created for different reasons. However, from a database design perspective, a dimension table could have a parent table as the case with the fact table which always has a dimension table (or more) as a parent. Also, fact tables may be aggregated, whereas Dimension tables are not aggregated. Another reason is that fact tables are not supposed to be updated in place whereas Dimension tables could be updated in place in some cases.
More details:
Fact and dimension tables appear in a what is commonly known as a Star Schema. A primary purpose of star schema is to simplify a complex normalized set of tables and consolidate data (possibly from different systems) into one database structure that can be queried in a very efficient way.
On its simplest form, it contains a fact table (Example: StoreSales) and a one or more dimension tables. Each Dimension entry has 0,1 or more fact tables associated with it (Example of dimension tables: Geography, Item, Supplier, Customer, Time, etc.). It would be valid also for the dimension to have a parent, in which case the model is of type "Snow Flake". However, designers attempt to avoid this kind of design since it causes more joins that slow performance. In the example of StoreSales, The Geography dimension could be composed of the columns (GeoID, ContenentName, CountryName, StateProvName, CityName, StartDate, EndDate)
In a Snow Flakes model, you could have 2 normalized tables for Geo information, namely: Content Table, Country Table.
You can find plenty of examples on Star Schema. Also, check this out to see an alternative view on the star schema model Inmon vs. Kimball. Kimbal has a good forum you may also want to check out here: Kimball Forum.
Edit: To answer comment about examples for 4NF:
Sales Fact (ID, BranchID, SalesPersonID, ItemID, Amount, TimeID)
AggregatedSales (BranchID, TotalAmount)
Here the relation is in 4NF
The last example is rather uncommon.
There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.
This can not have a variable:
create function Func() returns table
as
return
select 10 as ColName
You have to do like this instead:
create function Func()
returns @T table(ColName int)
as
begin
declare @Var int
set @Var = 10
insert into @T(ColName) values (@Var)
return
end
If anyone came here trying to do this with a decimal like me:
myFloat = parseFloat(myString);
If you just need an Int, that's well covered in the other answers.
To expand on Ryand's answer, if you're using Bootstrap.ui, this on your modal-instance will do the trick:
modalInstance.rendered.then(function (result) {
$('.modal .modal-body').css('overflow-y', 'auto');
$('.modal .modal-body').css('max-height', $(window).height() * 0.7);
$('.modal .modal-body').css('height', $(window).height() * 0.7);
});
There's no casting in javascript, so you cannot throw if "casting fails".
Typescript supports casting but that's only for compilation time, and you can do it like this:
const toDo = <IToDoDto> req.body;
// or
const toDo = req.body as IToDoDto;
You can check at runtime if the value is valid and if not throw an error, i.e.:
function isToDoDto(obj: any): obj is IToDoDto {
return typeof obj.description === "string" && typeof obj.status === "boolean";
}
@Post()
addToDo(@Response() res, @Request() req) {
if (!isToDoDto(req.body)) {
throw new Error("invalid request");
}
const toDo = req.body as IToDoDto;
this.toDoService.addToDo(toDo);
return res.status(HttpStatus.CREATED).end();
}
As @huyz pointed out, there's no need for the type assertion because isToDoDto
is a type guard, so this should be enough:
if (!isToDoDto(req.body)) {
throw new Error("invalid request");
}
this.toDoService.addToDo(req.body);
Your install is failing because you don't have the python development headers installed. You can do this through apt on ubuntu/debian with:
sudo apt-get install python-dev
for python3 use:
sudo apt-get install python3-dev
For eventlet
you might also need the libevent
libraries installed so if you get an error talking about that you can install libevent with:
sudo apt-get install libevent-dev
when i write import StringIO it says there is no such module.
From What’s New In Python 3.0:
The
StringIO
andcStringIO
modules are gone. Instead, import theio
module and useio.StringIO
orio.BytesIO
for text and data respectively.
.
A possibly useful method of fixing some Python 2 code to also work in Python 3 (caveat emptor):
try:
from StringIO import StringIO ## for Python 2
except ImportError:
from io import StringIO ## for Python 3
Note: This example may be tangential to the main issue of the question and is included only as something to consider when generically addressing the missing
StringIO
module. For a more direct solution the messageTypeError: Can't convert 'bytes' object to str implicitly
, see this answer.
Those are Java varargs. They let you pass any number of objects of a specific type (in this case they are of type JID).
In your example, the following function calls would be valid:
MessageBuilder msgBuilder; //There should probably be a call to a constructor here ;)
MessageBuilder msgBuilder2;
msgBuilder.withRecipientJids(jid1, jid2);
msgBuilder2.withRecipientJids(jid1, jid2, jid78_a, someOtherJid);
See more here: http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html
Anyone wondering about a Font Awesome 5 implementation:
Do not specify a general "Font Awesome 5" font family, you need to specifically end with the branch of icons you're working with. Here I am using the branch "Brands" for example.
<input style="font-family:'Font Awesome 5 Brands' !important"
type="text" placeholder="">
More detail Use Font Awesome (5) icon in input placeholder text
You could just do a simple extension like:
import UIKit
// MARK: - Mixed string utils and helpers
extension String {
/**
Encode a String to Base64
:returns:
*/
func toBase64()->String{
let data = self.dataUsingEncoding(NSUTF8StringEncoding)
return data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
}
}
iOS 7 and up
You have two possibilities:
org.springframework.beans.factory.config.MethodInvokingFactoryBean
to invoke a static setter.In the first option you have a bean with a regular setter but instead setting an instance property you set the static property/field.
public void setTheProperty(Object value) {
foo.bar.Class.STATIC_VALUE = value;
}
but in order to do this you need to have an instance of a bean that will expose this setter (its more like an workaround).
In the second case it would be done as follows:
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="foo.bar.Class.setTheProperty"/> <property name="arguments"> <list> <ref bean="theProperty"/> </list> </property> </bean>
On you case you will add a new setter on the Utils
class:
public static setDataBaseAttr(Properties p)
and in your context you will configure it with the approach exemplified above, more or less like:
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="foo.bar.Utils.setDataBaseAttr"/> <property name="arguments"> <list> <ref bean="dataBaseAttr"/> </list> </property> </bean>
By using cursor you can easily iterate through records individually and print records separately or as a single message including all the records.
DECLARE @CustomerID as INT;
declare @msg varchar(max)
DECLARE @BusinessCursor as CURSOR;
SET @BusinessCursor = CURSOR FOR
SELECT CustomerID FROM Customer WHERE CustomerID IN ('3908745','3911122','3911128','3911421')
OPEN @BusinessCursor;
FETCH NEXT FROM @BusinessCursor INTO @CustomerID;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @msg = '{
"CustomerID": "'+CONVERT(varchar(10), @CustomerID)+'",
"Customer": {
"LastName": "LastName-'+CONVERT(varchar(10), @CustomerID) +'",
"FirstName": "FirstName-'+CONVERT(varchar(10), @CustomerID)+'",
}
}|'
print @msg
FETCH NEXT FROM @BusinessCursor INTO @CustomerID;
END
Here is another solution which uses sub query but instead of IN clause it uses < operator
SELECT MAX(Salary) From Employees WHERE Salary < ( SELECT Max(Salary) FROM Employees);
We have used both and we like Bootstrap for its simplicity and the pace at which it's being developed and enhanced. The problem with jQuery UI is that it's moving at a snail's pace. It's taking years to roll out common features like Menubar, Tree control and DataGrid which are in planning/development stage for ever. We waited waited waited and finally given up and used other libraries like ExtJS for our product http://dblite.com.
Bootstrap has come up with quite a comprehensive set of features in a very short period of time and I am sure it will outpace jQuery UI pretty soon.
So I see no point in using something that will eventually be outdated...
To enable USB Debugging first you need to enable Developer Options.
Open Zenfone Settings and scroll down and tap About.
Scroll down and select Software Information.
Under Software information you will see Build Number.
Tap Build Number 7 times to enable Developer Options.
Come back to Settings and scroll down to find Developer Options.
Tap on Developer Options and it will open upto give you option to enable USB Debugging
Inside cmd
, run command pip install tk
and Tkinter should install.
Your using
statements appear to be correct.
Are you, perhaps, missing the assembly reference to System.configuration.dll
?
Right click the "References" folder in your project and click on "Add Reference..."
We see this constantly, all over our app, using Crashlytics. The crash usually happens way down in platform code. A small sampling:
android.database.CursorWindow.finalize() timed out after 10 seconds
java.util.regex.Matcher.finalize() timed out after 10 seconds
android.graphics.Bitmap$BitmapFinalizer.finalize() timed out after 10 seconds
org.apache.http.impl.conn.SingleClientConnManager.finalize() timed out after 10 seconds
java.util.concurrent.ThreadPoolExecutor.finalize() timed out after 10 seconds
android.os.BinderProxy.finalize() timed out after 10 seconds
android.graphics.Path.finalize() timed out after 10 seconds
The devices on which this happens are overwhelmingly (but not exclusively) devices manufactured by Samsung. That could just mean that most of our users are using Samsung devices; alternately it could indicate a problem with Samsung devices. I'm not really sure.
I suppose this doesn't really answer your questions, but I just wanted to reinforce that this seems quite common, and is not specific to your application.
Followed the steps.
DevKit
to path C:\Ruby193\DevKit
cd C:\Ruby192\DevKit
ruby dk.rb init
ruby dk.rb review
ruby dk.rb install
Then I wrote the command
gem install rails -r -y
Following syntax helped me when I have columns in sequence
awards_frame.values[:,1:4].sum(axis =1)
A better way to set the location in JS is via:
window.location.href = 'https://stackoverflow.com';
Whether to use PHP or JS to manage the redirection depends on what your code is doing and how. But if you're in a position to use PHP; that is, if you're going to be using PHP to send some JS code back to the browser that simply tells the browser to go somewhere else, then logic suggests that you should cut out the middle man and tell the browser directly via PHP.
git clone -b <branch> <remote_repo>
Example:
git clone -b my-branch [email protected]:user/myproject.git
With Git 1.7.10 and later, add --single-branch
to prevent fetching of all branches. Example, with OpenCV 2.4 branch:
git clone -b opencv-2.4 --single-branch https://github.com/Itseez/opencv.git
This is definitely not the best way to do this but, I got it done by doing something like following.
String imageName = "my_image.png";
String replace = imageName.replace('.','~');
String[] split = replace.split("~");
System.out.println("Image name : " + split[0]);
System.out.println("Image extension : " + split[1]);
Output,
Image name : my_image
Image extension : png
The accepted answer works well except for the fact that the javascript is briefly displayed in whatever the ajax target element is. To get around this, create a partial view called _Redirect with the following code:
@model string
<script>
window.location = '@Model';
</script>
Then, in the controller replace
return Redirect(Url.Action("Index", "Home"));
with
return PartialView("_Redirect",Url.Action("Index", "Home"));
The effect is the same as the accepted answer, but without the brief artifact in the display. Place the _Redirect.cshtml in the shared folder so it can be used from anywhere.
You will need to read the bytes
from that File
into a byte[]
and put that object into your JSONObject
.
You should also have a look at the following posts :
Hope this helps.
There is not only 1 %SystemRoot%\System32
on Windows x64. There are 2 such directories.
The real %SystemRoot%\System32
directory is for 64-bit applications. This directory contains a 64-bit cmd.exe
.
But there is also %SystemRoot%\SysWOW64
for 32-bit applications. This directory is used if a 32-bit application accesses %SystemRoot%\System32
. It contains a 32-bit cmd.exe
.
32-bit applications can access %SystemRoot%\System32
for 64-bit applications by using the alias %SystemRoot%\Sysnative
in path.
For more details see the Microsoft documentation about File System Redirector.
So the subdirectory run
was created either in %SystemRoot%\System32
for 64-bit applications and 32-bit cmd
is run for which this directory does not exist because there is no subdirectory run
in %SystemRoot%\SysWOW64
which is %SystemRoot%\System32
for 32-bit cmd.exe
or the subdirectory run
was created in %SystemRoot%\System32
for 32-bit applications and 64-bit cmd
is run for which this directory does not exist because there is no subdirectory run
in %SystemRoot%\System32
as this subdirectory exists only in %SystemRoot%\SysWOW64
.
The following code could be used at top of the batch file in case of subdirectory run
is in %SystemRoot%\System32
for 64-bit applications:
@echo off
set "SystemPath=%SystemRoot%\System32"
if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%\Sysnative\* set "SystemPath=%SystemRoot%\Sysnative"
Every console application in System32\run
directory must be executed with %SystemPath%
in the batch file, for example %SystemPath%\run\YourApp.exe
.
How it works?
There is no environment variable ProgramFiles(x86) on Windows x86 and therefore there is really only one %SystemRoot%\System32
as defined at top.
But there is defined the environment variable ProgramFiles(x86) with a value on Windows x64. So it is additionally checked on Windows x64 if there are files in %SystemRoot%\Sysnative
. In this case the batch file is processed currently by 32-bit cmd.exe
and only in this case %SystemRoot%\Sysnative
needs to be used at all. Otherwise %SystemRoot%\System32
can be used also on Windows x64 as when the batch file is processed by 64-bit cmd.exe
, this is the directory containing the 64-bit console applications (and the subdirectory run
).
Note: %SystemRoot%\Sysnative
is not a directory! It is not possible to cd
to %SystemRoot%\Sysnative
or use if exist %SystemRoot%\Sysnative
or if exist %SystemRoot%\Sysnative\
. It is a special alias existing only for 32-bit executables and therefore it is necessary to check if one or more files exist on using this path by using if exist %SystemRoot%\Sysnative\cmd.exe
or more general if exist %SystemRoot%\Sysnative\*
.
Use dictionary comprehension way,
x = {k:v for k,v in enumerate(states) if v == True}
Input:
states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
Output:
{4: True, 5: True, 7: True}
Solution with custom right drop-down arrow, uses only css (no images)
select {_x000D_
-webkit-appearance: none;_x000D_
-webkit-border-radius: 0px;_x000D_
background-image: linear-gradient(45deg, transparent 50%, gray 50%), linear-gradient(135deg, gray 50%, transparent 50%);_x000D_
background-position: calc(100% - 20px) calc(1em + 2px), calc(100% - 15px) calc(1em + 2px), calc(100% - 2.5em) 0.5em;_x000D_
background-size: 5px 5px, 5px 5px, 1px 1.5em;_x000D_
background-repeat: no-repeat;_x000D_
_x000D_
-moz-appearance: none;_x000D_
display: block;_x000D_
padding: 0.3rem;_x000D_
height: 2rem;_x000D_
width: 100%;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
<br/>_x000D_
<h4>Example</h4>_x000D_
<select>_x000D_
<option></option>_x000D_
<option>Hello</option>_x000D_
<option>World</option>_x000D_
</select>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
I'm using VS SSDT on Windows. I started a project and set up local version control. I later installed git and and created a Github repo. Once I had my repo on Github I grabbed the URL and put that into VS when it asked me for the URL when I hit the "publish to Github" button.
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in dirs:
print os.path.join(root, name)
Walk is a good built-in for what you are doing
for Support Toolbar v7 android.support.v7.widget.Toolbar
:
code
toolbar.setBackground(null);
// or
toolbar.setBackgroundColor(ContextCompat.getColor(getContext(), android.R.color.transparent));
xml (android:background="@null"
or android:background="@android:color/transparent"
)
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="@null"
android:minHeight="?attr/actionBarSize"
android:theme="@style/Theme.AppCompat.Light.DarkActionBar">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:ellipsize="start"
android:singleLine="true"
android:textAppearance="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"/>
</android.support.v7.widget.Toolbar>
if Title is invisible, set textColor
I was using Write #1 "Print my Line" instead I tried Print #1, "Print my Line" and it give me all the data without default Quote(")
Dim strFile_Path As String
strFile_Path = ThisWorkbook.Path & "\" & "XXXX" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".txt"
Open strFile_Path For Output As #1
Dim selectedFeature As String
For counter = 7 To maxNumberOfColumn
selectedFeature = "X"
Print #1, selectedFeature
'Write #1, selectedFeature
Next counter
Close #1
Some ideas:
Maybe you could simply not inherit from the parent in that case (and declare a dependency on base
with the exclusion). Not handy if you have lot of stuff in the parent pom.
Another thing to test would be to declare the mail
artifact with the version required by ALL-DEPS
under the dependencyManagement
in the parent pom to force the convergence (although I'm not sure this will solve the scoping problem).
<dependencyManagement>
<dependencies>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>???</version><!-- put the "right" version here -->
</dependency>
</dependencies>
</dependencyManagement>
mail
dependency from log4j if you're not using the features relying on it (and this is what I would do):<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
</dependency>
You can have a simple class which can be used for this kind of measurements.
class duration_printer {
public:
duration_printer() : __start(std::chrono::high_resolution_clock::now()) {}
~duration_printer() {
using namespace std::chrono;
high_resolution_clock::time_point end = high_resolution_clock::now();
duration<double> dur = duration_cast<duration<double>>(end - __start);
std::cout << dur.count() << " seconds" << std::endl;
}
private:
std::chrono::high_resolution_clock::time_point __start;
};
The only thing is needed to do is to create an object in your function at the beginning of that function
void veryLongExecutingFunction() {
duration_calculator dc;
for(int i = 0; i < 100000; ++i) std::cout << "Hello world" << std::endl;
}
int main() {
veryLongExecutingFunction();
return 0;
}
and that's it. The class can be modified to fit your requirements.