From your FirstActivity call the SecondActivity using startActivityForResult() method.
For example:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
In your SecondActivity set the data which you want to return back to FirstActivity. If you don't want to return back, don't set any.
For example: In secondActivity if you want to send back data:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();
If you don't want to return data:
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
Now in your FirstActivity class write following code for the onActivityResult() method.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
MacOS Sierra users can find their auto-generated vanity URL by going to System Preferences > Sharing
and checking beneath the Computer Name text input. To access it, enter this URL, plus your port number (e.g. your-name.local:8000), on your iPhone over the same Wi-Fi connection as your computer.
In C++: use RAII. Smart pointers like std::unique_ptr
, std::shared_ptr
, std::weak_ptr
are your friends.
If you do "git status" while having a merge conflict, the first thing git shows you is how to abort the merge.
Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N
for the S/U and U/S contention, as in No Conflict.
As for the HOLDLOCK hint the documentation states:
HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.
...
SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...
and the Transaction Isolation Level topic explains what SERIALIZABLE means:
No other transactions can modify data that has been read by the current transaction until the current transaction completes.
Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.
Therefore the behavior you see is perfectly explained by the product documentation:
SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...
After OP edit:
I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.
The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.
I added a directory to svn, then I accidentally deleted the .svn folder within.
I used
svn delete --keep-local folderName
to fix my problem.
I was also developing a similar application. I was also getting not found error even though the file was there. This solve my problem. I mention my download folder in 'static_folder':
app = Flask(__name__,static_folder='pdf')
My code for the download is as follows:
@app.route('/pdf/<path:filename>', methods=['GET', 'POST'])
def download(filename):
return send_from_directory(directory='pdf', filename=filename)
This is how I am calling my file from html.
<a class="label label-primary" href=/pdf/{{ post.hashVal }}.pdf target="_blank" style="margin-right: 5px;">Download pdf </a>
<a class="label label-primary" href=/pdf/{{ post.hashVal }}.png target="_blank" style="margin-right: 5px;">Download png </a>
In Linux, this information is available in the /proc file system. I'm not a big fan of the text file format used, as each Linux distribution seems to customize at least one important file. A quick look as the source to 'ps' reveals the mess.
But here is where to find the information you seek:
/proc/meminfo contains the majority of the system-wide information you seek. Here it looks like on my system; I think you are interested in MemTotal, MemFree, SwapTotal, and SwapFree:
Anderson cxc # more /proc/meminfo
MemTotal: 4083948 kB
MemFree: 2198520 kB
Buffers: 82080 kB
Cached: 1141460 kB
SwapCached: 0 kB
Active: 1137960 kB
Inactive: 608588 kB
HighTotal: 3276672 kB
HighFree: 1607744 kB
LowTotal: 807276 kB
LowFree: 590776 kB
SwapTotal: 2096440 kB
SwapFree: 2096440 kB
Dirty: 32 kB
Writeback: 0 kB
AnonPages: 523252 kB
Mapped: 93560 kB
Slab: 52880 kB
SReclaimable: 24652 kB
SUnreclaim: 28228 kB
PageTables: 2284 kB
NFS_Unstable: 0 kB
Bounce: 0 kB
CommitLimit: 4138412 kB
Committed_AS: 1845072 kB
VmallocTotal: 118776 kB
VmallocUsed: 3964 kB
VmallocChunk: 112860 kB
HugePages_Total: 0
HugePages_Free: 0
HugePages_Rsvd: 0
Hugepagesize: 2048 kB
For CPU utilization, you have to do a little work. Linux makes available overall CPU utilization since system start; this probably isn't what you are interested in. If you want to know what the CPU utilization was for the last second, or 10 seconds, then you need to query the information and calculate it yourself.
The information is available in /proc/stat, which is documented pretty well at http://www.linuxhowtos.org/System/procstat.htm; here is what it looks like on my 4-core box:
Anderson cxc # more /proc/stat
cpu 2329889 0 2364567 1063530460 9034 9463 96111 0
cpu0 572526 0 636532 265864398 2928 1621 6899 0
cpu1 590441 0 531079 265949732 4763 351 8522 0
cpu2 562983 0 645163 265796890 682 7490 71650 0
cpu3 603938 0 551790 265919440 660 0 9040 0
intr 37124247
ctxt 50795173133
btime 1218807985
processes 116889
procs_running 1
procs_blocked 0
First, you need to determine how many CPUs (or processors, or processing cores) are available in the system. To do this, count the number of 'cpuN' entries, where N starts at 0 and increments. Don't count the 'cpu' line, which is a combination of the cpuN lines. In my example, you can see cpu0 through cpu3, for a total of 4 processors. From now on, you can ignore cpu0..cpu3, and focus only on the 'cpu' line.
Next, you need to know that the fourth number in these lines is a measure of idle time, and thus the fourth number on the 'cpu' line is the total idle time for all processors since boot time. This time is measured in Linux "jiffies", which are 1/100 of a second each.
But you don't care about the total idle time; you care about the idle time in a given period, e.g., the last second. Do calculate that, you need to read this file twice, 1 second apart.Then you can do a diff of the fourth value of the line. For example, if you take a sample and get:
cpu 2330047 0 2365006 1063853632 9035 9463 96114 0
Then one second later you get this sample:
cpu 2330047 0 2365007 1063854028 9035 9463 96114 0
Subtract the two numbers, and you get a diff of 396, which means that your CPU had been idle for 3.96 seconds out of the last 1.00 second. The trick, of course, is that you need to divide by the number of processors. 3.96 / 4 = 0.99, and there is your idle percentage; 99% idle, and 1% busy.
In my code, I have a ring buffer of 360 entries, and I read this file every second. That lets me quickly calculate the CPU utilization for 1 second, 10 seconds, etc., all the way up to 1 hour.
For the process-specific information, you have to look in /proc/pid; if you don't care abut your pid, you can look in /proc/self.
CPU used by your process is available in /proc/self/stat. This is an odd-looking file consisting of a single line; for example:
19340 (whatever) S 19115 19115 3084 34816 19115 4202752 118200 607 0 0 770 384 2
7 20 0 77 0 266764385 692477952 105074 4294967295 134512640 146462952 321468364
8 3214683328 4294960144 0 2147221247 268439552 1276 4294967295 0 0 17 0 0 0 0
The important data here are the 13th and 14th tokens (0 and 770 here). The 13th token is the number of jiffies that the process has executed in user mode, and the 14th is the number of jiffies that the process has executed in kernel mode. Add the two together, and you have its total CPU utilization.
Again, you will have to sample this file periodically, and calculate the diff, in order to determine the process's CPU usage over time.
Edit: remember that when you calculate your process's CPU utilization, you have to take into account 1) the number of threads in your process, and 2) the number of processors in the system. For example, if your single-threaded process is using only 25% of the CPU, that could be good or bad. Good on a single-processor system, but bad on a 4-processor system; this means that your process is running constantly, and using 100% of the CPU cycles available to it.
For the process-specific memory information, you ahve to look at /proc/self/status, which looks like this:
Name: whatever
State: S (sleeping)
Tgid: 19340
Pid: 19340
PPid: 19115
TracerPid: 0
Uid: 0 0 0 0
Gid: 0 0 0 0
FDSize: 256
Groups: 0 1 2 3 4 6 10 11 20 26 27
VmPeak: 676252 kB
VmSize: 651352 kB
VmLck: 0 kB
VmHWM: 420300 kB
VmRSS: 420296 kB
VmData: 581028 kB
VmStk: 112 kB
VmExe: 11672 kB
VmLib: 76608 kB
VmPTE: 1244 kB
Threads: 77
SigQ: 0/36864
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: fffffffe7ffbfeff
SigIgn: 0000000010001000
SigCgt: 20000001800004fc
CapInh: 0000000000000000
CapPrm: 00000000ffffffff
CapEff: 00000000fffffeff
Cpus_allowed: 0f
Mems_allowed: 1
voluntary_ctxt_switches: 6518
nonvoluntary_ctxt_switches: 6598
The entries that start with 'Vm' are the interesting ones:
The only item I'm not sure about is Swapspace currently used by my process. I don't know if this is available.
An Essay way :
public class CharToInt{
public static void main(String[] poo){
String ss="toyota";
for(int i=0;i<ss.length();i++)
{
char c = ss.charAt(i);
// int a=c;
System.out.println(c); } }
}
For Output see this link: Click here
Thanks :-)
A good example of where this matters in practice is the ConcurrentSkipListSet
implementation in the JDK, which states:
Beware that, unlike in most collections, the size method is not a constant-time operation.
This is a clear case where isEmpty()
is much more efficient than checking whether size()==0
.
You can see why, intuitively, this might be the case in some collections. If it's the sort of structure where you have to traverse the whole thing to count the elements, then if all you want to know is whether it's empty, you can stop as soon as you've found the first one.
This might be a megabit to late but you can use continue 2
.
Some php builds / configs will output this warning:
PHP Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?
For example:
$i = 1;
while ($i <= 10) {
$mod = $i % 4;
echo "\r\n out $i";
$i++;
switch($mod)
{
case 0:
break;
case 2:
continue;
break;
default:
continue 2;
break;
}
echo " is even";
}
This will output:
out 1
out 2 is even
out 3
out 4 is even
out 5
out 6 is even
out 7
out 8 is even
out 9
out 10 is even
Tested with PHP 5.5 and higher.
--logic FOR OVERLAPPING DATES
DECLARE @StartDate datetime --Reference start date
DECLARE @EndDate datetime --Reference end date
DECLARE @NewStartDate datetime --New Start date
DECLARE @NewEndDate datetime --New End Date
Select
(Case
when @StartDate is null
then @NewStartDate
when (@StartDate<@NewStartDate and @EndDate < @NewStartDate)
then @NewStartDate
when (@StartDate<@NewStartDate and @EndDate > @NewEndDate)
then @NewStartDate
when (@StartDate<@NewStartDate and @EndDate > @NewStartDate)
then @NewStartDate
when (@StartDate>@NewStartDate and @NewEndDate < @StartDate)
then @NewStartDate
else @StartDate end) as StartDate,
(Case
when @EndDate is null
then @NewEndDate
when (@EndDate>@NewEndDate and @Startdate < @NewEndDate)
then @NewEndDate
when (@EndDate>@NewEndDate and @Startdate > @NewEndDate)
then @NewEndDate
when (@EndDate<@NewEndDate and @NewStartDate > @EndDate)
then @NewEndDate
else @EndDate end) as EndDate
Maybe you want more simple and short approach. This will clear all TextBoxes too. (Except TextBoxes inside Panel or GroupBox).
foreach (TextBox textBox in Controls.OfType<TextBox>())
textBox.Text = "";
You need to add your ORACLE_HOME
definition in your listener.ora file. Right now its not registered with any ORACLE_HOME
.
Sample listener.ora
abc =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = abc.kma.com)(PORT = 1521))
)
)
SID_LIST_abc =
(SID_LIST =
(SID_DESC =
(ORACLE_HOME= /abc/DbTier/11.2.0)
(SID_NAME = abc)
)
)
The problem with just setting
_controller.text = "New value";
is that the cursor will be repositioned to the beginning (in material's TextField). Using
_controller.text = "Hello";
_controller.selection = TextSelection.fromPosition(
TextPosition(offset: _controller.text.length),
);
setState(() {});
is not efficient since it rebuilds the widget more than it's necessary (when setting the text property and when calling setState).
--
I believe the best way is to combine everything into one simple command:
final _newValue = "New value";
_controller.value = TextEditingValue(
text: _newValue,
selection: TextSelection.fromPosition(
TextPosition(offset: _newValue.length),
),
);
It works properly for both Material and Cupertino Textfields.
pluginManagement: is an element that is seen along side plugins. Plugin Management contains plugin elements in much the same way, except that rather than configuring plugin information for this particular project build, it is intended to configure project builds that inherit from this one. However, this only configures plugins that are actually referenced within the plugins element in the children. The children have every right to override pluginManagement definitions.
From http://maven.apache.org/pom.html#Plugin%5FManagement
Copied from :
Maven2 - problem with pluginManagement and parent-child relationship
public class JSONPage {
Logger log = Logger.getLogger("com.prodapt.autotest.gui.design.EditTestData");
public static final JFrame JSONFrame = new JFrame();
public final JPanel jPanel = new JPanel();
JLabel IdLabel = new JLabel("JSON ID*");
JLabel DataLabel = new JLabel("JSON Data*");
JFormattedTextField JId = new JFormattedTextField("Auto Generated");
JTextArea JData = new JTextArea();
JButton Cancel = new JButton("Cancel");
JButton Add = new JButton("Add");
public void JsonPage() {
JSONFrame.getContentPane().add(jPanel);
JSONFrame.add(jPanel);
JSONFrame.setSize(400, 250);
JSONFrame.setResizable(false);
JSONFrame.setVisible(false);
JSONFrame.setTitle("Add JSON Data");
JSONFrame.setLocationRelativeTo(null);
jPanel.setLayout(null);
JData.setWrapStyleWord(true);
JId.setEditable(false);
IdLabel.setBounds(20, 30, 120, 25);
JId.setBounds(100, 30, 120, 25);
DataLabel.setBounds(20, 60, 120, 25);
JData.setBounds(100, 60, 250, 75);
Cancel.setBounds(80, 170, 80, 30);
Add.setBounds(280, 170, 50, 30);
jPanel.add(IdLabel);
jPanel.add(JId);
jPanel.add(DataLabel);
jPanel.add(JData);
jPanel.add(Cancel);
jPanel.add(Add);
SwingUtilities.updateComponentTreeUI(JSONFrame);
Cancel.addActionListener(new ActionListener() {
@SuppressWarnings("deprecation")
@Override
public void actionPerformed(ActionEvent e) {
JData.setText("");
JSONFrame.hide();
TestCasePage.testCaseFrame.show();
}
});
Add.addActionListener(new ActionListener() {
@SuppressWarnings("deprecation")
@Override
public void actionPerformed(ActionEvent e) {
try {
PreparedStatement pStatement = DAOHelper.getInstance()
.createJSON(
ConnectionClass.getInstance()
.getConnection());
pStatement.setString(1, null);
if (JData.getText().toString().isEmpty()) {
JOptionPane.showMessageDialog(JSONFrame,
"Must Enter JSON Path");
} else {
// System.out.println(eleSelectBy);
pStatement.setString(2, JData.getText());
pStatement.executeUpdate();
JOptionPane.showMessageDialog(JSONFrame, "!! Added !!");
log.info("JSON Path Added"+JData);
JData.setText("");
JSONFrame.hide();
}
} catch (SQLException e1) {
JData.setText("");
log.info("Error in Adding JSON Path");
e1.printStackTrace();
}
}
});
}
}
Also you can use this
private static final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%";
String urlEncoded = Uri.encode(path, ALLOWED_URI_CHARS);
it's the most simple method
The list is maintaining an object reference to the original value stored in the list. So when you execute this line:
Integer x = i.next();
Both x
and the list are storing a reference to the same object. However, when you execute:
x = Integer.valueOf(9);
nothing has changed in the list, but x
is now storing a reference to a different object. The list has not changed. You need to use some of the list manipulation methods, such as
list.set(index, Integer.valueof(9))
Note: this has nothing to do with the immutability of Integer
, as others are suggesting. This is just basic Java object reference behaviour.
Here's a complete example, to help explain the point. Note that this makes use of the ListIterator
class, which supports removing/setting items mid-iteration:
import java.util.*;
public class ListExample {
public static void main(String[] args) {
List<Foo> fooList = new ArrayList<Foo>();
for (int i = 0; i < 9; i++)
fooList.add(new Foo(i, i));
// Standard iterator sufficient for altering elements
Iterator<Foo> iterator = fooList.iterator();
if (iterator.hasNext()) {
Foo foo = iterator.next();
foo.x = 99;
foo.y = 42;
}
printList(fooList);
// List iterator needed for replacing elements
ListIterator<Foo> listIterator = fooList.listIterator();
if (listIterator.hasNext()) {
// Need to call next, before set.
listIterator.next();
// Replace item returned from next()
listIterator.set(new Foo(99,99));
}
printList(fooList);
}
private static void printList(List<?> list) {
Iterator<?> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next());
}
System.out.println();
}
private static class Foo {
int x;
int y;
Foo(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("[%d, %d]", x, y);
}
}
}
This will print:
[99, 42][1, 1][2, 2][3, 3][4, 4][5, 5][6, 6][7, 7][8, 8]
[99, 99][1, 1][2, 2][3, 3][4, 4][5, 5][6, 6][7, 7][8, 8]
Actually, on 32-bit computers a word is 32-bit, but the DWORD type is a leftover from the good old days of 16-bit.
In order to make it easier to port programs to the newer system, Microsoft has decided all the old types will not change size.
You can find the official list here: http://msdn.microsoft.com/en-us/library/aa383751(VS.85).aspx
All the platform-dependent types that changed with the transition from 32-bit to 64-bit end with _PTR (DWORD_PTR will be 32-bit on 32-bit Windows and 64-bit on 64-bit Windows).
The SELECT ... INTO
needs to be in the select from the CTE.
;WITH Calendar
AS (SELECT /*... Rest of CTE definition removed for clarity*/)
SELECT EventID,
EventStartDate,
EventEndDate,
PlannedDate AS [EventDates],
Cast(PlannedDate AS DATETIME) AS DT,
Cast(EventStartTime AS TIME) AS ST,
Cast(EventEndTime AS TIME) AS ET,
EventTitle,
EventType
INTO TEMPBLOCKEDDATES /* <---- INTO goes here*/
FROM Calendar
WHERE ( PlannedDate >= Getdate() )
AND ',' + EventEnumDays + ',' LIKE '%,' + Cast(Datepart(dw, PlannedDate) AS CHAR(1)) + ',%'
OR EventEnumDays IS NULL
ORDER BY EventID,
PlannedDate
OPTION (maxrecursion 0)
You can just use the Select()
extension method:
IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Select(i => i.ToString());
Or in LINQ syntax:
IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
var strings = from i in integers
select i.ToString();
With the desing support library v23 you can set programmatically the color and the height.
Just use for the height:
TabLayout.setSelectedTabIndicatorHeight(int height)
Here the official javadoc.
Just use for the color:
TabLayout.setSelectedTabIndicatorColor(int color)
Here the official javadoc.
Here you can find the info in the Google Tracker.
make change in changes in /opt/lampp/phpmyadmin/config.inc.php
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* phpMyAdmin sample configuration, you can use it as base for
* manual configuration. For easier setup you can use setup/
*
* All directives are explained in documentation in the doc/ folder
* or at <http://docs.phpmyadmin.net/>.
*
* @package PhpMyAdmin
*/
/**
* This is needed for cookie based authentication to encrypt password in
* cookie
*/
$cfg['blowfish_secret'] = 'xampp'; /* YOU SHOULD CHANGE THIS FOR A MORE SECURE COOKIE AUTH! */
/**
* Servers configuration
*/
$i = 0;
/**
* First server
*/
$i++;
/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
/* Server parameters */
//$cfg['Servers'][$i]['host'] = 'localhost';
//$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['AllowNoPassword'] = true;
/**
* phpMyAdmin configuration storage settings.
*/
/* User used to manipulate with storage */
// $cfg['Servers'][$i]['controlhost'] = '';
// $cfg['Servers'][$i]['controlport'] = '';
$cfg['Servers'][1]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][1]['controluser'] = 'pma';
$cfg['Servers'][1]['controlpass'] = '';
$cfg['Servers'][1]['bookmarktable'] = 'pma_bookmark';
$cfg['Servers'][1]['relation'] = 'pma_relation';
$cfg['Servers'][1]['userconfig'] = 'pma_userconfig';
$cfg['Servers'][1]['table_info'] = 'pma_table_info';
$cfg['Servers'][1]['column_info'] = 'pma_column_info';
$cfg['Servers'][1]['history'] = 'pma_history';
$cfg['Servers'][1]['recent'] = 'pma_recent';
$cfg['Servers'][1]['table_uiprefs'] = 'pma_table_uiprefs';
$cfg['Servers'][1]['tracking'] = 'pma_tracking';
$cfg['Servers'][1]['table_coords'] = 'pma_table_coords';
$cfg['Servers'][1]['pdf_pages'] = 'pma_pdf_pages';
$cfg['Servers'][1]['designer_coords'] = 'pma_designer_coords';
// $cfg['Servers'][$i]['favorite'] = 'pma__favorite';
// $cfg['Servers'][$i]['users'] = 'pma__users';
// $cfg['Servers'][$i]['usergroups'] = 'pma__usergroups';
// $cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
// $cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
// $cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
// $cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
// $cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';
/* Contrib / Swekey authentication */
// $cfg['Servers'][$i]['auth_swekey_config'] = '/etc/swekey-pma.conf';
/**
* End of servers configuration
*/
/**
* Directories for saving/loading files from server
*/
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';
/**
* Whether to display icons or text or both icons and text in table row
* action segment. Value can be either of 'icons', 'text' or 'both'.
* default = 'both'
*/
//$cfg['RowActionType'] = 'icons';
/**
* Defines whether a user should be displayed a "show all (records)"
* button in browse mode or not.
* default = false
*/
//$cfg['ShowAll'] = true;
/**
* Number of rows displayed when browsing a result set. If the result
* set contains more rows, "Previous" and "Next".
* Possible values: 25, 50, 100, 250, 500
* default = 25
*/
//$cfg['MaxRows'] = 50;
/**
* Disallow editing of binary fields
* valid values are:
* false allow editing
* 'blob' allow editing except for BLOB fields
* 'noblob' disallow editing except for BLOB fields
* 'all' disallow editing
* default = 'blob'
*/
//$cfg['ProtectBinary'] = false;
/**
* Default language to use, if not browser-defined or user-defined
* (you find all languages in the locale folder)
* uncomment the desired line:
* default = 'en'
*/
//$cfg['DefaultLang'] = 'en';
//$cfg['DefaultLang'] = 'de';
/**
* How many columns should be used for table display of a database?
* (a value larger than 1 results in some information being hidden)
* default = 1
*/
//$cfg['PropertiesNumColumns'] = 2;
/**
* Set to true if you want DB-based query history.If false, this utilizes
* JS-routines to display query history (lost by window close)
*
* This requires configuration storage enabled, see above.
* default = false
*/
//$cfg['QueryHistoryDB'] = true;
/**
* When using DB-based query history, how many entries should be kept?
* default = 25
*/
//$cfg['QueryHistoryMax'] = 100;
/**
* Whether or not to query the user before sending the error report to
* the phpMyAdmin team when a JavaScript error occurs
*
* Available options
* ('ask' | 'always' | 'never')
* default = 'ask'
*/
//$cfg['SendErrorReports'] = 'always';
/**
* You can find more configuration options in the documentation
* in the doc/ folder or at <http://docs.phpmyadmin.net/>.
*/
One can get the cuda
version by typing the following in the terminal:
$ nvcc -V
# below is the result
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2017 NVIDIA Corporation
Built on Fri_Nov__3_21:07:56_CDT_2017
Cuda compilation tools, release 9.1, V9.1.85
Alternatively, one can manually check for the version by first finding out the installation directory using:
$ whereis -b cuda
cuda: /usr/local/cuda
And then cd
into that directory and check for the CUDA version.
Another way to do this problem besides using ASCII conversions is the following:
String input = "abc".toLowerCase();
final static String alphabet = "abcdefghijklmnopqrstuvwxyz";
for(int i=0; i < input.length(); i++){
System.out.print(alphabet.indexOf(input.charAt(i))+1);
}
Try with cURL request for cross-domain.
If you are working through third party APIs or getting data through CROSS-DOMAIN, it is always recommended to use cURL script (server side) which is more secure.
I always prefer cURL script.
in response to mattlant's reply - sharepoint will work well as a version control only if the version control feature is turned on in the document library. in addition be aware that any code that calls other files by relative paths wont work. and finally any links to external files will break when a file is saved in sharepoint.
model.find({Branch:branch},function (err, docs){
if (err) res.send(err)
res.send(JSON.parse(JSON.stringify(docs)))
});
If you want to save a file to a particular DIRECTORY and FILENAME here is some simple example. It also checks to see if the directory has or has not been created.
import os.path
directory = './html/'
filename = "file.html"
file_path = os.path.join(directory, filename)
if not os.path.isdir(directory):
os.mkdir(directory)
file = open(file_path, "w")
file.write(html)
file.close()
Hope this helps you!
In addition:
AppDomain.CurrentDomain.BaseDirectory
Assembly.GetEntryAssembly().Location
You can use .empty()
, like this:
$("#foo").empty();
Remove all child nodes of the set of matched elements from the DOM.
mylist[c(5,7,9)]
should do it.
You want the sublists returned as sublists of the result list; you don't use [[]]
(or rather, the function is [[
) for that -- as Dason mentions in comments, [[
grabs the element.
.outside {
width: 200px;
height: 200px;
background-color: #EEE; /*to make it visible*/
}
Needs to be
.outside {
position: relative;
width: 200px;
height: 200px;
background-color: #EEE; /*to make it visible*/
}
Absolute positioning looks for the nearest relatively positioned parent within the DOM, if one isn't defined it will use the body.
To clarify and update @neo useful answer and the original question. A clean solution consists of installing Pillow, which is an updated version of the Python Imaging Library (PIL). This is done using
pip install pillow
Once Pillow is installed, the standard Matplotlib commands
import matplotlib.pyplot as plt
plt.plot([1, 2])
plt.savefig('image.jpg')
will save the figure into a JPEG file and will not generate a ValueError any more.
Contrary to @amillerrhodes answer, as of Matplotlib 3.1, JPEG files are still not supported. If I remove the Pillow package I still receive a ValueError about an unsupported file type.
if you mean an anonymous function, and are using a version of Java before Java 8, then in a word, no. (Read about lambda expressions if you use Java 8+)
However, you can implement an interface with a function like so :
Comparator<String> c = new Comparator<String>() {
int compare(String s, String s2) { ... }
};
and you can use this with inner classes to get an almost-anonymous function :)
Sometimes all you have to do to make sure the cursor is inside the text box is: click on the text box and when a menu is displayed, click on "Format text box" then click on the "text box" tab and finally modify all four margins (left, right, upper and bottom) by arrowing down until "0" appear on each margin.
If you are using HUE this is fairly simple as well. Simply go to the Hive editor in HUE, execute your hive query, then save the result file locally as XLS or CSV, or you can save the result file to HDFS.
As of 2016 you can also use the tidyverse
.
library(tidyverse)
samp %>% remove_rownames %>% column_to_rownames(var="names")
You can use \
to indicate that any line of Ruby continues on the next line. This works with strings too:
string = "this is a \
string that spans lines"
puts string.inspect
will output "this is a string that spans lines"
You could write a little, very simple routine that does it, without using a regular expression:
pos
so that is points to just before the opening bracket after your for
or while
. openBr
to 0
.pos
, reading the characters at the respective positions, and increment openBr
when you see an opening bracket, and decrement it when you see a closing bracket. That will increment it once at the beginning, for the first opening bracket in "for (
", increment and decrement some more for some brackets in between, and set it back to 0
when your for
bracket closes. openBr
is 0
again.The stopping positon is your closing bracket of for(...)
. Now you can check if there is a semicolon following or not.
As I think if system is connected to the internet then it's may be an issue of proxy
Do this to delete proxy
npm config delete proxy
To make the server respond with a valid JSONP array, wrap the JSON in brackets ()
and preprend the callback
:
echo $_GET['callback']."([{'fullname' : 'Jeff Hansen'}])";
Using json_encode() will convert a native PHP array into JSON:
$array = array(
'fullname' => 'Jeff Hansen',
'address' => 'somewhere no.3'
);
echo $_GET['callback']."(".json_encode($array).")";
Try withColumn
with the function when
as follows:
val sqlContext = new SQLContext(sc)
import sqlContext.implicits._ // for `toDF` and $""
import org.apache.spark.sql.functions._ // for `when`
val df = sc.parallelize(Seq((4, "blah", 2), (2, "", 3), (56, "foo", 3), (100, null, 5)))
.toDF("A", "B", "C")
val newDf = df.withColumn("D", when($"B".isNull or $"B" === "", 0).otherwise(1))
newDf.show()
shows
+---+----+---+---+
| A| B| C| D|
+---+----+---+---+
| 4|blah| 2| 1|
| 2| | 3| 0|
| 56| foo| 3| 1|
|100|null| 5| 0|
+---+----+---+---+
I added the (100, null, 5)
row for testing the isNull
case.
I tried this code with Spark 1.6.0
but as commented in the code of when
, it works on the versions after 1.4.0
.
I used this solution
OpenQA.Selenium.Chrome.ChromeOptions chromeoptions = new OpenQA.Selenium.Chrome.ChromeOptions();
chromeoptions.AddArgument("--start-maximized");
OpenQA.Selenium.Chrome.ChromeDriver chrome = new OpenQA.Selenium.Chrome.ChromeDriver(chromeoptions);
SELECT SCHEMA_NAME(schema_id) AS schema_name
,name AS view_name
,OBJECTPROPERTYEX(OBJECT_ID,'IsIndexed') AS IsIndexed
,OBJECTPROPERTYEX(OBJECT_ID,'IsIndexable') AS IsIndexable
FROM sys.views
Try trigger on logon
Insted of trying disconnect users you should not allow them to connect.
There is and example of such trigger.
CREATE OR REPLACE TRIGGER rds_logon_trigger
AFTER LOGON ON DATABASE
BEGIN
IF SYS_CONTEXT('USERENV','IP_ADDRESS') not in ('192.168.2.121','192.168.2.123','192.168.2.233') THEN
RAISE_APPLICATION_ERROR(-20003,'You are not allowed to connect to the database');
END IF;
IF (to_number(to_char(sysdate,'HH24'))< 6) and (to_number(to_char(sysdate,'HH24')) >18) THEN
RAISE_APPLICATION_ERROR(-20005,'Logon only allowed during business hours');
END IF;
END;
For future reference, you can get help for any command by using the /?
switch, which should explain what switches do what.
According to the set /?
screen, the format for set /p
is SET /P variable=[promptString]
which would indicate that the p in /p
is "prompt." It just prints in your example because <nul
passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.
/L
in for /L
generates a List of numbers.
From ping /?
:
Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
[-r count] [-s count] [[-j host-list] | [-k host-list]]
[-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name
Options:
-t Ping the specified host until stopped.
To see statistics and continue - type Control-Break;
To stop - type Control-C.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-l size Send buffer size.
-f Set Don't Fragment flag in packet (IPv4-only).
-i TTL Time To Live.
-v TOS Type Of Service (IPv4-only. This setting has been deprecated
and has no effect on the type of service field in the IP Header).
-r count Record route for count hops (IPv4-only).
-s count Timestamp for count hops (IPv4-only).
-j host-list Loose source route along host-list (IPv4-only).
-k host-list Strict source route along host-list (IPv4-only).
-w timeout Timeout in milliseconds to wait for each reply.
-R Use routing header to test reverse route also (IPv6-only).
-S srcaddr Source address to use.
-4 Force using IPv4.
-6 Force using IPv6.
Use ngModelChange
by breaking up the [(x)]
syntax into its two pieces, i.e., property databinding and event binding:
<input type="text" [ngModel]="mymodel" (ngModelChange)="valuechange($event)" />
{{mymodel}}
valuechange(newValue) {
mymodel = newValue;
console.log(newValue)
}
It works for the backspace key too.
The Webpack Dev Server has an option to enable this. Open up package.json
and add --history-api-fallback
.
This solutions worked for me.
For me the main reason of this problem was that I forgot to uncheck AutoLayout
in the Xib
editor.
In fact, I did a lot of adjustments of the XIB
in code.
He was considering having the date as a key, but worried that values will be written one above other, all I wanted to show (maybe not that obvious, that why I do edit) is that he can still have values intact, not written one above other, isn't this okay?!
<?php
$data['may_1_2002']=
Array(
'title_id_32'=>'Good morning',
'title_id_21'=>'Blue sky',
'title_id_3'=>'Summer',
'date'=>'1 May 2002'
);
$data['may_2_2002']=
Array(
'title_id_34'=>'Leaves',
'title_id_20'=>'Old times',
'date'=>'2 May 2002 '
);
echo '<pre>';
print_r($data);
?>
The whole thing to em is, that the size is relative to the base. So I would say you could keep the font sizes by altering the base.
Example: If you base is 16px, and p is .75em (which is 12px) you would have to raise the base to about 20px. In this case p would then equal about 15px which is the minimum I personally require for mobile phones.
Right click properties, Application tab, then see the assembly name and default namespace
This works for me:
FROM postgres:9.6
USER postgres
# Copy postgres config file into container
COPY postgresql.conf /etc/postgresql
# Override default postgres config file
CMD ["postgres", "-c", "config_file=/etc/postgresql/postgresql.conf"]
java.util.Calendar.getInstance()
represents the current time using the current locale and timezone.
You could also choose to import and use Joda-Time or one of the forks for Android.
Just add the *.dll
files to your c:/windows
You can get the java.library.path from the follow codes:and then add you dll files under any path of you get
import java.util.logging.Logger;
public class Test {
static Logger logger = Logger.getLogger(Test.class.getName());
public static void main(String[] args) {
logger.info(System.getProperty("java.library.path"));
}
}
You can use the x
descriptor of the srcset
attribute as such:
<!-- Original image -->
<img src="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png" />
<!-- With a 80% size reduction (1/0.8=1.25) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 1.25x" />
<!-- With a 50% size reduction (1/0.5=2) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 2x" />
_x000D_
Currently supported by all browsers except IE. (caniuse)
Above answer is very correct but I'm giving an easy step to do it:
private static final long[] THREE_CYCLES = new long[] { 100, 1000, 1000, 1000, 1000, 1000 };
public void longVibrate(View v)
{
vibrateMulti(THREE_CYCLES);
}
private void vibrateMulti(long[] cycles) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification();
notification.vibrate = cycles;
notificationManager.notify(0, notification);
}
And then in your xml file:
<button android:layout_height="wrap_content"
android:layout_width ="wrap_content"
android:onclick ="longVibrate"
android:text ="VibrateThrice">
</button>
That's the easiest way.
The article previously mentioned is good. http://forums.oracle.com/forums/thread.jspa?threadID=191750 (as far as it goes)
If this is not something that runs frequently (don't do it on your home page), you can turn off connection pooling.
There is one other "gotcha" that is not mentioned in the article. If the first thing you try to do with the connection is call a stored procedure, ODP will HANG!!!! You will not get back an error condition to manage, just a full bore HANG! The only way to fix it is to turn OFF connection pooling. Once we did that, all issues went away.
Pooling is good in some situations, but at the cost of increased complexity around the first statement of every connection.
If the error handling approach is so good, why don't they make it an option for ODP to handle it for us????
The necessary method is Mockito#verify:
public static <T> T verify(T mock,
VerificationMode mode)
mock
is your mocked object and mode
is the VerificationMode
that describes how the mock should be verified. Possible modes are:
verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");
You'll need these static imports from the Mockito
class in order to use the verify
method and these verification modes:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
So in your case the correct syntax will be:
Mockito.verify(mock, times(4)).send()
This verifies that the method send
was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.
If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode
. A simple
verify(mock).someMethod("was called once");
would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");
.
It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");
, but we can write
verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");
instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.
See the (quite) recent answer on the matplotlib repository, in which the following solution is suggested:
If you want to set the xticklabels:
ax.set_xticks([1,4,5])
ax.set_xticklabels([1,4,5], fontsize=12)
If you want to only increase the fontsize of the xticklabels, using the default values and locations (which is something I personally often need and find very handy):
ax.tick_params(axis="x", labelsize=12)
To do it all at once:
plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold",
horizontalalignment="left")`
An object is only once in memory. Your first addition to list
just adds the object references.
anotherList.addAll
will also just add the references. So still only 100 objects in memory.
If you change list
by adding/removing elements, anotherList
won't be changed. But if you change any object in list
, then it's content will be also changed, when accessing it from anotherList
, because the same reference is being pointed to from both lists.
You can pass an access level to the @Getter
and @Setter
annotations. This is useful to make getters or setters protected or private. It can also be used to override the default.
With @Data
, you have public access to the accessors by default. You can now use the special access level NONE
to completely omit the accessor, like this:
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private int mySecret;
I am not 100% sure what is meant by "running times of my algorithms written in python", so I thought I might try to offer a broader look at some of the potential answers.
Algorithms don't have running times; implementations can be timed, but an algorithm is an abstract approach to doing something. The most common and often the most valuable part of optimizing a program is analyzing the algorithm, usually using asymptotic analysis and computing the big O complexity in time, space, disk use and so forth.
A computer cannot really do this step for you. This requires doing the math to figure out how something works. Optimizing this side of things is the main component to having scalable performance.
You can time your specific implementation. The nicest way to do this in Python is to use timeit. The way it seems most to want to be used is to make a module with a function encapsulating what you want to call and call it from the command line with python -m timeit ...
.
Using timeit to compare multiple snippets when doing microoptimization, but often isn't the correct tool you want for comparing two different algorithms. It is common that what you want is asymptotic analysis, but it's possible you want more complicated types of analysis.
You have to know what to time. Most snippets aren't worth improving. You need to make changes where they actually count, especially when you're doing micro-optimisation and not improving the asymptotic complexity of your algorithm.
If you quadruple the speed of a function in which your code spends 1% of the time, that's not a real speedup. If you make a 20% speed increase on a function in which your program spends 50% of the time, you have a real gain.
To determine the time spent by a real Python program, use the stdlib profiling utilities. This will tell you where in an example program your code is spending its time.
This c++ function always returns the upper case string...
#include <locale>
#include <string>
using namespace std;
string toUpper (string str){
locale loc;
string n;
for (string::size_type i=0; i<str.length(); ++i)
n += toupper(str[i], loc);
return n;
}
The approved answer from George Claghorn worked great for simply inserting text at the cursor position. If the user had selected text though, and you want that text to be replaced (the default experience with most text), you need to make a small change when setting the 'back' variable.
Also, if you don't need to support older versions of IE, modern versions support textarea.selectionStart, so you can take out all of the browser detection, and IE-specific code.
Here is a simplified version that works for Chrome and IE11 at least, and handles replacing selected text.
function insertAtCaret(areaId, text) {
var txtarea = document.getElementById(areaId);
var scrollPos = txtarea.scrollTop;
var caretPos = txtarea.selectionStart;
var front = (txtarea.value).substring(0, caretPos);
var back = (txtarea.value).substring(txtarea.selectionEnd, txtarea.value.length);
txtarea.value = front + text + back;
caretPos = caretPos + text.length;
txtarea.selectionStart = caretPos;
txtarea.selectionEnd = caretPos;
txtarea.focus();
txtarea.scrollTop = scrollPos;
}
You can also use the AWS Data Wrangler:
import awswrangler as wr
wr.s3.to_csv(
df=df,
path="s3://...",
)
Note that it will handle multipart upload for you to make the upload faster.
Try to use:
require('events').EventEmitter.defaultMaxListeners = Infinity;
These all are ways:
String imageUri = "drawable://" + R.drawable.image;
Other ways I tested
Uri path = Uri.parse("android.resource://com.segf4ult.test/" + R.drawable.icon);
Uri otherPath = Uri.parse("android.resource://com.segf4ult.test/drawable/icon");
String path = path.toString();
String path = otherPath .toString();
Implementation is up to compiler developers.
If your question is "what will happen with such declaration" - compiler will set first array element to the value you've provided (0) and all others will be set to zero because it is a default value for omitted array elements.
You can throw an unchecked exception from the method which you wish to roll back. This will be detected by spring and your transaction will be marked as rollback only.
I'm assuming you're using Spring here. And I assume the annotations you refer to in your tests are the spring test based annotations.
The recommended way to indicate to the Spring Framework's transaction infrastructure that a transaction's work is to be rolled back is to throw an Exception from code that is currently executing in the context of a transaction.
and note that:
please note that the Spring Framework's transaction infrastructure code will, by default, only mark a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException.
Within a Python scope, any assignment to a variable not already declared within that scope creates a new local variable unless that variable is declared earlier in the function as referring to a globally scoped variable with the keyword global
.
Let's look at a modified version of your pseudocode to see what happens:
# Here, we're creating a variable 'x', in the __main__ scope.
x = 'None!'
def func_A():
# The below declaration lets the function know that we
# mean the global 'x' when we refer to that variable, not
# any local one
global x
x = 'A'
return x
def func_B():
# Here, we are somewhat mislead. We're actually involving two different
# variables named 'x'. One is local to func_B, the other is global.
# By calling func_A(), we do two things: we're reassigning the value
# of the GLOBAL x as part of func_A, and then taking that same value
# since it's returned by func_A, and assigning it to a LOCAL variable
# named 'x'.
x = func_A() # look at this as: x_local = func_A()
# Here, we're assigning the value of 'B' to the LOCAL x.
x = 'B' # look at this as: x_local = 'B'
return x # look at this as: return x_local
In fact, you could rewrite all of func_B
with the variable named x_local
and it would work identically.
The order matters only as far as the order in which your functions do operations that change the value of the global x. Thus in our example, order doesn't matter, since func_B
calls func_A
. In this example, order does matter:
def a():
global foo
foo = 'A'
def b():
global foo
foo = 'B'
b()
a()
print foo
# prints 'A' because a() was the last function to modify 'foo'.
Note that global
is only required to modify global objects. You can still access them from within a function without declaring global
.
Thus, we have:
x = 5
def access_only():
return x
# This returns whatever the global value of 'x' is
def modify():
global x
x = 'modified'
return x
# This function makes the global 'x' equal to 'modified', and then returns that value
def create_locally():
x = 'local!'
return x
# This function creates a new local variable named 'x', and sets it as 'local',
# and returns that. The global 'x' is untouched.
Note the difference between create_locally
and access_only
-- access_only
is accessing the global x despite not calling global
, and even though create_locally
doesn't use global
either, it creates a local copy since it's assigning a value.
The confusion here is why you shouldn't use global variables.
You can check the HttpContext.Current.User.Identity.IsAuthenticated
property which will allow you to know whether there's a currently authenticated user or not.
If your element is not directly on you scene go back to Parent to remove it
function removeEntity(object) {
var selectedObject = scene.getObjectByName(object.name);
selectedObject.parent.remove( selectedObject );
}
To complete other answers, the gem-path gem can find the installation path of a particular gem.
Installation:
gem install gem-path
Usage:
gem path rails
=> /home/cbliard/.rvm/gems/ruby-2.1.5/gems/rails-4.0.13
gem path rails '< 4'
=> /home/cbliard/.rvm/gems/ruby-2.1.5/gems/rails-3.2.21
This is really handy as you can use it to grep or edit files:
grep -R 'Internal server error' "$(gem path thin)"
subl "$(gem path thin)"
Try using the following, where n
is your variable and x is your offset (4 in this case):
LEFT(ADDRESS(1,n+x,4),1)
This will return the letter of that column (so for n=1 and x=4, it'll return A+4 = E). You can then use INDIRECT()
to reference this, as so:
COLUMNS(INDIRECT(LEFT(ADDRESS(1,n,4),1)&":"&LEFT(ADDRESS(1,n+x,4),1)))
which with n=1, x=4 becomes:
COLUMNS(INDIRECT("A"&":"&"E"))
and so:
COLUMNS(A:E)
The CSS tag 'margin' is actually a shorthand for the four separate margin values, top/left/bottom/right. Use css('marginTop')
, etc. - note they will have 'px' on the end if you have specified them that way.
Use parseInt()
around the result to turn it in to the number value.
NB. As noted by Omaty, the order of the shorthand 'margin' tag is:
top right bottom left
- the above list was not written in a way intended to be the list order, just a list of that specified in the tag.
If your iframe is in the same domain as your parent page you can access the elements using document.frames
collection.
// replace myIFrame with your iFrame id
// replace myIFrameElemId with your iFrame's element id
// you can work on document.frames['myIFrame'].document like you are working on
// normal document object in JS
window.frames['myIFrame'].document.getElementById('myIFrameElemId')
If your iframe is not in the same domain the browser should prevent such access for security reasons.
Just remove the .svn folder inside the required folder then the control will be automatically removed.
The problems you have are because of the extra <form>
you have, that your data goes in GET
method, and you are accessing the data in PHP
using POST
.
<body>
<!--<form>-->
<form action="myprocessingscript.php" method="POST">
MS SQL Server 2012 (and later) has the PERCENTILE_DISC function which computes a specific percentile for sorted values. PERCENTILE_DISC (0.5) will compute the median - https://msdn.microsoft.com/en-us/library/hh231327.aspx
Here is Kotlin version.
Thanks you :)
fun unSafeOkHttpClient() :OkHttpClient.Builder {
val okHttpClient = OkHttpClient.Builder()
try {
// Create a trust manager that does not validate certificate chains
val trustAllCerts: Array<TrustManager> = arrayOf(object : X509TrustManager {
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?){}
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {}
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
})
// Install the all-trusting trust manager
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory = sslContext.socketFactory
if (trustAllCerts.isNotEmpty() && trustAllCerts.first() is X509TrustManager) {
okHttpClient.sslSocketFactory(sslSocketFactory, trustAllCerts.first() as X509TrustManager)
okHttpClient.hostnameVerifier { _, _ -> true }
}
return okHttpClient
} catch (e: Exception) {
return okHttpClient
}
}
You could use import * as
syntax. Although not a class, they are real const
variables.
Constants.js
export const factor = 3;
export const pi = 3.141592;
index.js
import * as Constants from 'Constants.js'
console.log( Constants.factor );
file 1:
int x = 50;
file 2:
extern int x;
printf("%d", x);
My solution goes into a similar direction as Gareth, though I do some things differently.
Here goes:
1. Hide the cells
There is no way to directly hide the cells. UITableViewController
is the data source which provides the static cells, and currently there is no way to tell it "don't provide cell x".
So we have to provide our own data source, which delegates to the UITableViewController
in order to get the static cells.
Easiest is to subclass UITableViewController
, and override all methods which need to behave differently when hiding cells.
In the simplest case (single section table, all cells have the same height), this would go like this:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [super tableView:tableView numberOfRowsInSection:section] - numberOfCellsHidden;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Recalculate indexPath based on hidden cells
indexPath = [self offsetIndexPath:indexPath];
return [super tableView:tableView cellForRowAtIndexPath:indexPath];
}
- (NSIndexPath*)offsetIndexPath:(NSIndexPath*)indexPath
{
int offsetSection = indexPath.section; // Also offset section if you intend to hide whole sections
int numberOfCellsHiddenAbove = ... // Calculate how many cells are hidden above the given indexPath.row
int offsetRow = indexPath.row + numberOfCellsHiddenAbove;
return [NSIndexPath indexPathForRow:offsetRow inSection:offsetSection];
}
If your table has multiple sections, or the cells have differing heights, you need to override more methods. The same principle applies here: You need to offset indexPath, section and row before delegating to super.
Also keep in mind that the indexPath parameter for methods like didSelectRowAtIndexPath:
will be different for the same cell, depending on state (i.e. the number of cells hidden). So it is probably a good idea to always offset any indexPath parameter and work with these values.
2. Animate the change
As Gareth already stated, you get major glitches if you animate changes using reloadSections:withRowAnimation:
method.
I found out that if you call reloadData:
immediately afterwards, the animation is much improved (only minor glitches left). The table is displayed correctly after the animation.
So what I am doing is:
- (void)changeState
{
// Change state so cells are hidden/unhidden
...
// Reload all sections
NSIndexSet* reloadSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [self numberOfSectionsInTableView:tableView])];
[tableView reloadSections:reloadSet withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView reloadData];
}
Check if you have debugCompile
and releaseCompile
in build.gradle. Change it to debugImplementation
and releaseImplementation
. This was how I have solved it, gradle should pass through this successfully marked instructions as deprecated, but suddenly it stucked exactly on this two.
you can also covert int to str first and assign index to it then again convert it to int like this:
int(str(x)[n]) //where x is an integer value
Use ng-disabled or a special CSS class with ng-class
<input data-ng-model="userInf.username"
class="span12 editEmail"
type="text"
placeholder="[email protected]"
pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}"
required
ng-disabled="{expression or condition}"
/>
As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below
git ls-files -z | xargs -0 rm
git checkout -- .
or one line
git ls-files -z | xargs -0 rm ; git checkout -- .
I use it all the time and haven't found any down sides yet!
For some further explanation, the -z
appends a null character onto the end of each entry output by ls-files
, and the -0
tells xargs
to delimit the output it was receiving by those null characters.
Well, here's what worked for me:
Copy and paste the entire data folder, not just the content.
I use xampp, and the path to the data is xampp/mysql/data
.
Goodluck!
The following example demonstrates how to POST a JSON via WebClient.UploadString Method:
var vm = new { k = "1", a = "2", c = "3", v= "4" };
using (var client = new WebClient())
{
var dataString = JsonConvert.SerializeObject(vm);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}
Prerequisites: Json.NET library
The eval()
function evaluates an expression, but "5+5"
is a string, not an expression. Use parse()
with text=<string>
to change the string into an expression:
> eval(parse(text="5+5"))
[1] 10
> class("5+5")
[1] "character"
> class(parse(text="5+5"))
[1] "expression"
Calling eval()
invokes many behaviours, some are not immediately obvious:
> class(eval(parse(text="5+5")))
[1] "numeric"
> class(eval(parse(text="gray")))
[1] "function"
> class(eval(parse(text="blue")))
Error in eval(expr, envir, enclos) : object 'blue' not found
See also tryCatch.
%S
seems to conform to The Single Unix Specification v2 and is also part of the current (2008) POSIX specification.
Equivalent C99 conforming format specifiers would be %s
and %ls
.
You have to disable Globals
/**
* @backupGlobals disabled
*/
You should probably re-write the script to return a value rather than output it. Instead of:
a=$( script.sh ) # Now a is a string, either "success" or "Failed"
case "$a" in
success) echo script succeeded;;
Failed) echo script failed;;
esac
you would be able to do:
if script.sh > /dev/null; then
echo script succeeded
else
echo script failed
fi
It is much simpler for other programs to work with you script if they do not have to parse the output. This is a simple change to make. Just exit 0
instead of printing success
, and exit 1
instead of printing Failed
. Of course, you can also print those values as well as exiting with a reasonable return value, so that wrapper scripts have flexibility in how they work with the script.
a. Serialization - Static members belong to the class and hence can't be serialized.
b. Though we have made the constructor private, static member variables still will be carried to subclass.
c. We can't do lazy initialization as everything will be loaded upon class loading only.
My solution was to run
mysql_upgrade -u root
Scenario: I updated the MySQL version on my Mac with 'homebrew upgrade'. Afterwards, some stuff worked, but other commands raised the error described in the question.
instead of id use title to identify your element and write the code as below.
$(document).ready(()=>{
$("input[title='MyObject']").change(()=>{
console.log("Field has been changed...")
})
});
Look into the File class.
You can create a streamwriter with
StreamWriter sw = File.Create(....)
You can open an existing file with
File.Open(...)
You can append text easily with
File.AppendAllText(...);
import urllib2
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request('http://example.org', data='your_put_data')
request.add_header('Content-Type', 'your/contenttype')
request.get_method = lambda: 'PUT'
url = opener.open(request)
Problems with the stack frames could indicate stack corruption (a truely horrible beast), optimisation, or mixing frameworks such as C/C++/C#/Delphi and other craziness as that - there is no absolute standard with respect to stack frames. (Some languages do not even have them!).
So, I suggest getting slightly annoyed with the stack frame issues, ignoring it, and then just use Remy's answer.
Edit: Seems the OP is running a long script, in that case one only needs to wrap the part of the script after the quality control with
if (n >= 500) {
.... long running code here
}
If breaking out of a function, you'll probably just want return()
, either explicitly or implicitly.
For example, an explicit double return
foo <- function(x) {
if(x < 10) {
return(NA)
} else {
xx <- seq_len(x)
xx <- cumsum(xx)
}
xx ## return(xx) is implied here
}
> foo(5)
[1] 0
> foo(10)
[1] 1 3 6 10 15 21 28 36 45 55
By return()
being implied, I mean that the last line is as if you'd done return(xx)
, but it is slightly more efficient to leave off the call to return()
.
Some consider using multiple returns bad style; in long functions, keeping track of where the function exits can become difficult or error prone. Hence an alternative is to have a single return point, but change the return object using the if () else ()
clause. Such a modification to foo()
would be
foo <- function(x) {
## out is NA or cumsum(xx) depending on x
out <- if(x < 10) {
NA
} else {
xx <- seq_len(x)
cumsum(xx)
}
out ## return(out) is implied here
}
> foo(5)
[1] NA
> foo(10)
[1] 1 3 6 10 15 21 28 36 45 55
The icon file is added to your project as a content file.
What I found works well is as follows:
if you have a placeholder option like 'All' or '-Select-' and its the first option and that's that you want to set the value to when you 'reset' you can use
$('#id').select2('val',0);
0 is essentially the option that you want to set it to on reset. If you want to set it to the last option then get the length of options and set it that length - 1. Basically use the index of whatever option you want to set the select2 value to on reset.
If you don't have a placeholder and just want no text to appear in the field use:
$('#id').select2('val','');
If you put the try/catch inside the loop, you'll keep looping after an exception. If you put it outside the loop you'll stop as soon as an exception is thrown.
s[i:j:k]
is, according to the documentation, "slice of s from i to j with step k". When i
and j
are absent, the whole sequence is assumed and thus s[::k]
means "every k-th item".
First, let's initialize a list:
>>> s = range(20)
>>> s
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Let's take every 3rd item from s
:
>>> s[::3]
[0, 3, 6, 9, 12, 15, 18]
Let's take every 3rd item from s[2:]
:
>>> s[2:]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> s[2::3]
[2, 5, 8, 11, 14, 17]
Let's take every 3rd item from s[5:12]
:
>>> s[5:12]
[5, 6, 7, 8, 9, 10, 11]
>>> s[5:12:3]
[5, 8, 11]
Let's take every 3rd item from s[:10]
:
>>> s[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> s[:10:3]
[0, 3, 6, 9]
One thing that should be considered is licensing.
Notepad++ is free (as in speech and as in beer) for perpetual use, released under the GPL license, whereas Sublime Text 2 requires a license.
To quote the Sublime Text 2 website:
..a license must be purchased for continued use. There is currently no enforced time limit for the evaluation.
The same is now true of Sublime Text 3, and a paid upgrade will be needed for future versions.
Upgrade Policy A license is valid for Sublime Text 3, and includes all point updates, as well as access to prior versions (e.g., Sublime Text 2). Future major versions, such as Sublime Text 4, will be a paid upgrade.
This licensing requirement is still correct as of Dec 2019.
Map<Integer, String> map = new HashMap<>();
map.put(1, "B");
map.put(2, "C");
map.put(3, "D");
map.put(4, "A");
List<String> list = map.values()
.stream()
.sorted()
.collect(Collectors.toList());
Output: [A, B, C, D]
You can try this:
header('Refresh: 10; URL=http://yoursite.com/page.php');
Where 10 is in seconds.
Use the CX register to count the loops
mov cx, 3 startloop: cmp cx, 0 jz endofloop push cx loopy: Call ClrScr pop cx dec cx jmp startloop endofloop: ; Loop ended ; Do what ever you have to do here
This simply loops around 3 times calling ClrScr
, pushing the CX register onto the stack, comparing to 0, jumping if ZeroFlag is set then jump to endofloop
. Notice how the contents of CX is pushed/popped on/off the stack to maintain the flow of the loop.
Because gets
doesn't do any kind of check while getting bytes from stdin and putting them somewhere. A simple example:
char array1[] = "12345";
char array2[] = "67890";
gets(array1);
Now, first of all you are allowed to input how many characters you want, gets
won't care about it. Secondly the bytes over the size of the array in which you put them (in this case array1
) will overwrite whatever they find in memory because gets
will write them. In the previous example this means that if you input "abcdefghijklmnopqrts"
maybe, unpredictably, it will overwrite also array2
or whatever.
The function is unsafe because it assumes consistent input. NEVER USE IT!
Control Panel > Administrative Tools > Services
or simply type
services.msc
in run to open a list of all windows services.World Wide Web Publishing Service
and stop
it. (if you want to disable it permanently you can change its start up type from automatically
to disabled
).That's All
I would use the shebang #!/usr/bin/python
(first line of code) with the serial number of Python at the end ;)
Then run the Python file as a script, e.g., ./main.py
from the command line, rather than python main.py
.
It is the same when you want to run Python from a Linux command line.
<script>
$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('hhttps://example.com/') + '&callback=?', function (data) {
alert(data.contents);
});
</script>
Include jQuery and use this code to get HTML of other website. Replace example.com with your website.
This method involves an external server fetching the sites HTML & sending it to you. :)
Set nocount on
Exec sp_MSForEachTable 'Alter Table ? NoCheck Constraint All'
Exec sp_MSForEachTable
'
If ObjectProperty(Object_ID(''?''), ''TableHasForeignRef'')=1
Begin
-- Just to know what all table used delete syntax.
Print ''Delete from '' + ''?''
Delete From ?
End
Else
Begin
-- Just to know what all table used Truncate syntax.
Print ''Truncate Table '' + ''?''
Truncate Table ?
End
'
Exec sp_MSForEachTable 'Alter Table ? Check Constraint All'
SELECT group, COUNT(*) FROM table GROUP BY group ORDER BY group
or to order by the count
SELECT group, COUNT(*) AS count FROM table GROUP BY group ORDER BY count DESC
Download all actual dependencies of your projects
find your-projects-dir -name pom.xml -exec mvn -f '{}' dependency:resolve
Move your local maven repository to temporary location
mv ~/.m2 ~/saved-m2
Rename all files maven-metadata-central.xml* from saved repository into maven-metadata.xml*
find . -type f -name "maven-metadata-central.xml*" -exec rename -v -- 's/-central//' '{}' \;
To setup the modified copy of the local repository as a mirror, create the directory ~/.m2 and the file ~/.m2/settings.xml with the following content (replacing user with your username):
<settings>
<mirrors>
<mirror>
<id>mycentral</id>
<name>My Central</name>
<url>file:/home/user/saved-m2/</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
</settings>
Resolve your projects dependencies again:
find your-projects-dir -name pom.xml -exec mvn -f '{}' dependency:resolve
Now you have local maven repository with minimal of necessary artifacts. Remove local mirror from config file and from file system.
well, i had a similar problem, so when i entered, lets say: localhost/test.php I would got Object not found warning! I solved my problem when i realized that windows changed my test.php into this test.php.txt. I changed my extension and voila! problem solved I could finaly acceses localhost/test.php.
You can add your own static resource handler (it overwrites the default), e.g.
@Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("file:/path/to/my/dropbox/");
}
}
There is some documentation about this in Spring Boot, but it's really just a vanilla Spring MVC feature.
Also since spring boot 1.2 (I think) you can simply set spring.resources.staticLocations
.
Does anything, easy like that, exists?? THANKS :))
C++ does not store class member names in compiled code, and there's no way to discover (at runtime) which members (variables/methods) class contains. In other words, you cannot iterate through members of a struct. Because there's no such mechanism, you won't be able to automatically create "JSONserialize" for every object.
You can, however, use any json library to serialize objects, BUT you'll have to write serialization/deserialization code yourself for every class. Either that, or you'll have to create serializeable class similar to QVariantMap that'll be used instead of structs for all serializeable objects.
In other words, if you're okay with using specific type for all serializeable objects (or writing serialization routines yourself for every class), it can be done. However, if you want to automatically serialize every possible class, you should forget about it. If this feature is important to you, try another language.
May be it is the problem of using len()
for an integer value.
does not posses the len attribute in Python.
Error as:I will give u an example:
number= 1
print(len(num))
Instead of use ths,
data = [1,2,3,4]
print(len(data))
we can create nested cte.please see the below cte in example
;with cte_data as
(
Select * from [HumanResources].[Department]
),cte_data1 as
(
Select * from [HumanResources].[Department]
)
select * from cte_data,cte_data1
You need to go throgh these scenario:
How about using display:inline-block
?
1) Take one <div/>
give it style=display:inline-block
make it vertical-align:top
and put image inside that div.
2) Take another div and give it also the same style display:inline-block;
and put all the labels/divs inside this div.
Here is the prototype of your requirement
You can also use the pipeline
stage to perform checks on a sub-docunment array
Here's the example using python
(sorry I'm snake people).
db.products.aggregate([
{ '$lookup': {
'from': 'products',
'let': { 'pid': '$products' },
'pipeline': [
{ '$match': { '$expr': { '$in': ['$_id', '$$pid'] } } }
// Add additional stages here
],
'as':'productObjects'
}
])
The catch here is to match all objects in the ObjectId
array
(foreign _id
that is in local
field/prop products
).
You can also clean up or project the foreign records with additional stage
s, as indicated by the comment above.
For the question
How can i run a jar file in command prompt but with arguments
.
To pass arguments to the jar file at the time of execution
java -jar myjar.jar arg1 arg2
In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:
String arg1 = args[0];
String arg2 = args[1];
HTTP and redirects
Let's first recap how ASP.NET MVC works:
Let's also remind ourselves what a redirect is:
An HTTP redirect is a response that the webserver can send to the client, telling the client to look for the requested content under a different URL. The new URL is contained in a Location
header that the webserver returns to the client. In ASP.NET MVC, you do an HTTP redirect by returning a RedirectResult
from an action.
Passing data
If you were just passing simple values like strings and/or integers, you could pass them as query parameters in the URL in the Location
header. This is what would happen if you used something like
return RedirectToAction("ActionName", "Controller", new { arg = updatedResultsDocument });
as others have suggested
The reason that this will not work is that the XDocument
is a potentially very complex object. There is no straightforward way for the ASP.NET MVC framework to serialize the document into something that will fit in a URL and then model bind from the URL value back to your XDocument
action parameter.
In general, passing the document to the client in order for the client to pass it back to the server on the next request, is a very brittle procedure: it would require all sorts of serialisation and deserialisation and all sorts of things could go wrong. If the document is large, it might also be a substantial waste of bandwidth and might severely impact the performance of your application.
Instead, what you want to do is keep the document around on the server and pass an identifier back to the client. The client then passes the identifier along with the next request and the server retrieves the document using this identifier.
Storing data for retrieval on the next request
So, the question now becomes, where does the server store the document in the meantime? Well, that is for you to decide and the best choice will depend upon your particular scenario. If this document needs to be available in the long run, you may want to store it on disk or in a database. If it contains only transient information, keeping it in the webserver's memory, in the ASP.NET cache or the Session
(or TempData
, which is more or less the same as the Session
in the end) may be the right solution. Either way, you store the document under a key that will allow you to retrieve the document later:
int documentId = _myDocumentRepository.Save(updatedResultsDocument);
and then you return that key to the client:
return RedirectToAction("UpdateConfirmation", "ApplicationPoolController ", new { id = documentId });
When you want to retrieve the document, you simply fetch it based on the key:
public ActionResult UpdateConfirmation(int id)
{
XDocument doc = _myDocumentRepository.GetById(id);
ConfirmationModel model = new ConfirmationModel(doc);
return View(model);
}
I used the example by smartcodes with the current version of the Google API, but that one didn't work. I think his API is too outdated.
So, I just wrote my own version, based on one of the API examples... It outputs access token, request token, token type, ID token, expiration time and creation time as strings
If your client credentials and developer key are correct, this code should work out of the box.
<?php
// Call set_include_path() as needed to point to your client library.
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Get Token");
// Visit https://code.google.com/apis/console?api=plus to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
$oauth2 = new Google_Oauth2Service($client);
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
return;
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
?>
<!doctype html>
<html>
<head><meta charset="utf-8"></head>
<body>
<header><h1>Get Token</h1></header>
<?php
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
$token = json_decode($_SESSION['token']);
echo "Access Token = " . $token->access_token . '<br/>';
echo "Refresh Token = " . $token->refresh_token . '<br/>';
echo "Token type = " . $token->token_type . '<br/>';
echo "Expires in = " . $token->expires_in . '<br/>';
echo "ID Token = " . $token->id_token . '<br/>';
echo "Created = " . $token->created . '<br/>';
echo "<a class='logout' href='?logout'>Logout</a>";
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
</body>
</html>
<context:property-placeholder ... />
is the XML equivalent to the PropertyPlaceholderConfigurer.
Example: applicationContext.xml
<context:property-placeholder location="classpath:test.properties"/>
Component class
private @Value("${propertyName}") String propertyField;
Actually, you have it down pat, there's nothing more you need to know :-)
I would just add the following bits:
&
takes a variable and gives you the address, *
takes an address and gives you the variable (or contents).char **p
means that p
is a pointer to a pointer to a char
.As to things working differently, not really:
\0
) character.You can't define an object literal with a dynamic key. Do this :
var o = {};
o[key] = value;
return o;
There's no shortcut (edit: there's one now, with ES6, see the other answer).
The best way I can think of to accomplish this is via sp_addlinkedserver. You need to make sure that whatever account you use to add the link (via sp_addlinkedsrvlogin) has permissions to the table you're joining, but then once the link is established, you can call the server by name, i.e.:
SELECT *
FROM server1table
INNER JOIN server2.database.dbo.server2table ON .....
You don't add or link directly against a DLL, you link against the LIB produced by the DLL.
A LIB provides symbols and other necessary data to either include a library in your code (static linking) or refer to the DLL (dynamic linking).
To link against a LIB, you need to add it to the project Properties -> Linker -> Input -> Additional Dependencies list. All LIB files here will be used in linking. You can also use a pragma like so:
#pragma comment(lib, "dll.lib")
With static linking, the code is included in your executable and there are no runtime dependencies. Dynamic linking requires a DLL with matching name and symbols be available within the search path (which is not just the path or system directory).
Try this...
Calendar calendar = Calendar.getInstance();
String currentDate24Hrs = (String) DateFormat.format(
"MM/dd/yyyy kk:mm:ss", calendar.getTime());
Log.i("DEBUG_TAG", "24Hrs format date: " + currentDate24Hrs);
Given that I just lost a day trying to figure this out and actually found a solution with the help of a coworker, I thought I should chime in.
We have a large code base and we have to deal with 2 branch heavily being modified at the same time. There is a main branch and a secondary branch if you which.
While I merge the secondary branch into the main branch, work continues in the main branch and by the time i'm done, I can't push my changes because they are incompatible.
I therefore need to "rebase" my "merge".
This is how we finally did it :
1) make note of the SHA. ex.: c4a924d458ea0629c0d694f1b9e9576a3ecf506b
git log -1
2) Create the proper history but this will break the merge.
git rebase -s ours --preserve-merges origin/master
3) make note of the SHA. ex.: 29dd8101d78
git log -1
4) Now reset to where you were before
git reset c4a924d458ea0629c0d694f1b9e9576a3ecf506b --hard
5) Now merge the current master into your working branch
git merge origin/master
git mergetool
git commit -m"correct files
6) Now that you have the right files, but the wrong history, get the right history on top of your change with :
git reset 29dd8101d78 --soft
7) And then --amend the results in your original merge commit
git commit --amend
Voila!
you can try this:"Filename.txt" file will be created automatically in the bin->debug folder everytime you run this code or you can specify path of the file like: @"C:/...". you can check ëxistance of "Hello" by going to the bin -->debug folder
P.S dont forget to add Console.Readline() after this code snippet else console will not appear.
TextWriter tw = new StreamWriter("filename.txt");
String text = "Hello";
tw.WriteLine(text);
tw.Close();
TextReader tr = new StreamReader("filename.txt");
Console.WriteLine(tr.ReadLine());
tr.Close();
I use listCollections
(supports MongoDB 3.0 and up) for this purpose.
Example:
db.runCommand({ listCollections: 1, filter: {}, nameOnly: true });
To fetch more information like the index of the collection:
db.runCommand({ listCollections: 1, filter: {}, nameOnly: false });
To print just the collection names:
db.runCommand({ listCollections: 1, filter: {}, nameOnly: true }).cursor.firstBatch.forEach(v => {print(v.name)})
I feel this provides more flexibility.
Read more: listCollections
You need to include angular-route.js
in your HTML:
<script src="angular-route.js">
$arraysAreEqual = ($a == $b); // TRUE if $a and $b have the same key/value pairs.
$arraysAreEqual = ($a === $b); // TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
See Array Operators.
EDIT
The inequality operator is !=
while the non-identity operator is !==
to match the equality
operator ==
and the identity operator ===
.
<form id="myForm">
<select id="selectNumber">
<option>Choose a number</option>
<script>
var myArray = new Array("1", "2", "3", "4", "5" . . . . . "N");
for(i=0; i<myArray.length; i++) {
document.write('<option value="' + myArray[i] +'">' + myArray[i] + '</option>');
}
</script>
</select>
</form>
ones
and zeros
, which create arrays full of ones and zeros respectively, take an optional dtype
parameter:
>>> numpy.ones((2, 2), dtype=bool)
array([[ True, True],
[ True, True]], dtype=bool)
>>> numpy.zeros((2, 2), dtype=bool)
array([[False, False],
[False, False]], dtype=bool)
2008 Answer The "Official" Java API for this is now JAXB - Java API for XML Binding. See Tutorial by Oracle. The reference implementation lives at http://jaxb.java.net/
2018 Update Note that the Java EE and CORBA Modules are deprecated in SE in JDK9 and to be removed from SE in JDK11. Therefore, to use JAXB it will either need to be in your existing enterprise class environment bundled by your e.g. app server, or you will need to bring it in manually.
Right click your Project > Properties > Java Build Path > Libraries
Remove the file with red "X" (something like JRE...)
Add Library
That's how I solved my problem.
In my experience storing all the settings in a database table is the best solution. Don't even worry about performance. Today's databases are fast and can easily store thousands columns in a table. I learned this the hard way - before I was serilizing/deserializing - nightmare. Storing it in local file or registry has one big problem - if you have to support your app and computer is off - user is not in front of it - there is nothing you can do.... if setings are in DB - you can changed them and viola not to mention that you can compare the settings....
SELECT CASE WHEN EXISTS (SELECT TOP 1 *
FROM dbo.[YourTable]
WHERE [YourColumn] = [YourValue])
THEN CAST (1 AS BIT)
ELSE CAST (0 AS BIT) END
This approach returns a boolean for you.
Here is a trick with what you want to achieve. I was also having problem like you.
Its hard to get selected row and data key in RowDeleting Event But it is very easy to get selected row and datakeys in SelectedIndexChanged event. Here's an example-
protected void gv_SelectedIndexChanged(object sender, EventArgs e)
{
int index = gv.SelectedIndex;
int vehicleId = Convert.ToInt32(gv.DataKeys[index].Value);
SqlConnection con = new SqlConnection("-----");
SqlCommand com = new SqlCommand("DELETE FROM tbl WHERE vId = @vId", con);
com.Parameters.AddWithValue("@vId", vehicleId);
con.Open();
com.ExecuteNonQuery();
}
you have type and hit enter :
PowerShell -Command
here is a ghetto way, but it works :)
DateTime dt = DateTime.Now; //get a DateTime variable for the example
string newSecondsValue = "00";
dt = Convert.ToDateTime(dt.ToString("MM/dd/yyyy hh:mm:" + newSecondsValue));
To retrieve data from database:
private SqlConnection Conn;
private void CreateConnection()
{
string ConnStr =
ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
Conn = new SqlConnection(ConnStr);
}
public DataTable getData()
{
CreateConnection();
string SqlString = "SELECT * FROM TableName WHERE SomeID = @SomeID;";
SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
DataTable dt = new DataTable();
try
{
Conn.Open();
sda.Fill(dt);
}
catch (SqlException se)
{
DBErLog.DbServLog(se, se.ToString());
}
finally
{
Conn.Close();
}
return dt;
}
i'd also like to know the right way, but you can always peek either into:
$ cat .git/packed-refs
or:
$ cat .git/refs/tags/*
$(document).ready(function() {
$('#Button').click(function() {
$(this).addClass('active');
});
});
should do the trick. unless you're loading the button with ajax. In which case you could do:
$('#Button').live('click', function() {...
Also remember not to use the same id more than once in your html code.
For what it's worth, for Gecko-based browsers you can't condition this thing off of :visited
due to the resulting privacy leaks. See http://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/
I've had this problem before, you can go to "advanced" tab of "choose a data source" page and click on "suggested types" button, and set the "number of rows" as much as you want. after that, the type and text qualified are set to the true values.
i applied the above solution and can convert my data to SQL.
I'm no expert but I'd say that if you really want to be semantic, you should use vocabularies (RDFa).
This should result in something like that:
<em property="italic" href="http://url/to/a/definition_of_italic"> Your text </em>
em
is used for the presentation (humans will see it in italic) and the property
and href
attributes are linking to a definition of what italic is (for machines).
You should check if there's a vocabulary for that kind of thing, maybe properties already exist.
More info about RDFa here: http://www.alistapart.com/articles/introduction-to-rdfa/
When you want to create an external_table, all field's name must be written in UPPERCASE.
Done.
Memcached is a newer API, it also provides memcached as a session provider which could be great if you have a farm of server.
After the version is still really low 0.2 but I have used both and I didn't encounter major problem, so I would go to memcached since it's new.
You should do mkdir build
and cd build
while inside opencv
folder, not the opencv-contrib
folder. The CMakeLists.txt
is there.
My Solution in laravel 5.2
{{ Form::open(['route' => ['votes.submit', $video->id], 'method' => 'POST']) }}
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-thumbs-up"></span> Votar
</button>
{{ Form::close() }}
My Routes File (under middleware)
Route::post('votar/{id}', [
'as' => 'votes.submit',
'uses' => 'VotesController@submit'
]);
Route::delete('votar/{id}', [
'as' => 'votes.destroy',
'uses' => 'VotesController@destroy'
]);
From MSDN: SqlCommand.ExecuteNonQuery Method
You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.
Although the ExecuteNonQuery returns no rows, any output parameters or return values mapped to parameters are populated with data.
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.
You are using SELECT query, thus you get -1
I couldn't find any good information on this, so I did some trial and error. The following attributes and fields (and only these) are recognized by Jenkins (v1.585).
<?xml version="1.0" encoding="UTF-8"?>
<testsuite>
<!-- if your classname does not include a dot, the package defaults to "(root)" -->
<testcase name="my testcase" classname="my package.my classname" time="29">
<!-- If the test didn't pass, specify ONE of the following 3 cases -->
<!-- option 1 --> <skipped />
<!-- option 2 --> <failure message="my failure message">my stack trace</failure>
<!-- option 3 --> <error message="my error message">my crash report</error>
<system-out>my STDOUT dump</system-out>
<system-err>my STDERR dump</system-err>
</testcase>
</testsuite>
(I started with this sample XML document and worked backwards from there.)
title = u"Klüft skräms inför på fédéral électoral große"
import unicodedata
unicodedata.normalize('NFKD', title).encode('ascii', 'ignore')
'Kluft skrams infor pa federal electoral groe'
This is http authentication. You can find username and password inside users.xml WEB-INF directory if any. otherwise you have to edit or remove security-constraint
element from web.xml file
UPDATE Sorry, I haven't noticed XDB. check if Oracle and tomcat using same port. Update anyone of them
here's what six is:
pip search six
six - Python 2 and 3 compatibility utilities
to install:
pip install six
though if you did install python-dateutil
from pip six should have been set as a dependency.
N.B.: to install pip run easy_install pip
from command line.
TL;DR; If you're still having trouble after restarting apache or nginx, also try restarting the php-fpm
service.
The answers here don't always satisfy the requirement to force a reload of the php.ini file. On numerous occasions I've taken these steps to be rewarded with no update, only to find the solution I need after also restarting the php-fpm service. So if restarting apache or nginx doesn't trigger a php.ini update although you know the files are updated, try restarting php-fpm as well.
To restart the service:
Note: prepend sudo if not root
Using SysV Init scripts directly:
/etc/init.d/php-fpm restart # typical
/etc/init.d/php5-fpm restart # debian-style
/etc/init.d/php7.0-fpm restart # debian-style PHP 7
Using service wrapper script
service php-fpm restart # typical
service php5-fpm restart # debian-style
service php7.0-fpm restart. # debian-style PHP 7
Using Upstart (e.g. ubuntu):
restart php7.0-fpm # typical (ubuntu is debian-based) PHP 7
restart php5-fpm # typical (ubuntu is debian-based)
restart php-fpm # uncommon
Using systemd (newer servers):
systemctl restart php-fpm.service # typical
systemctl restart php5-fpm.service # uncommon
systemctl restart php7.0-fpm.service # uncommon PHP 7
Or whatever the equivalent is on your system.
The above commands taken directly from this server fault answer
It makes sure that the returned object (which is an RValue at that point) can't be modified. This makes sure the user can't do thinks like this:
myFunc() = Object(...);
That would work nicely if myFunc
returned by reference, but is almost certainly a bug when returned by value (and probably won't be caught by the compiler). Of course in C++11 with its rvalues this convention doesn't make as much sense as it did earlier, since a const object can't be moved from, so this can have pretty heavy effects on performance.
You can use any decompiler to first decompile the file.
I had once faced a simillar problem where I didn't have source code of the application and had to make a very small change in a file.
Below is what I did:
Extracted the class file from the jar
Opened it in a decompiler (I use JD GUI, you can get it easily from many resources on internet) You may download it from here
You can actually view all the files in a jar using JD GUI.
Each tablespace has one or more datafiles that it uses to store data.
The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.
To find out if the actual limit is 32gb, run the following:
select value from v$parameter where name = 'db_block_size';
Compare the result you get with the first column below, and that will indicate what your max datafile size is.
I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).
Block Sz Max Datafile Sz (Gb) Max DB Sz (Tb)
-------- -------------------- --------------
2,048 8,192 524,264
4,096 16,384 1,048,528
8,192 32,768 2,097,056
16,384 65,536 4,194,112
32,768 131,072 8,388,224
You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):
select bytes/1024/1024 as mb_size,
maxbytes/1024/1024 as maxsize_set,
x.*
from dba_data_files x
MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).
If your datafile has a low max size or autoextend is not on you could simply run:
alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;
However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:
alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;
As others have said this can be caused when you've not installed an app that is listed in INSTALLED_APPS
.
In my case, manage.py
was attempting to log the exception, which led to an attempt to render it which failed due to the app not being initialized yet. By
commenting out the except
clause in manage.py
the exception was displayed without special rendering, avoiding the confusing error.
# Temporarily commenting out the log statement.
#try:
execute_from_command_line(sys.argv)
#except Exception as e:
# log.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())
# raise e
Integer
is not a primitive, Class.isPrimitive()
is not lying.
This happens when you index a row/column with a number that is larger than the dimensions of your dataframe
. For instance, getting the eleventh column when you have only three.
import pandas as pd
df = pd.DataFrame({'Name': ['Mark', 'Laura', 'Adam', 'Roger', 'Anna'],
'City': ['Lisbon', 'Montreal', 'Lisbon', 'Berlin', 'Glasgow'],
'Car': ['Tesla', 'Audi', 'Porsche', 'Ford', 'Honda']})
You have 5 rows and three columns:
Name City Car
0 Mark Lisbon Tesla
1 Laura Montreal Audi
2 Adam Lisbon Porsche
3 Roger Berlin Ford
4 Anna Glasgow Honda
Let's try to index the eleventh column (it doesn't exist):
df.iloc[:, 10] # there is obviously no 11th column
IndexError: single positional indexer is out-of-bounds
If you are a beginner with Python, remember that df.iloc[:, 10]
would refer to the eleventh column.
Took me a while to find this out but if you a number stored in a variable, say x and you want to select it, use
document.querySelector('a[data-a= + CSS.escape(x) + ']').
This is due to some attribute naming specifications that I'm not yet very familiar with. Hope this will help someone.
/^\d+(\.\d{1,2})?$/
var regexp = /^\d+(\.\d{1,2})?$/;_x000D_
_x000D_
console.log("'.74' returns " + regexp.test('.74'));_x000D_
console.log("'7' returns " + regexp.test('7'));_x000D_
console.log("'10.5' returns " + regexp.test('10.5'));_x000D_
console.log("'115.25' returns " + regexp.test('115.25'));_x000D_
console.log("'1535.803' returns " + regexp.test('1535.803'));_x000D_
console.log("'153.14.5' returns " + regexp.test('153.14.5'));_x000D_
console.log("'415351108140' returns " + regexp.test('415351108140'));_x000D_
console.log("'415351108140.5' returns " + regexp.test('415351108140.5'));_x000D_
console.log("'415351108140.55' returns " + regexp.test('415351108140.55'));_x000D_
console.log("'415351108140.556' returns " + regexp.test('415351108140.556'));
_x000D_
/ /
: the beginning and end of the expression^
: whatever follows should be at the beginning of the string you're testing\d+
: there should be at least one digit( )?
: this part is optional\.
: here goes a dot\d{1,2}
: there should be between one and two digits here$
: whatever precedes this should be at the end of the string you're testingYou can use regexr.com or regex101.com for testing regular expressions directly in the browser!
You can declare as many Exceptions as you want for your interface method. But the class you gave in your question is invalid. It should read
public class MyClass implements MyInterface {
public void find(int x) throws A_Exception, B_Exception{
----
----
---
}
}
Then an interface would look like this
public interface MyInterface {
void find(int x) throws A_Exception, B_Exception;
}
Simple extension for UIApplication in Swift (cares even about moreNavigationController within UITabBarController
on iPhone):
extension UIApplication {
class func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(base: nav.visibleViewController)
}
if let tab = base as? UITabBarController {
let moreNavigationController = tab.moreNavigationController
if let top = moreNavigationController.topViewController where top.view.window != nil {
return topViewController(top)
} else if let selected = tab.selectedViewController {
return topViewController(selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(base: presented)
}
return base
}
}
Simple usage:
if let rootViewController = UIApplication.topViewController() {
//do sth with root view controller
}
Works perfect:-)
UPDATE for clean code:
extension UIViewController {
var top: UIViewController? {
if let controller = self as? UINavigationController {
return controller.topViewController?.top
}
if let controller = self as? UISplitViewController {
return controller.viewControllers.last?.top
}
if let controller = self as? UITabBarController {
return controller.selectedViewController?.top
}
if let controller = presentedViewController {
return controller.top
}
return self
}
}
I just recently wrote a c# app that had to restart daily. I realize this question is old but I don't think it hurts to add another possible solution. This is how I handled daily restarts at a specified time.
public void RestartApp()
{
AppRestart = AppRestart.AddHours(5);
AppRestart = AppRestart.AddMinutes(30);
DateTime current = DateTime.Now;
if (current > AppRestart) { AppRestart = AppRestart.AddDays(1); }
TimeSpan UntilRestart = AppRestart - current;
int MSUntilRestart = Convert.ToInt32(UntilRestart.TotalMilliseconds);
tmrRestart.Interval = MSUntilRestart;
tmrRestart.Elapsed += tmrRestart_Elapsed;
tmrRestart.Start();
}
To ensure your timer is kept in scope I recommend creating it outside of the method using System.Timers.Timer tmrRestart = new System.Timers.Timer()
method. Put the method RestartApp()
in your form load event. When the application launches it will set the values for AppRestart
if current
is greater than the restart time we add 1 day to AppRestart
to ensure the restart happens on time and that we don't get an exception for putting a negative value into the timer. In the tmrRestart_Elapsed
event run whatever code you need ran at that specific time. If your application restarts on it's own you don't necessarily have to stop the timer but it doesn't hurt either, If the application does not restart simply call the RestartApp()
method again and you will be good to go.
How about the PATINDEX function?
The pattern matching in TSQL is not a complete regex library, but it gives you the basics.
(From Books Online)
Wildcard Meaning
% Any string of zero or more characters.
_ Any single character.
[ ] Any single character within the specified range
(for example, [a-f]) or set (for example, [abcdef]).
[^] Any single character not within the specified range
(for example, [^a - f]) or set (for example, [^abcdef]).
The JSON spec says you CAN escape forward slash, but you don't have to.
Here is an example Dockerfile leveraging several clever techniques to all you to run a full conda environment for every RUN
stanza. You can use a similar approach to execute any arbitrary prep in a script file.
Note: there is a lot of nuance when it comes to login/interactive vs nonlogin/noninteractive shells, signals, exec
, the way multiple args are handled, quoting, how CMD and ENTRYPOINT interact, and a million other things, so don't be discouraged if when hacking around with these things, stuff goes sideways. I've spent many frustrating hours digging through all manner of literature and I still don't quite get how it all clicks.
## Conda with custom entrypoint from base ubuntu image
## Build with e.g. `docker build -t monoconda .`
## Run with `docker run --rm -it monoconda bash` to drop right into
## the environment `foo` !
FROM ubuntu:18.04
## Install things we need to install more things
RUN apt-get update -qq &&\
apt-get install -qq curl wget git &&\
apt-get install -qq --no-install-recommends \
libssl-dev \
software-properties-common \
&& rm -rf /var/lib/apt/lists/*
## Install miniconda
RUN wget -nv https://repo.anaconda.com/miniconda/Miniconda3-4.7.12-Linux-x86_64.sh -O ~/miniconda.sh && \
/bin/bash ~/miniconda.sh -b -p /opt/conda && \
rm ~/miniconda.sh && \
/opt/conda/bin/conda clean -tipsy && \
ln -s /opt/conda/etc/profile.d/conda.sh /etc/profile.d/conda.sh
## add conda to the path so we can execute it by name
ENV PATH=/opt/conda/bin:$PATH
## Create /entry.sh which will be our new shell entry point. This performs actions to configure the environment
## before starting a new shell (which inherits the env).
## The exec is important! This allows signals to pass
RUN (echo '#!/bin/bash' \
&& echo '__conda_setup="$(/opt/conda/bin/conda shell.bash hook 2> /dev/null)"' \
&& echo 'eval "$__conda_setup"' \
&& echo 'conda activate "${CONDA_TARGET_ENV:-base}"' \
&& echo '>&2 echo "ENTRYPOINT: CONDA_DEFAULT_ENV=${CONDA_DEFAULT_ENV}"' \
&& echo 'exec "$@"'\
) >> /entry.sh && chmod +x /entry.sh
## Tell the docker build process to use this for RUN.
## The default shell on Linux is ["/bin/sh", "-c"], and on Windows is ["cmd", "/S", "/C"]
SHELL ["/entry.sh", "/bin/bash", "-c"]
## Now, every following invocation of RUN will start with the entry script
RUN conda update conda -y
## Create a dummy env
RUN conda create --name foo
## I added this variable such that I have the entry script activate a specific env
ENV CONDA_TARGET_ENV=foo
## This will get installed in the env foo since it gets activated at the start of the RUN stanza
RUN conda install pip
## Configure .bashrc to drop into a conda env and immediately activate our TARGET env
RUN conda init && echo 'conda activate "${CONDA_TARGET_ENV:-base}"' >> ~/.bashrc
ENTRYPOINT ["/entry.sh"]
In the receiving activity
Bundle extras = getIntent().getExtras();
String userName;
if (extras != null) {
userName = extras.getString("name");
// and get whatever type user account id is
}
For anyone who wants to sort the variable in third layer:
<select ng-option="friend.pet.name for friend in friends"></select>
you can do it like this
<select ng-option="friend.pet.name for friend in friends | orderBy: 'pet.name'"></select>
Ed McManus has certainly provided a key to getting this to work. I found a case that does not work
UIFont *font = ...
UIColor *color = ...
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
font, NSFontAttributeName,
color, NSForegroundColorAttributeName,
nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString: someString attributes:attributesDictionary];
[string appendAttributedString: [[NSAttributedString alloc] initWithString: anotherString];
CGRect rect = [string boundingRectWithSize:constraint options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) context:nil];
rect will not have the correct height. Notice that anotherString (which is appended to string) was initialized without an attribute dictionary. This is a legitimate initializer for anotherString but boundingRectWithSize: does not give an accurate size in this case.
In C++11 you can easily avoid inheritance altogether:
struct Interface {
explicit Interface(SomeType& other)
: foo([=](){ return other.my_foo(); }),
bar([=](){ return other.my_bar(); }), /*...*/ {}
explicit Interface(SomeOtherType& other)
: foo([=](){ return other.some_foo(); }),
bar([=](){ return other.some_bar(); }), /*...*/ {}
// you can add more types here...
// or use a generic constructor:
template<class T>
explicit Interface(T& other)
: foo([=](){ return other.foo(); }),
bar([=](){ return other.bar(); }), /*...*/ {}
const std::function<void(std::string)> foo;
const std::function<void(std::string)> bar;
// ...
};
In this case, an Interface has reference semantics, i.e. you have to make sure that the object outlives the interface (it is also possible to make interfaces with value semantics).
These type of interfaces have their pros and cons:
Finally, inheritance is the root of all evil in complex software design. In Sean Parent's Value Semantics and Concepts-based Polymorphism (highly recommended, better versions of this technique are explained there) the following case is studied:
Say I have an application in which I deal with my shapes polymorphically using the MyShape
interface:
struct MyShape { virtual void my_draw() = 0; };
struct Circle : MyShape { void my_draw() { /* ... */ } };
// more shapes: e.g. triangle
In your application, you do the same with different shapes using the YourShape
interface:
struct YourShape { virtual void your_draw() = 0; };
struct Square : YourShape { void your_draw() { /* ... */ } };
/// some more shapes here...
Now say you want to use some of the shapes that I've developed in your application. Conceptually, our shapes have the same interface, but to make my shapes work in your application you would need to extend my shapes as follows:
struct Circle : MyShape, YourShape {
void my_draw() { /*stays the same*/ };
void your_draw() { my_draw(); }
};
First, modifying my shapes might not be possible at all. Furthermore, multiple inheritance leads the road to spaghetti code (imagine a third project comes in that is using the TheirShape
interface... what happens if they also call their draw function my_draw
?).
Update: There are a couple of new references about non-inheritance based polymorphism:
can you try
<p:column width="20">
Here is a solution for Win32 Console.
1) Get JavaNativeAccess libraries here: https://github.com/twall/jna/
2) These two Java classes will do the trick.
Enjoy.
package com.stackoverflow.util;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.Structure;
public class Win32 {
public static final int STD_INPUT_HANDLE = -10;
public static final int STD_OUTPUT_HANDLE = -11;
public static final int STD_ERROR_HANDLE = -12;
public static final short CONSOLE_FOREGROUND_COLOR_BLACK = 0x00;
public static final short CONSOLE_FOREGROUND_COLOR_BLUE = 0x01;
public static final short CONSOLE_FOREGROUND_COLOR_GREEN = 0x02;
public static final short CONSOLE_FOREGROUND_COLOR_AQUA = 0x03;
public static final short CONSOLE_FOREGROUND_COLOR_RED = 0x04;
public static final short CONSOLE_FOREGROUND_COLOR_PURPLE = 0x05;
public static final short CONSOLE_FOREGROUND_COLOR_YELLOW = 0x06;
public static final short CONSOLE_FOREGROUND_COLOR_WHITE = 0x07;
public static final short CONSOLE_FOREGROUND_COLOR_GRAY = 0x08;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_BLUE = 0x09;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_GREEN = 0x0A;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_AQUA = 0x0B;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_RED = 0x0C;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_PURPLE = 0x0D;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_YELLOW = 0x0E;
public static final short CONSOLE_FOREGROUND_COLOR_BRIGHT_WHITE = 0x0F;
public static final short CONSOLE_BACKGROUND_COLOR_BLACK = 0x00;
public static final short CONSOLE_BACKGROUND_COLOR_BLUE = 0x10;
public static final short CONSOLE_BACKGROUND_COLOR_GREEN = 0x20;
public static final short CONSOLE_BACKGROUND_COLOR_AQUA = 0x30;
public static final short CONSOLE_BACKGROUND_COLOR_RED = 0x40;
public static final short CONSOLE_BACKGROUND_COLOR_PURPLE = 0x50;
public static final short CONSOLE_BACKGROUND_COLOR_YELLOW = 0x60;
public static final short CONSOLE_BACKGROUND_COLOR_WHITE = 0x70;
public static final short CONSOLE_BACKGROUND_COLOR_GRAY = 0x80;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_BLUE = 0x90;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_GREEN = 0xA0;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_AQUA = 0xB0;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_RED = 0xC0;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_PURPLE = 0xD0;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_YELLOW = 0xE0;
public static final short CONSOLE_BACKGROUND_COLOR_BRIGHT_WHITE = 0xF0;
// typedef struct _COORD {
// SHORT X;
// SHORT Y;
// } COORD, *PCOORD;
public static class COORD extends Structure {
public short X;
public short Y;
}
// typedef struct _SMALL_RECT {
// SHORT Left;
// SHORT Top;
// SHORT Right;
// SHORT Bottom;
// } SMALL_RECT;
public static class SMALL_RECT extends Structure {
public short Left;
public short Top;
public short Right;
public short Bottom;
}
// typedef struct _CONSOLE_SCREEN_BUFFER_INFO {
// COORD dwSize;
// COORD dwCursorPosition;
// WORD wAttributes;
// SMALL_RECT srWindow;
// COORD dwMaximumWindowSize;
// } CONSOLE_SCREEN_BUFFER_INFO;
public static class CONSOLE_SCREEN_BUFFER_INFO extends Structure {
public COORD dwSize;
public COORD dwCursorPosition;
public short wAttributes;
public SMALL_RECT srWindow;
public COORD dwMaximumWindowSize;
}
// Source: https://github.com/twall/jna/nonav/javadoc/index.html
public interface Kernel32 extends Library {
Kernel32 DLL = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);
// HANDLE WINAPI GetStdHandle(
// __in DWORD nStdHandle
// );
public int GetStdHandle(
int nStdHandle);
// BOOL WINAPI SetConsoleTextAttribute(
// __in HANDLE hConsoleOutput,
// __in WORD wAttributes
// );
public boolean SetConsoleTextAttribute(
int in_hConsoleOutput,
short in_wAttributes);
// BOOL WINAPI GetConsoleScreenBufferInfo(
// __in HANDLE hConsoleOutput,
// __out PCONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo
// );
public boolean GetConsoleScreenBufferInfo(
int in_hConsoleOutput,
CONSOLE_SCREEN_BUFFER_INFO out_lpConsoleScreenBufferInfo);
// DWORD WINAPI GetLastError(void);
public int GetLastError();
}
}
package com.stackoverflow.util;
import java.io.PrintStream;
import com.stackoverflow.util.Win32.Kernel32;
public class ConsoleUtil {
public static void main(String[] args)
throws Exception {
System.out.print("abc");
static_color_print(
System.out,
"def",
Win32.CONSOLE_BACKGROUND_COLOR_RED,
Win32.CONSOLE_FOREGROUND_COLOR_BRIGHT_WHITE);
System.out.print("def");
System.out.println();
}
private static Win32.CONSOLE_SCREEN_BUFFER_INFO _static_console_screen_buffer_info = null;
public static void static_save_settings() {
if (null == _static_console_screen_buffer_info) {
_static_console_screen_buffer_info = new Win32.CONSOLE_SCREEN_BUFFER_INFO();
}
int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
Kernel32.DLL.GetConsoleScreenBufferInfo(stdout_handle, _static_console_screen_buffer_info);
}
public static void static_restore_color()
throws Exception {
if (null == _static_console_screen_buffer_info) {
throw new Exception("Internal error: Must save settings before restore");
}
int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
Kernel32.DLL.SetConsoleTextAttribute(
stdout_handle,
_static_console_screen_buffer_info.wAttributes);
}
public static void static_set_color(Short background_color, Short foreground_color) {
int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
if (null == background_color || null == foreground_color) {
Win32.CONSOLE_SCREEN_BUFFER_INFO console_screen_buffer_info =
new Win32.CONSOLE_SCREEN_BUFFER_INFO();
Kernel32.DLL.GetConsoleScreenBufferInfo(stdout_handle, console_screen_buffer_info);
short current_bg_and_fg_color = console_screen_buffer_info.wAttributes;
if (null == background_color) {
short current_bg_color = (short) (current_bg_and_fg_color / 0x10);
background_color = new Short(current_bg_color);
}
if (null == foreground_color) {
short current_fg_color = (short) (current_bg_and_fg_color % 0x10);
foreground_color = new Short(current_fg_color);
}
}
short bg_and_fg_color =
(short) (background_color.shortValue() | foreground_color.shortValue());
Kernel32.DLL.SetConsoleTextAttribute(stdout_handle, bg_and_fg_color);
}
public static<T> void static_color_print(
PrintStream ostream,
T value,
Short background_color,
Short foreground_color)
throws Exception {
static_save_settings();
try {
static_set_color(background_color, foreground_color);
ostream.print(value);
}
finally {
static_restore_color();
}
}
public static<T> void static_color_println(
PrintStream ostream,
T value,
Short background_color,
Short foreground_color)
throws Exception {
static_save_settings();
try {
static_set_color(background_color, foreground_color);
ostream.println(value);
}
finally {
static_restore_color();
}
}
}
To avoid deprecated opts
and theme_rect
use:
myplot + theme(panel.background = element_rect(fill='green', colour='red'))
To define your own custom theme, based on theme_gray but with some of your changes and a few added extras including control of gridline colour/size (more options available to play with at ggplot2.org):
theme_jack <- function (base_size = 12, base_family = "") {
theme_gray(base_size = base_size, base_family = base_family) %+replace%
theme(
axis.text = element_text(colour = "white"),
axis.title.x = element_text(colour = "pink", size=rel(3)),
axis.title.y = element_text(colour = "blue", angle=45),
panel.background = element_rect(fill="green"),
panel.grid.minor.y = element_line(size=3),
panel.grid.major = element_line(colour = "orange"),
plot.background = element_rect(fill="red")
)
}
To make your custom theme the default when ggplot is called in future, without masking:
theme_set(theme_jack())
If you want to change an element of the currently set theme:
theme_update(plot.background = element_rect(fill="pink"), axis.title.x = element_text(colour = "red"))
To store the current default theme as an object:
theme_pink <- theme_get()
Note that theme_pink
is a list whereas theme_jack
was a function. So to return the theme to theme_jack use theme_set(theme_jack())
whereas to return to theme_pink use theme_set(theme_pink)
.
You can replace theme_gray
by theme_bw
in the definition of theme_jack
if you prefer. For your custom theme to resemble theme_bw
but with all gridlines (x, y, major and minor) turned off:
theme_nogrid <- function (base_size = 12, base_family = "") {
theme_bw(base_size = base_size, base_family = base_family) %+replace%
theme(
panel.grid = element_blank()
)
}
Finally a more radical theme useful when plotting choropleths or other maps in ggplot, based on discussion here but updated to avoid deprecation. The aim here is to remove the gray background, and any other features that might distract from the map.
theme_map <- function (base_size = 12, base_family = "") {
theme_gray(base_size = base_size, base_family = base_family) %+replace%
theme(
axis.line=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks=element_blank(),
axis.ticks.length=unit(0.3, "lines"),
axis.ticks.margin=unit(0.5, "lines"),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
legend.background=element_rect(fill="white", colour=NA),
legend.key=element_rect(colour="white"),
legend.key.size=unit(1.2, "lines"),
legend.position="right",
legend.text=element_text(size=rel(0.8)),
legend.title=element_text(size=rel(0.8), face="bold", hjust=0),
panel.background=element_blank(),
panel.border=element_blank(),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
panel.margin=unit(0, "lines"),
plot.background=element_blank(),
plot.margin=unit(c(1, 1, 0.5, 0.5), "lines"),
plot.title=element_text(size=rel(1.2)),
strip.background=element_rect(fill="grey90", colour="grey50"),
strip.text.x=element_text(size=rel(0.8)),
strip.text.y=element_text(size=rel(0.8), angle=-90)
)
}
try this javascript
Snippet for getting the parameters from URL. Use javascript to get the URL parameters either from current window location or static URL into the argument for the function call.
javascript
function getUrlParameters(parameter, staticURL, decode){
var currLocation = (staticURL.length)? staticURL : window.location.search,
parArr = currLocation.split("?")[1].split("&"),
returnBool = true;
for(var i = 0; i < parArr.length; i++){
parr = parArr[i].split("=");
if(parr[0] == parameter){
return (decode) ? decodeURIComponent(parr[1]) : parr[1];
returnBool = true;
}else{
returnBool = false;
}
}
if(!returnBool) return false;
}
To get the parameter “id” from above static URL, use the following:
var idParameter = getUrlParameters("id", "http://www.example.com?id=1234&auth=true", true);
or
var idParameter = getUrlParameters("id", "", true);
It's the '+' operator at the beginning of the line that trips things up (not just that you are using two '+' operators consecutively). The '+' operator can be used at the end of lines, but not at the beginning.
This works:
ggplot(combined.data, aes(x = region, y = expression, fill = species)) +
geom_boxplot()
The does not:
ggplot(combined.data, aes(x = region, y = expression, fill = species))
+ geom_boxplot()
*Error in + geom_boxplot():
invalid argument to unary operator*
You also can't use two '+' operators, which in this case you've done. But to fix this, you'll have to selectively remove those at the beginning of lines.
For Win Forms :
To get the value (assuming that you want the value, not the text) out of a radio button, you get the Checked property:
string value = "";
bool isChecked = radioButton1.Checked;
if(isChecked )
value=radioButton1.Text;
else
value=radioButton2.Text;
For Web Forms :
<asp:RadioButtonList ID="rdoPriceRange" runat="server" RepeatLayout="Flow">
<asp:ListItem Value="Male">Male</asp:ListItem>
<asp:ListItem Value="Female">Female</asp:ListItem>
</asp:RadioButtonList>
And CS-in some button click
string value=rdoPriceRange.SelectedItem.Value.ToString();
Following the advice from NibblyPig and zendar, I came up with the code below, which works on every test I made. I ended up needing both the ping, and the poll. The ping will let me know if the cable has been disconnected, or the physical layer otherwise disrupted (router powered off, etc). But sometimes after reconnect I get a RST, the ping is ok, but the tcp state is not.
#region CHECKS THE SOCKET'S HEALTH
if (_tcpClient.Client.Connected)
{
//Do a ping test to see if the server is reachable
try
{
Ping pingTest = new Ping()
PingReply reply = pingTest.Send(ServeripAddress);
if (reply.Status != IPStatus.Success) ConnectionState = false;
} catch (PingException) { ConnectionState = false; }
//See if the tcp state is ok
if (_tcpClient.Client.Poll(5000, SelectMode.SelectRead) && (_tcpClient.Client.Available == 0))
{
ConnectionState = false;
}
}
}
else { ConnectionState = false; }
#endregion
Right now you seem to be saying 'does this array of strings equal this string', which of course it never would.
Perhaps you should think about iterating through your array of strings with a loop, and checking each to see if they are equals() with the inputted string?
...or do I misunderstand your question?
use blank? http://api.rubyonrails.org/classes/Object.html#method-i-blank-3F
unless params[:one].blank? && params[:two].blank?
will return true if its empty or nil
also... that will not work if you are testing boolean values.. since
>> false.blank?
=> true
in that case you could use
unless params[:one].to_s.blank? && params[:two].to_s.blank?
I've never come across point 2? Can you explain why you think this affects deployment in any way. If anything maven allows you to structure your projects in a modularised way that actually allows hot fixes for bugs in a particular tier, and allows independent development of an API from the remainder of the project for example.
It is possible that you are trying to cram everything into a single module, in which case the problem isn't really maven at all, but the way you are using it.
I have a simpler solution. In your destination page (irc_online.php) add an auto-refresh tag in the header.
Within the body of a class, the class name isn't defined yet, so it is not available. Can you not simply type the name of the class? Maybe you need to say more about the problem so we can find a solution for you.
I would create a metaclass to do this work for you. It's invoked at class creation time (conceptually at the very end of the class: block), and can manipulate the class being created. I haven't tested this:
class InputAssigningMetaclass(type):
def __new__(cls, name, bases, attrs):
cls.input = get_input(name)
return super(MyType, cls).__new__(cls, name, bases, newattrs)
class MyBaseFoo(object):
__metaclass__ = InputAssigningMetaclass
class foo(MyBaseFoo):
# etc, no need to create 'input'
class foo2(MyBaseFoo):
# etc, no need to create 'input'
document.getElementById('myRadio').checked
is a boolean value. It should be true
or false
document.getElementById('myRadio').checked = "checked";
casts the string to a boolean, which is true.
document.getElementById('myRadio').checked = true;
just assigns true
without casting.
Use true
as it is marginally more efficient and is more intention revealing to maintainers.
\n
is used for Unix systems (including Linux, and OSX).
\r\n
is mainly used on Windows.
\r
is used on really old Macs.
PHP_EOL
constant is used instead of these characters for portability between platforms.
UPDATE some_table
SET this_column=x, that_column=y
WHERE something LIKE 'them'