I claimed 3.5gb space in ubuntu AWS through this.
clean docker
docker stop $(docker ps -qa) && docker system prune -af --volumes
build again
docker build .
docker-compose build
docker-compose up
My simple way, but it can help for further variations on this subject. List all methods and alter them to useless.
Object.getOwnPropertyNames(console).filter(function(property) {
return typeof console[property] == 'function';
}).forEach(function (verb) {
console[verb] =function(){return 'Sorry, for security reasons...';};
});
I had the same error using an UpdateView
I had this:
if form.is_valid() and form2.is_valid():
form.save()
form2.save()
return HttpResponseRedirect(self.get_success_url())
and I solved just doing:
if form.is_valid() and form2.is_valid():
form.save()
form2.save()
return HttpResponseRedirect(reverse_lazy('adopcion:solicitud_listar'))
I've been interested in the original question here and related ones.
For an answer, this week I did some experiments with XCOPY.
To help answer the original question, here I post the results of my experiments.
I did the experiments on Windows 7 64 bit Professional SP1 with the copy of XCOPY that came with the operating system.
For the experiments, I wrote some code in the scripting language Open Object Rexx and the editor macro language Kexx with the text editor KEdit.
XCOPY was called from the Rexx code. The Kexx code edited the screen output of XCOPY to focus on the crucial results.
The experiments all had to do with using XCOPY to copy one directory with several files and subdirectories.
The experiments consisted of 10 cases. Each case adjusted the arguments to XCOPY and called XCOPY once. All 10 cases were attempting to do the same copying operation.
Here are the main results:
(1) Of the 10 cases, only three did copying. The other 7 cases right away, just from processing the arguments to XCOPY, gave error messages, e.g.,
Invalid path
Access denied
with no files copied.
Of the three cases that did copying, they all did the same copying, that is, gave the same results.
(2) If want to copy a directory X and all the files and directories in directory X, in the hierarchical file system tree rooted at directory X, then apparently XCOPY -- and this appears to be much of the original question -- just will NOT do that.
One consequence is that if using XCOPY to copy directory X and its contents, then CAN copy the contents but CANNOT copy the directory X itself; thus, lose the time-date stamp on directory X, its archive bit, data on ownership, attributes, etc.
Of course if directory X is a subdirectory of directory Y, an XCOPY of Y will copy all of the contents of directory Y WITH directory X. So in this way can get a copy of directory X. However, the copy of directory X will have its time-date stamp of the time of the run of XCOPY and NOT the time-date stamp of the original directory X.
This change in time-date stamps can be awkward for a copy of a directory with a lot of downloaded Web pages: The HTML file of the Web page will have its original time-date stamp, but the corresponding subdirectory for files used by the HTML file will have the time-date stamp of the run of XCOPY. So, when sorting the copy on time date stamps, all the subdirectories, the HTML files and the corresponding subdirectories, e.g.,
x.htm
x_files
can appear far apart in the sort on time-date.
Hierarchical file systems go way back, IIRC to Multics at MIT in 1969, and since then lots of people have recognized the two cases, given a directory X, (i) copy directory X and all its contents and (ii) copy all the contents of X but not directory X itself. Well, if only from the experiments, XCOPY does only (ii).
So, the results of the 10 cases are below. For each case, in the results the first three lines have the first three arguments to XCOPY. So, the first line has the tree name of the directory to be copied, the 'source'; the second line has the tree name of the directory to get the copies, the 'destination', and the third line has the options for XCOPY. The remaining 1-2 lines have the results of the run of XCOPY.
One big point about the options is that options /X and /O result in result
Access denied
To see this, compare case 8 with the other cases that were the same, did not have /X and /O, but did copy.
These experiments have me better understand XCOPY and contribute an answer to the original question.
======= case 1 ==================
"k:\software\dir_time-date\"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_1\"
options = /E /F /G /H /K /O /R /V /X /Y
Result: Invalid path
Result: 0 File(s) copied
======= case 2 ==================
"k:\software\dir_time-date\*"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_2\"
options = /E /F /G /H /K /O /R /V /X /Y
Result: Access denied
Result: 0 File(s) copied
======= case 3 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_3\"
options = /E /F /G /H /K /O /R /V /X /Y
Result: Access denied
Result: 0 File(s) copied
======= case 4 ==================
"k:\software\dir_time-date\"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_4\"
options = /E /F /G /H /K /R /V /Y
Result: Invalid path
Result: 0 File(s) copied
======= case 5 ==================
"k:\software\dir_time-date\"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_5\"
options = /E /F /G /H /K /O /R /S /X /Y
Result: Invalid path
Result: 0 File(s) copied
======= case 6 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_6\"
options = /E /F /G /H /I /K /O /R /S /X /Y
Result: Access denied
Result: 0 File(s) copied
======= case 7 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_7"
options = /E /F /G /H /I /K /R /S /Y
Result: 20 File(s) copied
======= case 8 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_8"
options = /E /F /G /H /I /K /O /R /S /X /Y
Result: Access denied
Result: 0 File(s) copied
======= case 9 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_9"
options = /I /S
Result: 20 File(s) copied
======= case 10 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_10"
options = /E /I /S
Result: 20 File(s) copied
The following steps can be used:
sudo apt-get -y update
---------
sudo apt-get install python3.7
--------------
python3.7
-------------
curl -O https://bootstrap.pypa.io/get-pip.py
-----------------
sudo apt install python3-pip
-----------------
sudo apt install python3.7-venv
-----------------
python3.7 -m venv /home/ubuntu/app
-------------
cd app
----------------
source bin/activate
Use:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= TRUNC(SYSDATE) - 30
SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date
that is 30 days previous including the current time.
Depending on your needs, you could also look at using ADD_MONTHS:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)
Try this way, almost same.. but that's what I did, and working.
<configuration>
<system.web>
<customErrors mode="On" defaultRedirect="apperror.aspx">
<error statusCode="404" redirect="404.aspx" />
<error statusCode="500" redirect="500.aspx" />
</customErrors>
</system.web>
</configuration>
or try to change the 404 error page from IIS settings, if required urgently.
Aside from limiting the columns selected to reduce bandwidth and memory:
DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);
Do nothing to the browser. CORS is supported by default on all modern browsers (and since Firefox 3.5).
The server being accessed by JavaScript has to give the site hosting the HTML document in which the JS is running permission via CORS HTTP response headers.
security.fileuri.strict_origin_policy
is used to give JS in local HTML documents access to your entire hard disk. Don't set it to false
as it makes you vulnerable to attacks from downloaded HTML documents (including email attachments).
requests
library doesn't support ftp links.
To download a file from FTP server you could:
import urllib
urllib.urlretrieve('ftp://server/path/to/file', 'file')
# if you need to pass credentials:
# urllib.urlretrieve('ftp://username:password@server/path/to/file', 'file')
Or:
import shutil
import urllib2
from contextlib import closing
with closing(urllib2.urlopen('ftp://server/path/to/file')) as r:
with open('file', 'wb') as f:
shutil.copyfileobj(r, f)
Python3:
import shutil
import urllib.request as request
from contextlib import closing
with closing(request.urlopen('ftp://server/path/to/file')) as r:
with open('file', 'wb') as f:
shutil.copyfileobj(r, f)
XML requires all tags to have a corresponding closing tag. So there is a special short-hand syntax for tags without inner contents.
HTML5 is not XML, so it should not pose such a requirement. Neither is HTML 4.01.
For instance, in HTML5 specs, all examples with br
tag use <br>
syntax, not <br/>
.
UPD Actually, <br/>
is permitted in HTML5. 9.1.2.1, 7.
A bit late to the game for this question, but in recent changes introduced in C# 7 (Available by default in Visual Studio 2017/.NET Framework 4.6.2), range-based switching is now possible with the switch
statement.
Example:
int i = 63;
switch (i)
{
case int n when (n >= 100):
Console.WriteLine($"I am 100 or above: {n}");
break;
case int n when (n < 100 && n >= 50 ):
Console.WriteLine($"I am between 99 and 50: {n}");
break;
case int n when (n < 50):
Console.WriteLine($"I am less than 50: {n}");
break;
}
Notes:
(
and )
are not required in the when
condition, but are used in this example to highlight the comparison(s). var
may also be used in lieu of int
. For example: case var n when n >= 100:
.The function you're looking for is 'Insert'. It takes as its parameters the index you want to insert at, and an array of values to use for the new row values. Typical usage might include:
myDataGridView.Rows.Insert(4,new object[]{value1,value2,value3});
or something to that effect.
The trunk directory is the directory that you're probably most familiar with, because it is used to hold the most recent changes. Your main codebase should be in trunk.
The branches directory is for holding your branches, whatever they may be.
The tags directory is basically for tagging a certain set of files. You do this for things like releases, where you want "1.0" to be these files at these revisions and "1.1" to be these files at these revisions. You usually don't modify tags once they're made. For more information on tags, see Chapter 4. Branching and Merging (in Version Control with Subversion).
A good rule of thumb: use the built-in help system in Python. Example below...
jdoe@server:~$ python
Python 2.7.3 (default, Aug 1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import memcache
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'memcache']
>>> help(memcache)
------------------------------------------
NAME
memcache - client module for memcached (memory cache daemon)
FILE
/usr/lib/python2.7/dist-packages/memcache.py
MODULE DOCS
http://docs.python.org/library/memcache
DESCRIPTION
Overview
========
See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.
Usage summary
=============
...
------------------------------------------
Not exactly the same as NUnit's Value
(or TestCase
) attributes, but MSTest has the DataSource
attribute, which allows you to do a similar thing.
You can hook it up to database or XML file - it is not as straightforward as NUnit's feature, but it does the job.
The method described in the accepted answer didn't work for me even after applying changes mentioned in its comments. But the below simple code worked:
import matplotlib.pyplot as plt
plt.imsave(filename, np_array, cmap='Greys')
np_array could be either a 2D array with values from 0..1 floats o2 0..255 uint8, and in that case it needs cmap. For 3D arrays, cmap will be ignored.
This worked for me. In my service class, I created the notification channel for android 8.1 as below:
public class Service extends Service {
public static final String NOTIFICATION_CHANNEL_ID_SERVICE = "com.package.MyService";
public static final String NOTIFICATION_CHANNEL_ID_INFO = "com.package.download_info";
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_SERVICE, "App Service", NotificationManager.IMPORTANCE_DEFAULT));
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_INFO, "Download Info", NotificationManager.IMPORTANCE_DEFAULT));
} else {
Notification notification = new Notification();
startForeground(1, notification);
}
}
}
Note: Create the channel where you are creating the Notification for Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
Why not go even simpler with either one of these options:
$("#box").html('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
Or, if you want to append it to existing content:
$("#box").append('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
Note: I put the id="myid"
right into the HTML string rather than using separate code to set it.
Both the .html()
and .append()
jQuery methods can take a string of HTML so there's no need to use a separate step for creating the objects.
Your friend's PC is missing the runtime support DLLs for your program:
You can do this:
//first get all the <a> elements
List<WebElement> linkList=driver.findElements(By.tagName("a"));
//now traverse over the list and check
for(int i=0 ; i<linkList.size() ; i++)
{
if(linkList.get(i).getAttribute("href").contains("long"))
{
linkList.get(i).click();
break;
}
}
in this what we r doing is first we are finding all the <a>
tags and storing them in a list.After
that we are iterating the list one by one to find <a>
tag whose href attribute contains long string. And then we click on that particular <a>
tag and comes out of the loop.
Using Ionic with Cordova via command line...
ionic cordova run android --prod
I ran into this and found that I had deleted the release version from a previous test install, but had an old debug version that was hanging out in apps drawer that I missed. I unplugged my device from the computer, opened the app drawer and used "Search apps.." to find all instances of the app to uninstall them. Then I re-plugged in the device to the computer and viola, it worked!
Thanks for the help everyone!
I found the solution:
public class DefaultPostgresKeyServer
{
private Session session;
private Iterator<BigInteger> iter;
private long batchSize;
public DefaultPostgresKeyServer (Session sess, long batchFetchSize)
{
this.session=sess;
batchSize = batchFetchSize;
iter = Collections.<BigInteger>emptyList().iterator();
}
@SuppressWarnings("unchecked")
public Long getNextKey()
{
if ( ! iter.hasNext() )
{
Query query = session.createSQLQuery( "SELECT nextval( 'mySchema.mySequence' ) FROM generate_series( 1, " + batchSize + " )" );
iter = (Iterator<BigInteger>) query.list().iterator();
}
return iter.next().longValue() ;
}
}
netstat -l (assuming it comes with that version of UNIX)
Have a look at ?"%in%"
.
dt[dt$fct %in% vc,]
fct X
1 a 2
3 c 3
5 c 5
7 a 7
9 c 9
10 a 1
12 c 2
14 c 4
You could also use ?is.element
:
dt[is.element(dt$fct, vc),]
Try this one
where datediff(month, datetime_column, getdate()) <= 6
To exclude or filter out future dates
where datediff(month, datetime_column, getdate()) between 0 and 6
This part datediff(month, datetime_column, getdate())
will get the month difference in number of current date and Datetime_Column and will return Rows like:
Result
1
2
3
4
5
6
7
8
9
10
This is Our final condition to get last 6 months data
where result <= 6
You use a for..in
loop for this. Be sure to check if the object owns the properties or all inherited properties are shown as well. An example is like this:
var obj = {a: 1, b: 2};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
}
}
Or if you need recursion to walk through all the properties:
var obj = {a: 1, b: 2, c: {a: 1, b: 2}};
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(obj);
Also; auto it = std::next(v.begin(), index);
Update: Needs a C++11x compliant compiler
It looks like all of the edits are already a part of the index. So to commit just use the commit
command
git commit -m "My Commit Message"
Looking at your messages though my instinct says that you probably don't want the cache
files to be included in your depot. Especially if it something that is built on the fly when running your program. If so then you should add the following line to your .gitignore file
httpdocs/newsite/manifest/cache/*
I think I just discovered a way to apply overlapping conditions in the expected way using VBA. After hours of trying out different approaches I found that what worked was changing the "Applies to" range for the conditional format rule, after every single one was created!
This is my working example:
Sub ResetFormatting()
' ----------------------------------------------------------------------------------------
' Written by..: Julius Getz Mørk
' Purpose.....: If conditional formatting ranges are broken it might cause a huge increase
' in duplicated formatting rules that in turn will significantly slow down
' the spreadsheet.
' This macro is designed to reset all formatting rules to default.
' ----------------------------------------------------------------------------------------
On Error GoTo ErrHandler
' Make sure we are positioned in the correct sheet
WS_PROMO.Select
' Disable Events
Application.EnableEvents = False
' Delete all conditional formatting rules in sheet
Cells.FormatConditions.Delete
' CREATE ALL THE CONDITIONAL FORMATTING RULES:
' (1) Make negative values red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlLess, "=0")
.Font.Color = -16776961
.StopIfTrue = False
End With
' (2) Highlight defined good margin as green values
With Cells(1, 1).FormatConditions.add(xlCellValue, xlGreater, "=CP_HIGH_MARGIN_DEFINITION")
.Font.Color = -16744448
.StopIfTrue = False
End With
' (3) Make article strategy "D" red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""D""")
.Font.Bold = True
.Font.Color = -16776961
.StopIfTrue = False
End With
' (4) Make article strategy "A" blue
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""A""")
.Font.Bold = True
.Font.Color = -10092544
.StopIfTrue = False
End With
' (5) Make article strategy "W" green
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""W""")
.Font.Bold = True
.Font.Color = -16744448
.StopIfTrue = False
End With
' (6) Show special cost in bold green font
With Cells(1, 1).FormatConditions.add(xlCellValue, xlNotEqual, "=0")
.Font.Bold = True
.Font.Color = -16744448
.StopIfTrue = False
End With
' (7) Highlight duplicate heading names. There can be none.
With Cells(1, 1).FormatConditions.AddUniqueValues
.DupeUnique = xlDuplicate
.Font.Color = -16383844
.Interior.Color = 13551615
.StopIfTrue = False
End With
' (8) Make heading rows bold with yellow background
With Cells(1, 1).FormatConditions.add(Type:=xlExpression, Formula1:="=IF($B8=""H"";TRUE;FALSE)")
.Font.Bold = True
.Interior.Color = 13434879
.StopIfTrue = False
End With
' Modify the "Applies To" ranges
Cells.FormatConditions(1).ModifyAppliesToRange Range("O8:P507")
Cells.FormatConditions(2).ModifyAppliesToRange Range("O8:O507")
Cells.FormatConditions(3).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(4).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(5).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(6).ModifyAppliesToRange Range("E8:E507")
Cells.FormatConditions(7).ModifyAppliesToRange Range("A7:AE7")
Cells.FormatConditions(8).ModifyAppliesToRange Range("B8:L507")
ErrHandler:
Application.EnableEvents = False
End Sub
Instead of using the = operator, you may want to use LIKE or LIKE BINARY
// this returns 1 (true)
select 'A' like 'a'
// this returns 0 (false)
select 'A' like binary 'a'
select * from user where username like binary 'a'
It will take 'a' and not 'A' in its condition
If your filename contains a dot (other than the one of the extension) then use this:
echo $filename | rev | cut -f 2- -d '.' | rev
As @Felix Kling suggested use action='store_true'
:
>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True
You want to focus on immutability in Scala generally by eliminating any vars. Readability is still important for your fellow man so:
Try:
scala> val list = for(i <- 1 to 10) yield i
list: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
You probably don't even need to convert to a list in most cases :)
The indexed seq will have everything you need:
That is, you can now work on that IndexedSeq:
scala> list.foldLeft(0)(_+_)
res0: Int = 55
When starting all over is not an option...
I deleted the log file in the .svn
directory (I also deleted the offending file in .svn/props-base
), did a cleanup, and resumed my update.
How about this modification on 7daysclean.cmd to take a leap year into account?
It can be done in less than 10 lines of coding!
set /a Leap=0
if (Month GEQ 2 and ((Years%4 EQL 0 and Years%100 NEQ 0) or Years%400 EQL 0)) set /a Leap=day
set /a Months=!_months!+Leap
Edit by Mofi:
The condition above contributed by J.R. evaluates always to false because of invalid syntax.
And Month GEQ 2
is also wrong because adding 86400 seconds for one more day must be done in a leap year only for the months March to December, but not for February.
A working code to take leap day into account - in current year only - in batch file 7daysclean.cmd posted by Jay would be:
set "LeapDaySecs=0"
if %Month% LEQ 2 goto CalcMonths
set /a "LeapRule=Years%%4"
if %LeapRule% NEQ 0 goto CalcMonths
rem The other 2 rules can be ignored up to year 2100.
set /A "LeapDaySecs=day"
:CalcMonths
set /a Months=!_months!+LeapDaySecs
A couple of issues arise when trying to reload/source ~/.profile file. [This refers to Ubuntu linux - in some cases the details of the commands will be different]
Ad. 1)
Running this directly in terminal means that there will be no subshell created. So you can use either two commands:
source ~/.bash_profile
or
. ~/.bash_profile
In both cases this will update the environment with the contents of .profile file.
Ad 2) You can start any bash script either by calling
sh myscript.sh
or
. myscript.sh
In the first case this will create a subshell that will not affect the environment variables of your system and they will be visible only to the subshell process. After finishing the subshell command none of the exports etc. will not be applied. THIS IS A COMMON MISTAKE AND CAUSES A LOT OF DEVELOPERS TO LOSE A LOT OF TIME.
In order for your changes applied in your script to have effect for the global environment the script has to be run with
.myscript.sh
command.
In order to make sure that you script is not runned in a subshel you can use this function. (Again example is for Ubuntu shell)
#/bin/bash
preventSubshell(){
if [[ $_ != $0 ]]
then
echo "Script is being sourced"
else
echo "Script is a subshell - please run the script by invoking . script.sh command";
exit 1;
fi
}
I hope this clears some of the common misunderstandings! :D Good Luck!
Use -C
option of tar:
tar zxvf <yourfile>.tar.gz -C /usr/src/
and then, the content of the tar should be in:
/usr/src/<yourfile>
DELETE message.*, usersmessage.* from users, usersmessage WHERE message.messageid=usersmessage.messageid AND message.messageid='1'
Eclipse by default does not know about your external Maven installation and uses the embedded one. Therefore in order for Eclipse to use your global settings you need to set it in menu Settings ? Maven ? Installations.
Try this:
Use back-ticks for NAME
CREATE TABLE `teachers` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`addr` varchar(255) NOT NULL,
`phone` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Adding to the above answer, whoever looks for a solution, you can also try 'match' operator instead of 'like'. Do not want to be biased but it perfectly worked for me in Postgresql.
Note.query.filter(Note.message.match("%somestr%")).all()
It inherits database functions such as CONTAINS and MATCH. However, it is not available in SQLite.
For more info go Common Filter Operators
Create dictionaries for both arrays using _.keyBy()
, merge the dictionaries, and convert the result to an array with _.values()
. In this way, the order of the arrays doesn't matter. In addition, it can also handle arrays of different length.
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = _(arr1) // start sequence_x000D_
.keyBy('member') // create a dictionary of the 1st array_x000D_
.merge(_.keyBy(arr2, 'member')) // create a dictionary of the 2nd array, and merge it to the 1st_x000D_
.values() // turn the combined dictionary to array_x000D_
.value(); // get the value (array) out of the sequence_x000D_
_x000D_
console.log(merged);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
Using ES6 Map
Concat the arrays, and reduce the combined array to a Map. Use Object#assign to combine objects with the same member
to a new object, and store in map. Convert the map to an array with Map#values and spread:
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = [...arr1.concat(arr2).reduce((m, o) => _x000D_
m.set(o.member, Object.assign(m.get(o.member) || {}, o))_x000D_
, new Map()).values()];_x000D_
_x000D_
console.log(merged);
_x000D_
There are two ways to add references using VBA. .AddFromGuid(Guid, Major, Minor)
and .AddFromFile(Filename)
. Which one is best depends on what you are trying to add a reference to. I almost always use .AddFromFile
because the things I am referencing are other Excel VBA Projects and they aren't in the Windows Registry.
The example code you are showing will add a reference to the workbook the code is in. I generally don't see any point in doing that because 90% of the time, before you can add the reference, the code has already failed to compile because the reference is missing. (And if it didn't fail-to-compile, you are probably using late binding and you don't need to add a reference.)
If you are having problems getting the code to run, there are two possible issues.
Aside from that, if you can be a little more clear on what your question is or what you are trying to do that isn't working, I could give a more specific answer.
The answer of Uttam didnt work for me. I just got null when I do:
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);
In my case, bitmapdata only has the buffer of the pixels, so it is imposible for the function decodeByteArray to guess which the width, the height and the color bits use. So I tried this and it worked:
//Create bitmap with width, height, and 4 bytes color (RGBA)
Bitmap bmp = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
ByteBuffer buffer = ByteBuffer.wrap(bitmapdata);
bmp.copyPixelsFromBuffer(buffer);
Check https://developer.android.com/reference/android/graphics/Bitmap.Config.html for different color options
You can "persist" the state using local storage as Omar Suggest, but it should be done once the state has been set. For that you need to pass a callback to the setState
function and you need to serialize and deserialize the objects put into local storage.
constructor(props) {
super(props);
this.state = {
allProjects: JSON.parse(localStorage.getItem('allProjects')) || []
}
}
addProject = (newProject) => {
...
this.setState({
allProjects: this.state.allProjects.concat(newProject)
},() => {
localStorage.setItem('allProjects', JSON.stringify(this.state.allProjects))
});
}
You can simply just pass the attribute you want without any annotations in your controller:
@RequestMapping(value = "/someUrl")
public String someMethod(String valueOne) {
//do stuff with valueOne variable here
}
Works with GET and POST
Use float roundf(float x)
.
"The round functions round their argument to the nearest integer value in floating-point format, rounding halfway cases away from zero, regardless of the current rounding direction." C11dr §7.12.9.5
#include <math.h>
float y = roundf(x * 100.0f) / 100.0f;
Depending on your float
implementation, numbers that may appear to be half-way are not. as floating-point is typically base-2 oriented. Further, precisely rounding to the nearest 0.01
on all "half-way" cases is most challenging.
void r100(const char *s) {
float x, y;
sscanf(s, "%f", &x);
y = round(x*100.0)/100.0;
printf("%6s %.12e %.12e\n", s, x, y);
}
int main(void) {
r100("1.115");
r100("1.125");
r100("1.135");
return 0;
}
1.115 1.115000009537e+00 1.120000004768e+00
1.125 1.125000000000e+00 1.129999995232e+00
1.135 1.134999990463e+00 1.139999985695e+00
Although "1.115" is "half-way" between 1.11 and 1.12, when converted to float
, the value is 1.115000009537...
and is no longer "half-way", but closer to 1.12 and rounds to the closest float
of 1.120000004768...
"1.125" is "half-way" between 1.12 and 1.13, when converted to float
, the value is exactly 1.125
and is "half-way". It rounds toward 1.13 due to ties to even rule and rounds to the closest float
of 1.129999995232...
Although "1.135" is "half-way" between 1.13 and 1.14, when converted to float
, the value is 1.134999990463...
and is no longer "half-way", but closer to 1.13 and rounds to the closest float
of 1.129999995232...
If code used
y = roundf(x*100.0f)/100.0f;
Although "1.135" is "half-way" between 1.13 and 1.14, when converted to float
, the value is 1.134999990463...
and is no longer "half-way", but closer to 1.13 but incorrectly rounds to float
of 1.139999985695...
due to the more limited precision of float
vs. double
. This incorrect value may be viewed as correct, depending on coding goals.
The example code does not throw an NPE. (there also should not be a ';' behind the i++)
When you are not sure of the number of rows, then you can do it this way:
followers_df.index = range(len(followers_df))
Replace all non-digit with blank: the remaining string contains only digits.
Integer.parseInt(s.replaceAll("[\\D]", ""))
This will also remove non-digits inbetween digits, so "x1x1x"
becomes 11
.
If you need to confirm that the string consists of a sequence of digits (at least one) possibly followed a letter, then use this:
s.matches("[\\d]+[A-Za-z]?")
Use sed to remove the duplicate user ID, assuming user IDs do not contain any spaces.
awk -F, '{ print $3, $0 }' user.csv | sort | sed 's/^.* //'
Using Java 7:
Paths.get(string).toUri().toURL();
However, you probably want to get a URI
. Eg, a URI
begins with file:///
but a URL with file:/
(at least, that's what toString
produces).
Hardcode the checkbox's height and width, remove its padding, and make its height plus vertical margins equal to the label's line-height. If the label text is inline, float the checkbox. Firefox, Chrome, and IE7+ all render the following example identically: http://www.kornea.com/css-checkbox-align
I had this same issue, and solved it with a solution similar to what Cheeso provided, above.
"doesn't work, says password is srequire, tried it a couple different ways "
Yep, that's because FTP sessions via a command file don't require the username to be prefaced with the string "user". Drop that, and try it.
Or, you could be seeing this because your FTP command file is not properly encoded (that bit me, too). That's the crappy part about generating a FTP command file at runtime. Powershell's out-file cmdlet does not have an encoding option that Windows FTP will accept (at least not one that I could find).
Regardless, as doing a WebClient.DownloadFile is the way to go.
Using a text editor, check for ^M
(control-M, or carriage return) at the end of each line. You will need to remove them first, then append the additional text at the end of the line.
sed -i 's|^M||g' ips.txt
sed -i 's|$|:80|g' ips.txt
From the first result on Google:
mailto:[email protected]_t?subject=Header&body=This%20is...%20the%20first%20line%0D%0AThis%20is%20the%20second
I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server
argument.
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] `
-Filter { EmailAddress -Like "*Smith_Karla*" } `
-Properties EmailAddress
I know basic use of abstract classes is to create templates for future classes. But are there any more uses of them?
Not only can you define a template for children, but Abstract Classes offer the added benefit of letting you define functionality that your child classes can utilize later.
You could not provide a default method implementation in an Interface prior to Java 8.
When should you prefer them over interfaces and when not?
Abstract Classes are a good fit if you want to provide implementation details to your children but don't want to allow an instance of your class to be directly instantiated (which allows you to partially define a class).
If you want to simply define a contract for Objects to follow, then use an Interface.
Also when are abstract methods useful?
Abstract methods are useful in the same way that defining methods in an Interface is useful. It's a way for the designer of the Abstract class to say "any child of mine MUST implement this method".
Page should be refresh auto using meta tag
<meta http-equiv="Refresh" content="60">
content value in seconds.after one minute page should be refresh
http://dev.mysql.com/doc/refman/5.6/en/load-data-local.html
Put this in my.cnf - the [client]
section should already be there
(if you're not too concerned about security).
[client]
loose-local-infile=1
Swift 5 : For evenly distributed spaces between cells with dynamic cell width to make the best of container space you may use the code snippet below by providing a minimumCellWidth value.
private func collectionViewLayout() -> UICollectionViewLayout {
let layout = UICollectionViewFlowLayout()
layout.sectionHeadersPinToVisibleBounds = true
// Important: if direction is horizontal use minimumItemSpacing instead.
layout.scrollDirection = .vertical
let itemHeight: CGFloat = 240
let minCellWidth :CGFloat = 130.0
let minItemSpacing: CGFloat = 10
let containerWidth: CGFloat = self.view.bounds.width
let maxCellCountPerRow: CGFloat = floor((containerWidth - minItemSpacing) / (minCellWidth+minItemSpacing ))
let itemWidth: CGFloat = floor( ((containerWidth - (2 * minItemSpacing) - (maxCellCountPerRow-1) * minItemSpacing) / maxCellCountPerRow ) )
// Calculate the remaining space after substracting calculating cellWidth (Divide by 2 because of left and right insets)
let inset = max(minItemSpacing, floor( (containerWidth - (maxCellCountPerRow*itemWidth) - (maxCellCountPerRow-1)*minItemSpacing) / 2 ) )
layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
layout.minimumInteritemSpacing = min(minItemSpacing,inset)
layout.minimumLineSpacing = minItemSpacing
layout.sectionInset = UIEdgeInsets(top: minItemSpacing, left: inset, bottom: minItemSpacing, right: inset)
return layout
}
You can use split() to get string array from comma separated string. If you iterate and perform mathematical operation on element of string array then that element will be treated as number by run-time cast but still you have string array. To convert comma separated string int array see the edit.
arr = strVale.split(',');
var strVale = "130,235,342,124";
arr = strVale.split(',');
for(i=0; i < arr.length; i++)
console.log(arr[i] + " * 2 = " + (arr[i])*2);
Output
130 * 2 = 260
235 * 2 = 470
342 * 2 = 684
124 * 2 = 248
Edit, Comma separated string to int Array In the above example the string are casted to numbers in expression but to get the int array from string array you need to convert it to number.
var strVale = "130,235,342,124";
var strArr = strVale.split(',');
var intArr = [];
for(i=0; i < strArr.length; i++)
intArr.push(parseInt(strArr[i]));
Here is a SO thread where @Matt renders only the desired pixel into a 1x1 context by displacing the image so that the desired pixel aligns with the one pixel in the context.
Inside a <button>
element you can put content, like text or images.
<button type="button">Click Me!</button>
This is the difference between this element and buttons created with the <input>
element.
Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.
Discord supports Markdown and uses highlight.js to highlight code-blocks.
Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.
To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).
```language
message
```
Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).
Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.
I might understand the question incorrectly, but if you want to declare an array of a certain shape but with nothing inside, the following might be helpful:
Initialise empty array:
>>> a = np.zeros((0,3)) #or np.empty((0,3)) or np.array([]).reshape(0,3)
>>> a
array([], shape=(0, 3), dtype=float64)
Now you can use this array to append rows of similar shape to it. Remember that a numpy array is immutable, so a new array is created for each iteration:
>>> for i in range(3):
... a = np.vstack([a, [i,i,i]])
...
>>> a
array([[ 0., 0., 0.],
[ 1., 1., 1.],
[ 2., 2., 2.]])
np.vstack and np.hstack is the most common method for combining numpy arrays, but coming from Matlab I prefer np.r_ and np.c_:
Concatenate 1d:
>>> a = np.zeros(0)
>>> for i in range(3):
... a = np.r_[a, [i, i, i]]
...
>>> a
array([ 0., 0., 0., 1., 1., 1., 2., 2., 2.])
Concatenate rows:
>>> a = np.zeros((0,3))
>>> for i in range(3):
... a = np.r_[a, [[i,i,i]]]
...
>>> a
array([[ 0., 0., 0.],
[ 1., 1., 1.],
[ 2., 2., 2.]])
Concatenate columns:
>>> a = np.zeros((3,0))
>>> for i in range(3):
... a = np.c_[a, [[i],[i],[i]]]
...
>>> a
array([[ 0., 1., 2.],
[ 0., 1., 2.],
[ 0., 1., 2.]])
@Test
public void google_Search()
{
WebDriver driver;
driver = new FirefoxDriver();
driver.get("http://www.google.com");
driver.manage().window().maximize();
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("Cheese!\n");
element.submit();
//Wait until the google page shows the result
WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("resultStats")));
List<WebElement> findElements = driver.findElements(By.xpath("//*[@id='rso']//h3/a"));
//Get the url of third link and navigate to it
String third_link = findElements.get(2).getAttribute("href");
driver.navigate().to(third_link);
}
Perhaps the simplest option is just to put those functions outside of the class:
class Dog(object):
def __init__(self, name):
self.name = name
def bark(self):
if self.name == "Doggy":
return barking_sound()
else:
return "yip yip"
def barking_sound():
return "woof woof"
Using this method, functions which modify or use internal object state (have side effects) can be kept in the class, and the reusable utility functions can be moved outside.
Let's say this file is called dogs.py
. To use these, you'd call dogs.barking_sound()
instead of dogs.Dog.barking_sound
.
If you really need a static method to be part of the class, you can use the staticmethod decorator.
First, let’s clarify what HEAD is and what it means when it is detached.
HEAD is the symbolic name for the currently checked out commit. When HEAD is not detached (the “normal”1 situation: you have a branch checked out), HEAD actually points to a branch’s “ref” and the branch points to the commit. HEAD is thus “attached” to a branch. When you make a new commit, the branch that HEAD points to is updated to point to the new commit. HEAD follows automatically since it just points to the branch.
git symbolic-ref HEAD
yields refs/heads/master
git rev-parse refs/heads/master
yield 17a02998078923f2d62811326d130de991d1a95a
git rev-parse HEAD
also yields 17a02998078923f2d62811326d130de991d1a95a
We have HEAD
? refs/heads/master
? 17a02998078923f2d62811326d130de991d1a95a
When HEAD is detached, it points directly to a commit—instead of indirectly pointing to one through a branch. You can think of a detached HEAD as being on an unnamed branch.
git symbolic-ref HEAD
fails with fatal: ref HEAD is not a symbolic ref
git rev-parse HEAD
yields 17a02998078923f2d62811326d130de991d1a95a
We have HEAD
? 17a02998078923f2d62811326d130de991d1a95a
The important thing to remember with a detached HEAD is that if the commit it points to is otherwise unreferenced (no other ref can reach it), then it will become “dangling” when you checkout some other commit. Eventually, such dangling commits will be pruned through the garbage collection process (by default, they are kept for at least 2 weeks and may be kept longer by being referenced by HEAD’s reflog).
1 It is perfectly fine to do “normal” work with a detached HEAD, you just have to keep track of what you are doing to avoid having to fish dropped history out of the reflog.
The intermediate steps of an interactive rebase are done with a detached HEAD (partially to avoid polluting the active branch’s reflog). If you finish the full rebase operation, it will update your original branch with the cumulative result of the rebase operation and reattach HEAD to the original branch. My guess is that you never fully completed the rebase process; this will leave you with a detached HEAD pointing to the commit that was most recently processed by the rebase operation.
To recover from your situation, you should create a branch that points to the commit currently pointed to by your detached HEAD:
git branch temp
git checkout temp
(these two commands can be abbreviated as git checkout -b temp
)
This will reattach your HEAD to the new temp
branch.
Next, you should compare the current commit (and its history) with the normal branch on which you expected to be working:
git log --graph --decorate --pretty=oneline --abbrev-commit master origin/master temp
git diff master temp
git diff origin/master temp
(You will probably want to experiment with the log options: add -p
, leave off --pretty=…
to see the whole log message, etc.)
If your new temp
branch looks good, you may want to update (e.g.) master
to point to it:
git branch -f master temp
git checkout master
(these two commands can be abbreviated as git checkout -B master temp
)
You can then delete the temporary branch:
git branch -d temp
Finally, you will probably want to push the reestablished history:
git push origin master
You may need to add --force
to the end of this command to push if the remote branch can not be “fast-forwarded” to the new commit (i.e. you dropped, or rewrote some existing commit, or otherwise rewrote some bit of history).
If you were in the middle of a rebase operation you should probably clean it up. You can check whether a rebase was in process by looking for the directory .git/rebase-merge/
. You can manually clean up the in-progress rebase by just deleting that directory (e.g. if you no longer remember the purpose and context of the active rebase operation). Usually you would use git rebase --abort
, but that does some extra resetting that you probably want to avoid (it moves HEAD back to the original branch and resets it back to the original commit, which will undo some of the work we did above).
The $@
and $<
are special macros.
Where:
$@
is the file name of the target.
$<
is the name of the first dependency.
Since phone numbers must conform to a pattern, you can use regular expressions to match the entered phone number against the pattern you define in regexp.
php has both ereg and preg_match() functions. I'd suggest using preg_match() as there's more documentation for this style of regex.
An example
$phone = '000-0000-0000';
if(preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) {
// $phone is valid
}
For future readers, one easy way is as follows if they wish to export in bulk using bash,
akshay@ideapad:/tmp$ mysql -u someuser -p test -e "select * from offices"
Enter password:
+------------+---------------+------------------+--------------------------+--------------+------------+-----------+------------+-----------+
| officeCode | city | phone | addressLine1 | addressLine2 | state | country | postalCode | territory |
+------------+---------------+------------------+--------------------------+--------------+------------+-----------+------------+-----------+
| 1 | San Francisco | +1 650 219 4782 | 100 Market Street | Suite 300 | CA | USA | 94080 | NA |
| 2 | Boston | +1 215 837 0825 | 1550 Court Place | Suite 102 | MA | USA | 02107 | NA |
| 3 | NYC | +1 212 555 3000 | 523 East 53rd Street | apt. 5A | NY | USA | 10022 | NA |
| 4 | Paris | +33 14 723 4404 | 43 Rue Jouffroy D'abbans | NULL | NULL | France | 75017 | EMEA |
| 5 | Tokyo | +81 33 224 5000 | 4-1 Kioicho | NULL | Chiyoda-Ku | Japan | 102-8578 | Japan |
| 6 | Sydney | +61 2 9264 2451 | 5-11 Wentworth Avenue | Floor #2 | NULL | Australia | NSW 2010 | APAC |
| 7 | London | +44 20 7877 2041 | 25 Old Broad Street | Level 7 | NULL | UK | EC2N 1HN | EMEA |
+------------+---------------+------------------+--------------------------+--------------+------------+-----------+------------+-----------+
If you're exporting by non-root user then set permission like below
root@ideapad:/tmp# mysql -u root -p
MariaDB[(none)]> UPDATE mysql.user SET File_priv = 'Y' WHERE user='someuser' AND host='localhost';
Restart or Reload mysqld
akshay@ideapad:/tmp$ sudo su
root@ideapad:/tmp# systemctl restart mariadb
Sample code snippet
akshay@ideapad:/tmp$ cat test.sh
#!/usr/bin/env bash
user="someuser"
password="password"
database="test"
mysql -u"$user" -p"$password" "$database" <<EOF
SELECT *
INTO OUTFILE '/tmp/csvs/offices.csv'
FIELDS TERMINATED BY '|'
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM offices;
EOF
Execute
akshay@ideapad:/tmp$ mkdir -p /tmp/csvs
akshay@ideapad:/tmp$ chmod +x test.sh
akshay@ideapad:/tmp$ ./test.sh
akshay@ideapad:/tmp$ cat /tmp/csvs/offices.csv
"1"|"San Francisco"|"+1 650 219 4782"|"100 Market Street"|"Suite 300"|"CA"|"USA"|"94080"|"NA"
"2"|"Boston"|"+1 215 837 0825"|"1550 Court Place"|"Suite 102"|"MA"|"USA"|"02107"|"NA"
"3"|"NYC"|"+1 212 555 3000"|"523 East 53rd Street"|"apt. 5A"|"NY"|"USA"|"10022"|"NA"
"4"|"Paris"|"+33 14 723 4404"|"43 Rue Jouffroy D'abbans"|\N|\N|"France"|"75017"|"EMEA"
"5"|"Tokyo"|"+81 33 224 5000"|"4-1 Kioicho"|\N|"Chiyoda-Ku"|"Japan"|"102-8578"|"Japan"
"6"|"Sydney"|"+61 2 9264 2451"|"5-11 Wentworth Avenue"|"Floor #2"|\N|"Australia"|"NSW 2010"|"APAC"
"7"|"London"|"+44 20 7877 2041"|"25 Old Broad Street"|"Level 7"|\N|"UK"|"EC2N 1HN"|"EMEA"
HTML or Jsp Page
<input type="text" name="1UserName">
<input type="text" name="2Password">
<Input type="text" name="3MobileNo">
<input type="text" name="4country">
and so on...
in java Code
SortedSet ss = new TreeSet();
Enumeration<String> enm=request.getParameterNames();
while(enm.hasMoreElements())
{
String pname = enm.nextElement();
ss.add(pname);
}
Iterator i=ss.iterator();
while(i.hasNext())
{
String param=(String)i.next();
String value=request.getParameter(param);
}
This doesn't "move" them in the technical sense but it has the same effect:
A--B--C (branch-foo)
\ ^-- I wanted them here!
\
D--E--F--G (branch-bar)
^--^--^-- Opps wrong branch!
While on branch-bar:
$ git reset --hard D # remember the SHAs for E, F, G (or E and G for a range)
A--B--C (branch-foo)
\
\
D-(E--F--G) detached
^-- (branch-bar)
Switch to branch-foo
$ git cherry-pick E..G
A--B--C--E'--F'--G' (branch-foo)
\ E--F--G detached (This can be ignored)
\ /
D--H--I (branch-bar)
Now you won't need to worry about the detached branch because it is basically
like they are in the trash can waiting for the day it gets garbage collected.
Eventually some time in the far future it will look like:
A--B--C--E'--F'--G'--L--M--N--... (branch-foo)
\
\
D--H--I--J--K--.... (branch-bar)
You need to create a new Window class. You can design that then any way you want. You can create and show a window modally like this:
MyWindow popup = new MyWindow();
popup.ShowDialog();
You can add a custom property for your result value, or if you only have two possible results ( + possibly undeterminate, which would be null
), you can set the window's DialogResult
property before closing it and then check for it (it is the value returned by ShowDialog()
).
You might want to consider using console.log
with the built-in "arguments" object:
console.log(arguments); // would have shown you [0] null, [1] yourResult
This will always output all of your arguments, no matter how many arguments you have.
You can accomplish this via Maps. Something like
Map<String, String>[] arr = new HashMap<String, String>[2]();
arr[0].put("name", "demo");
But as you start using Java I am sure you will find that if you create a class/model that represents your data will be your best options. I would do
class Person{
String name;
String fname;
}
List<Person> people = new ArrayList<Person>();
Person p = new Person();
p.name = "demo";
p.fname = "fdemo";
people.add(p);
You could use a div
with a background image instead and this CSS3 property:
background-size: contain
You can check out an example on:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Scaling_background_images#contain
To quote Mozilla:
The contain value specifies that regardless of the size of the containing box, the background image should be scaled so that each side is as large as possible while not exceeding the length of the corresponding side of the container.
However, keep in mind that your image will be upscaled if the div
is larger than your original image.
I'm not sure what happened in your case that fixed the issue, but your issue was on this line:
Caused by: java.lang.NoClassDefFoundError: javax/xml/rpc/handler/soap/SOAPMessageContext
You need to add jaxrpc-api.jar
to your /lib
s or add
<dependency>
<groupId>javax.xml</groupId>
<artifactId>jaxrpc-api</artifactId>
<version>x.x.x</version>
</dependency>
to your maven dependencies.
From the dojo API documentation:
dojo.html._emptyNode(node);
Add
transport_select.setAttribute("onchange", function(){toggleSelect(transport_select_id);});
or try replacing onChange
with onchange
Programmatically, Swift
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.titleView.numberOfLines = 2
Your indentation is broken. This should fix it:
import sys
def hello(a,b):
print 'hello and thats your sum:'
sum=a+b
print sum
if __name__ == "__main__":
hello(sys.argv[1], sys.argv[2])
Obviously, if you put the if __name__
statement inside the function, it will only ever be evaluated if you run that function. The problem is: the point of said statement is to run the function in the first place.
Something along the lines of:
yourString = yourString.replace ( /[^0-9]/g, '' );
The variable selectedHero
is null
in the template so you cannot bind selectedHero.name
as is. You need to use the elvis operator ?.
for this case:
<input [ngModel]="selectedHero?.name" (ngModelChange)="selectedHero.name = $event" />
The separation of the [(ngModel)]
into [ngModel]
and (ngModelChange)
is also needed because you can't assign to an expression that uses the elvis operator.
I also think you mean to use:
<h2>{{selectedHero?.name}} details!</h2>
instead of:
<h2>{{hero.name}} details!</h2>
Depending on the use case, you might also want to disable the buffering in the subprocess itself.
If the subprocess will be a Python process, you could do this before the call:
os.environ["PYTHONUNBUFFERED"] = "1"
Or alternatively pass this in the env
argument to Popen
.
Otherwise, if you are on Linux/Unix, you can use the stdbuf
tool. E.g. like:
cmd = ["stdbuf", "-oL"] + cmd
See also here about stdbuf
or other options.
(See also here for the same answer.)
If the property does not change for the widget it may be better to use like
android:imeOptions="actionDone"
in the layout xml
file.
In your pom.xml you should add distributionManagement configuration to where to deploy.
In the following example I have used file system as the locations.
<distributionManagement>
<repository>
<id>internal.repo</id>
<name>Internal repo</name>
<url>file:///home/thara/testesb/in</url>
</repository>
</distributionManagement>
you can add another location while deployment by using the following command (but to avoid above error you should have at least 1 repository configured) :
mvn deploy -DaltDeploymentRepository=internal.repo::default::file:///home/thara/testesb/in
1. You've got the right idea about how to design your resources, IMHO. I wouldn't change a thing.
2. Rather than trying to extend HTTP with more verbs, consider what your proposed verbs can be reduced to in terms of the basic HTTP methods and resources. For example, instead of an activate_login
verb, you could set up resources like: /api/users/1/login/active
which is a simple boolean. To activate a login, just PUT
a document there that says 'true' or 1 or whatever. To deactivate, PUT
a document there that is empty or says 0 or false.
Similarly, to change or set passwords, just do PUT
s to /api/users/1/password
.
Whenever you need to add something (like a credit) think in terms of POST
s. For example, you could do a POST
to a resource like /api/users/1/credits
with a body containing the number of credits to add. A PUT
on the same resource could be used to overwrite the value rather than add. A POST
with a negative number in the body would subtract, and so on.
3. I'd strongly advise against extending the basic HTTP status codes. If you can't find one that matches your situation exactly, pick the closest one and put the error details in the response body. Also, remember that HTTP headers are extensible; your application can define all the custom headers that you like. One application that I worked on, for example, could return a 404 Not Found
under multiple circumstances. Rather than making the client parse the response body for the reason, we just added a new header, X-Status-Extended
, which contained our proprietary status code extensions. So you might see a response like:
HTTP/1.1 404 Not Found
X-Status-Extended: 404.3 More Specific Error Here
That way a HTTP client like a web browser will still know what to do with the regular 404 code, and a more sophisticated HTTP client can choose to look at the X-Status-Extended
header for more specific information.
4. For authentication, I recommend using HTTP authentication if you can. But IMHO there's nothing wrong with using cookie-based authentication if that's easier for you.
git diff <path>/filename
path can your be complete system path till the file or
if you are in the project you paste the modified file path also
for Modified files with path use :git status
A bare repository is pretty much something you only push to and fetch from. You cannot do much directly "in it": you cannot check stuff out, create references (branches, tags), run git status
, etc.
If you want to create a new branch in a bare Git repository, you can push a branch from a clone to your bare repo:
# initialize your bare repo
$ git init --bare test-repo.git
# clone it and cd to the clone's root directory
$ git clone test-repo.git/ test-clone
Cloning into 'test-clone'...
warning: You appear to have cloned an empty repository.
done.
$ cd test-clone
# make an initial commit in the clone
$ touch README.md
$ git add .
$ git commit -m "add README"
[master (root-commit) 65aab0e] add README
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 README.md
# push to origin (i.e. your bare repo)
$ git push origin master
Counting objects: 3, done.
Writing objects: 100% (3/3), 219 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To /Users/jubobs/test-repo.git/
* [new branch] master -> master
we are using like this
<label for="1">
<div class="options">
<input type="radio" name="mem" id="1" value="1" checked="checked"/>option one
</div>
</label>
<label for="2">
<div class="options">
<input type="radio" name="mem" id="2" value="1" checked="checked"/>option two
</div></label>
using
<label for="1">
tag and catching is with
id=1
hope this helps.
If you are running cmake
to generate SomeLib
yourself (say as part of a superbuild), consider using the User Package Registry. This requires no hard-coded paths and is cross-platform. On Windows (including mingw64) it works via the registry. If you examine how the list of installation prefixes is constructed by the CONFIG
mode of the find_packages() command, you'll see that the User Package Registry is one of elements.
Brief how-to
Associate the targets of SomeLib
that you need outside of that external project by adding them to an export set in the CMakeLists.txt
files where they are created:
add_library(thingInSomeLib ...)
install(TARGETS thingInSomeLib Export SomeLib-export DESTINATION lib)
Create a XXXConfig.cmake
file for SomeLib
in its ${CMAKE_CURRENT_BUILD_DIR}
and store this location in the User Package Registry by adding two calls to export() to the CMakeLists.txt
associated with SomeLib
:
export(EXPORT SomeLib-export NAMESPACE SomeLib:: FILE SomeLibConfig.cmake) # Create SomeLibConfig.cmake
export(PACKAGE SomeLib) # Store location of SomeLibConfig.cmake
Issue your find_package(SomeLib REQUIRED)
commmand in the CMakeLists.txt
file of the project that depends on SomeLib
without the "non-cross-platform hard coded paths" tinkering with the CMAKE_MODULE_PATH
.
When it might be the right approach
This approach is probably best suited for situations where you'll never use your software downstream of the build directory (e.g., you're cross-compiling and never install anything on your machine, or you're building the software just to run tests in the build directory), since it creates a link to a .cmake file in your "build" output, which may be temporary.
But if you're never actually installing SomeLib
in your workflow, calling EXPORT(PACKAGE <name>)
allows you to avoid the hard-coded path. And, of course, if you are installing SomeLib
, you probably know your platform, CMAKE_MODULE_PATH
, etc, so @user2288008's excellent answer will have you covered.
As of iOS 5, the simulator has a configurable location.
Under the Debug menu, the last entry is "Location"; this gives you a sub menu with:
Custom Location lets you enter a Lat/Long value. Bicycle ride, City Run, and Freeway Drive are simulation of a moving location (in Cupertino, of course).
Of course, this does nothing to help with debugging for iOS 4 (or earlier); but it's a definite improvement!
You need to wrap them all in a character class. The current version means replace this sequence of characters with an empty string. When wrapped in square brackets it means replace any of these characters with an empty string.
var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");
SELECT * FROM adds where id=(select max(id) from adds);
This query used to fetch the last record in your table.
You can retrieve information about the version of your JBoss EAP installation by running the same script used to start the server with the -V switch. For Linux and Unix installations this script is run.sh and on Microsoft Windows installations it is run.bat. Regardless of platform the script is located in $JBOSS_HOME/bin. Using these scripts to actually start your server is dealt with in Chapter 4, Launching the JBoss EAP Server.
I had this when build my application with "All cpu" target while it referenced a 3rd party x64-only (managed) dll.
The following script catenates several (relative/absolute) paths (BASEPATH) with a relative path (SUBDIR):
shopt -s extglob
SUBDIR="subdir"
for BASEPATH in '' / base base/ base// /base /base/ /base//; do
echo "BASEPATH = \"$BASEPATH\" --> ${BASEPATH%%+(/)}${BASEPATH:+/}$SUBDIR"
done
The output of which is:
BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base/subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base/subdir
The shopt -s extglob
is only necessary to allow BASEPATH to end on multiple slashes (which is probably nonsense). Without extended globing you can just use:
echo ${BASEPATH%%/}${BASEPATH:+/}$SUBDIR
which would result in the less neat but still working:
BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base//subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base//subdir
To capitalize words...
str = "this is string example.... wow!!!";
print "str.title() : ", str.title();
@Gary02127 comment, the below solution works with title with apostrophe
import re
def titlecase(s):
return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", lambda mo: mo.group(0)[0].upper() + mo.group(0)[1:].lower(), s)
text = "He's an engineer, isn't he? SnippetBucket.com "
print(titlecase(text))
If you're going to be doing this search frequently, consider changing the format of your object so dinner actually is a key. This is kind of like assigning a primary clustered key in a database table. So, for example:
Obj = { 'pizza' : { 'name' : 'bob' }, 'sushi' : { 'name' : 'john' } }
You can now easily access it like this: Object['sushi']['name']
Or if the object really is this simple (just 'name' in the object), you could just change it to:
Obj = { 'pizza' : 'bob', 'sushi' : 'john' }
And then access it like: Object['sushi']
.
It's obviously not always possible or to your advantage to restructure your data object like this, but the point is, sometimes the best answer is to consider whether your data object is structured the best way. Creating a key like this can be faster and create cleaner code.
I am not familiar with Python so I am writing the C counter part(too lazy to write pseudo code.. :P) To find the first n prime numbers.. // prints all the primes.. not bothering to make an array and return it etc..
void find_first_n_primes(int n){
int count = 0;
for(int i=2;count<=n;i++){
factFlag == 0; //flag for factor count...
for(int k=2;k<sqrt(n)+1;k++){
if(i%k == 0) // factor found..
factFlag++;
}
if(factFlag==0)// no factors found hence prime..
{
Print(i); // prime displayed..
count++;
}
}
}
It is surprisingly simple...
Code behind:
// Here's your object that you'll create a list of
private class Products
{
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ProductPrice { get; set; }
}
// Here you pass in the List of Products
private void BindItemsInCart(List<Products> ListOfSelectedProducts)
{
// The the LIST as the DataSource
this.rptItemsInCart.DataSource = ListOfSelectedProducts;
// Then bind the repeater
// The public properties become the columns of your repeater
this.rptItemsInCart.DataBind();
}
ASPX code:
<asp:Repeater ID="rptItemsInCart" runat="server">
<HeaderTemplate>
<table>
<thead>
<tr>
<th>Product Name</th>
<th>Product Description</th>
<th>Product Price</th>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("ProductName") %></td>
<td><%# Eval("ProductDescription")%></td>
<td><%# Eval("ProductPrice")%></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
I hope this helps!
Here are some conversion routines I wrote many years ago for a c++/cli project, they should still work.
void StringToStlWString ( System::String const^ s, std::wstring& os)
{
String^ string = const_cast<String^>(s);
const wchar_t* chars = reinterpret_cast<const wchar_t*>((Marshal::StringToHGlobalUni(string)).ToPointer());
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}
System::String^ StlWStringToString (std::wstring const& os) {
String^ str = gcnew String(os.c_str());
//String^ str = gcnew String("");
return str;
}
System::String^ WPtrToString(wchar_t const* pData, int length) {
if (length == 0) {
//use null termination
length = wcslen(pData);
if (length == 0) {
System::String^ ret = "";
return ret;
}
}
System::IntPtr bfr = System::IntPtr(const_cast<wchar_t*>(pData));
System::String^ ret = System::Runtime::InteropServices::Marshal::PtrToStringUni(bfr, length);
return ret;
}
void Utf8ToStlWString(char const* pUtfString, std::wstring& stlString) {
//wchar_t* pString;
MAKE_WIDEPTR_FROMUTF8(pString, pUtfString);
stlString = pString;
}
void Utf8ToStlWStringN(char const* pUtfString, std::wstring& stlString, ULONG length) {
//wchar_t* pString;
MAKE_WIDEPTR_FROMUTF8N(pString, pUtfString, length);
stlString = pString;
}
First, you need to create your branch locally
git checkout -b your_branch
After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it
git push -u origin your_branch
Your Teammates/colleagues can push to your branch by doing commits and then push explicitly
... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch
The immediate problem is you have is with quoting: by using double quotes ("..."
), your variable references are instantly expanded, which is probably not what you want.
Use single quotes instead - strings inside single quotes are not expanded or interpreted in any way by the shell.
(If you want selective expansion inside a string - i.e., expand some variable references, but not others - do use double quotes, but prefix the $
of references you do not want expanded with \
; e.g., \$var
).
However, you're better off using a single here-doc[ument], which allows you to create multi-line stdin
input on the spot, bracketed by two instances of a self-chosen delimiter, the opening one prefixed by <<
, and the closing one on a line by itself - starting at the very first column; search for Here Documents
in man bash
or at http://www.gnu.org/software/bash/manual/html_node/Redirections.html.
If you quote the here-doc delimiter (EOF
in the code below), variable references are also not expanded. As @chepner points out, you're free to choose the method of quoting in this case: enclose the delimiter in single quotes or double quotes, or even simply arbitrarily escape one character in the delimiter with \
:
echo "creating new script file."
cat <<'EOF' > "$servfile"
#!/bin/bash
read -p "Please enter a service: " ser
servicetest=`getsebool -a | grep ${ser}`
if [ $servicetest > /dev/null ]; then
echo "we are now going to work with ${ser}"
else
exit 1
fi
EOF
As @BruceK notes, you can prefix your here-doc delimiter with -
(applied to this example: <<-"EOF"
) in order to have leading tabs stripped, allowing for indentation that makes the actual content of the here-doc easier to discern.
Note, however, that this only works with actual tab characters, not leading spaces.
Employing this technique combined with the afterthoughts regarding the script's content below, we get (again, note that actual tab chars. must be used to lead each here-doc content line for them to get stripped):
cat <<-'EOF' > "$servfile"
#!/bin/bash
read -p "Please enter a service name: " ser
if [[ -n $(getsebool -a | grep "${ser}") ]]; then
echo "We are now going to work with ${ser}."
else
exit 1
fi
EOF
Finally, note that in bash
even normal single- or double-quoted strings can span multiple lines, but you won't get the benefits of tab-stripping or line-block scoping, as everything inside the quotes becomes part of the string.
Thus, note how in the following #!/bin/bash
has to follow the opening '
immediately in order to become the first line of output:
echo '#!/bin/bash
read -p "Please enter a service: " ser
servicetest=$(getsebool -a | grep "${ser}")
if [[ -n $servicetest ]]; then
echo "we are now going to work with ${ser}"
else
exit 1
fi' > "$servfile"
Afterthoughts regarding the contents of your script:
$(...)
is preferred over `...`
for command substitution nowadays.${ser}
in the grep
command, as the command will likely break if the value contains embedded spaces (alternatively, make sure that the valued read contains no spaces or other shell metacharacters).[[ -n $servicetest ]]
to test whether $servicetest
is empty (or perform the command substitution directly inside the conditional) - [[ ... ]]
- the preferred form in bash
- protects you from breaking the conditional if the $servicetest
happens to have embedded spaces; there's NEVER a need to suppress stdout output inside a conditional (whether [ ... ]
or [[ ... ]]
, as no stdout output is passed through; thus, the > /dev/null
is redundant (that said, with a command substitution inside a conditional, stderr output IS passed through).the safest way is to put the ! for the regex negation within the [[ ]]
like this:
if [[ ! ${STR} =~ YOUR_REGEX ]]; then
otherwise it might fail on certain systems.
JSX isn't standard JavaScript, based to Airbnb style guide 'eslint' could consider this pattern
// filename: MyComponent.js
function MyComponent() {
return <div />;
}
as a warning, if you named your file MyComponent.jsx it will pass , unless if you edit the eslint rule you can check the style guide here
Java version to create empty DataSet:
public Dataset<Row> emptyDataSet(){
SparkSession spark = SparkSession.builder().appName("Simple Application")
.config("spark.master", "local").getOrCreate();
Dataset<Row> emptyDataSet = spark.createDataFrame(new ArrayList<>(), getSchema());
return emptyDataSet;
}
public StructType getSchema() {
String schemaString = "column1 column2 column3 column4 column5";
List<StructField> fields = new ArrayList<>();
StructField indexField = DataTypes.createStructField("column0", DataTypes.LongType, true);
fields.add(indexField);
for (String fieldName : schemaString.split(" ")) {
StructField field = DataTypes.createStructField(fieldName, DataTypes.StringType, true);
fields.add(field);
}
StructType schema = DataTypes.createStructType(fields);
return schema;
}
i'd use a simple one line comparisant for these use cases
$username = trim($_POST['userName'])?:'Anonymous';
This is for the use case you are certain error logging is off so you don't get a warning that the variable isn't initialised.
this is the paranoid version:
$username = !empty(trim(isset($_POST['userName'])?$_POST['userName']:''))?$_POST['userName']:'Anonymous';
This implements a check if the $_POST
variable is set. before accessing it.
Html like this
<input type="text" value="click the input to select" onclick="javascript:textSelector(this)"/>
and javascript code without bind
function textSelector(ele){
$(ele).select();
}
Oracle does not allow joining tables in an UPDATE statement. You need to rewrite your statement with a co-related sub-select
Something like this:
UPDATE system_info
SET field_value = 'NewValue'
WHERE field_desc IN (SELECT role_type
FROM system_users
WHERE user_name = 'uname')
For a complete description on the (valid) syntax of the UPDATE statement, please read the manual:
http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_10008.htm#i2067715
I'm using Visual Studio 2015, and I've found that the first thing to do is look in the build output.
I found this error reported there:
Reading build config file: \build.json... SyntaxError: Unexpected token
The solution for that was to remove the bom from the build.json file
Then I hit a second problem - with this message in the build output:
FAILURE: Build failed with an exception. * What went wrong: A problem was found with the configuration of task ':packageRelease'.
File 'C:\Users\Colin\etc' specified for property 'signingConfig.storeFile' is not a file.
Easily solved by putting the correct filename into the keystore property
You can use the -Q --help=target
options:
gcc -march=native -Q --help=target ...
The -v
option may also be of use.
You can see the documentation on the --help
option here.
Somewhere in your code there is a line #include <string>
. This by itself tells you that the program is written in C++. So using g++
is better than gcc
.
For the missing library: you should look around in the file system if you can find a file called libl.so
. Use the locate
command, try /usr/lib
, /usr/local/lib
, /opt/flex/lib
, or use the brute-force find / | grep /libl
.
Once you have found the file, you have to add the directory to the compiler command line, for example:
g++ -o scan lex.yy.c -L/opt/flex/lib -ll
The mentioned package/classes are not present in the compiletime classpath. Basically, Java has no idea what you're talking about when you say to import this and that. It can't find them in the classpath.
It's part of Apache Commons FileUpload. Just download the JAR and drop it in /WEB-INF/lib
folder of the webapp project and this error should disappear. Don't forget to do the same for Apache Commons IO, that's where FileUpload depends on, otherwise you will get the same problem during runtime.
Unrelated to the concrete problem, I see that you're using Tomcat 7, which is a Servlet 3.0 compatible container. Do you know that you can just use the new request.getPart()
method to obtain the uploaded file without the need for the whole Commons FileUpload stuff? Just add @MultipartConfig
annotation to the servlet class so that you can use it. See also How to upload files to server using JSP/Servlet?
Try this instead, remove the SelectCommand property and SelectParameters:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:itematConnectionString %>">
Then in the code behind do this:
SqlDataSource1.SelectParameters.Add("userId", userId.ToString());
SqlDataSource1.SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"
While this worked for me, the following code also works:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:itematConnectionString %>"
SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"></asp:SqlDataSource>
SqlDataSource1.SelectParameters.Add("userid", DbType.Guid, userId.ToString());
In your example, because you use CurrentDB to execute your INSERT you've made it harder for yourself. Instead, this will work:
Dim query As String
Dim newRow As Long ' note change of data type
Dim db As DAO.Database
query = "INSERT INTO InvoiceNumbers (date) VALUES (" & NOW() & ");"
Set db = CurrentDB
db.Execute(query)
newRow = db.OpenRecordset("SELECT @@IDENTITY")(0)
Set db = Nothing
I used to do INSERTs by opening an AddOnly
recordset and picking up the ID from there, but this here is a lot more efficient. And note that it doesn't require ADO
.
This works for me.
void pause()
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
std::string dummy;
std::cout << "Press any key to continue . . .";
std::getline(std::cin, dummy);
}
Use utcOffset function.
var testDateUtc = moment.utc("2015-01-30 10:00:00");
var localDate = moment(testDateUtc).utcOffset(10 * 60); //set timezone offset in minutes
console.log(localDate.format()); //2015-01-30T20:00:00+10:00
Instead of requiring explicit imports, the Swift compiler implicitly searches for .swiftmodule
files of dependency Swift libraries.
Xcode can build swift modules for you, or refer to the railsware blog for command line instructions for swiftc
.
You can query the data dictionary/catalog views to find out when an object was created as well as the time of last DDL involving the object (example: alter table)
select *
from all_objects
where owner = '<name of schema owner>'
and object_name = '<name of table>'
The column "CREATED" tells you when the object was created. The column "LAST_DDL_TIME" tells you when the last DDL was performed against the object.
As for when a particular row was inserted/updated, you can use audit columns like an "insert_timestamp" column or use a trigger and populate an audit table
I had faced a similar problem. Every thing was okay, the "readystate" was 4, but the "status" was 0. It was because I was using a Apache PHP portable server and my file in which I used the "XMLHttpRequest" object was a html file. I changed the file extension to php and the problem was solved.
To generate a random number between min and max, use:
int randNum = rand()%(max-min + 1) + min;
(Includes max and min)
Differences might not be meaningful in a typical use case, but using the standard DOM functionality
$("#el")[0].outerHTML
is about twice as fast as
$("<div />").append($("#el").clone()).html();
so I would go with:
/*
* Return outerHTML for the first element in a jQuery object,
* or an empty string if the jQuery object is empty;
*/
jQuery.fn.outerHTML = function() {
return (this[0]) ? this[0].outerHTML : '';
};
I don't think there is a more "angular way" to select an element. See, for instance, the way they are achieving this goal in the last example of this old documentation page:
{
template: '<div>' +
'<div class="title">{{title}}</div>' +
'<div class="body" ng-transclude></div>' +
'</div>',
link: function(scope, element, attrs) {
// Title element
var title = angular.element(element.children()[0]),
// ...
}
}
Have you tried using an absolute path:
File file = new File(System.getProperty("user.dir") + "/file.txt");
Update (2008-09-19 10:05) - Solution:
My Solution: Social engineering, I dug real hard and found someone who knew the schema name.
Technical Solution: Searching the .dmp file did yield the schema name.
Once I knew the schema name, I searched the dump file and learned where to find it.
Places the Schemas name were seen, in the .dmp file:
<OWNER_NAME>SOURCE_SCHEMA</OWNER_NAME>
This was seen before each table name/definition.
SCHEMA_LIST 'SOURCE_SCHEMA'
This was seen near the end of the .dmp.
Interestingly enough, around the SCHEMA_LIST 'SOURCE_SCHEMA'
section, it also had the command line used to create the dump, directories used, par files used, windows version it was run on, and export session settings (language, date formats).
So, problem solved :)
I used pandas and it worked well... While I was using it, I had to open a file and add some random columns to it and then save back to same file only.
This code adds multiple column entries, you may edit as much you need.
import pandas as pd
csv_input = pd.read_csv('testcase.csv') #reading my csv file
csv_input['Phone1'] = csv_input['Name'] #this would also copy the cell value
csv_input['Phone2'] = csv_input['Name']
csv_input['Phone3'] = csv_input['Name']
csv_input['Phone4'] = csv_input['Name']
csv_input['Phone5'] = csv_input['Name']
csv_input['Country'] = csv_input['Name']
csv_input['Website'] = csv_input['Name']
csv_input.to_csv('testcase.csv', index=False) #this writes back to your file
If you want that cell value doesn't gets copy, so first of all create a empty Column in your csv file manually, like you named it as Hours then, Now for this you can add this line in above code,
csv_input['New Value'] = csv_input['Hours']
or simply we can, without adding the manual column, we can
csv_input['New Value'] = '' #simple and easy
I Hope it helps.
On Android >=6.0, We have to request permission runtime.
Step1: add in AndroidManifest.xml file
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Step2: Request permission.
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
} else {
//TODO
}
Step3: Handle callback when you request permission.
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_READ_PHONE_STATE:
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
//TODO
}
break;
default:
break;
}
}
Edit: Read official guide here Requesting Permissions at Run Time
it seems that you should set your command as an String[]
,for example:
String[] command = new String[]{"rmiregistry","2020"};
Runtime.getRuntime().exec(command);
it just like the style of main(String[] args)
.
if you have numbers in list, you can use map
to apply str
to each element:
print ', '.join(map(str, LIST))
^ map
is C code so it's faster than str(i) for i in LIST
ExecuteScalar();
will work, but an output parameter would be a superior solution.
OWASP discusses this:
What's the difference between the cache-control directives: no-cache, and no-store?
The no-cache directive in a response indicates that the response must not be used to serve a subsequent request i.e. the cache must not display a response that has this directive set in the header but must let the server serve the request. The no-cache directive can include some field names; in which case the response can be shown from the cache except for the field names specified which should be served from the server. The no-store directive applies to the entire message and indicates that the cache must not store any part of the response or any request that asked for it.
Am I totally safe with these directives?
No. But generally, use both Cache-Control: no-cache, no-store and Pragma: no-cache, in addition to Expires: 0 (or a sufficiently backdated GMT date such as the UNIX epoch). Non-html content types like pdf, word documents, excel spreadsheets, etc often get cached even when the above cache control directives are set (although this varies by version and additional use of must-revalidate, pre-check=0, post-check=0, max-age=0, and s-maxage=0 in practice can sometimes result at least in file deletion upon browser closure in some cases due to browser quirks and HTTP implementations). Also, 'Autocomplete' feature allows a browser to cache whatever the user types in an input field of a form. To check this, the form tag or the individual input tags should include 'Autocomplete="Off" ' attribute. However, it should be noted that this attribute is non-standard (although it is supported by the major browsers) so it will break XHTML validation.
Source here.
you could submit all parameters with such naming:
params[0][topdiameter]
params[0][bottomdiameter]
params[1][topdiameter]
params[1][bottomdiameter]
then later you do something like this:
foreach ($_REQUEST['params'] as $item) {
echo $item['topdiameter'];
echo $item['bottomdiameter'];
}
On Mac OS use
find -E packages -regex ".*\.(jpg|gif|png|jpeg)"
try this
int intIdt = db.Users.Max(u => u.UserId);
Update:
If no record then generate exception using above code try this
int? intIdt = db.Users.Max(u => (int?)u.UserId);
For me it happen because i run it with default java version (7) and not with compiled java version (8) used to create this jar.
So i used:
%Java8_64%\bin\java -jar myjar.jar
Instead of java 7 version:
java -jar myjar.jar
Try using %0A
in the URL, just like you've used %20
instead of the space character.
I was wraped it with <> </> as a parent when I changed it to normal , div , its worked fine
I try lots of ways and finally try this:
def db_persist(func):
def persist(*args, **kwargs):
func(*args, **kwargs)
try:
session.commit()
logger.info("success calling db func: " + func.__name__)
return True
except SQLAlchemyError as e:
logger.error(e.args)
session.rollback()
return False
return persist
and :
@db_persist
def insert_or_update(table_object):
return session.merge(table_object)
just add following line in wamp/alias/phpmyadmin.conf
Allow from ::1
so it will look something like this depending your phpmyadmin version.
<Directory "c:/wamp/apps/phpmyadmin3.5.1/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from ::1
</Directory>
In Visual Studio Xamarin:
using Android.Content.PM;
to you activity namespace list.
[Activity(ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait)]
as an attribute to you class, like that:
[Activity(ScreenOrientation = ScreenOrientation.Portrait)]
public class MainActivity : Activity
{...}
I solved my problem that way. Thank you for suggestions for improvements. Example in C#.
string dd, mm, aa, trc, data;
dd = nData.Text.Substring(0, 2);
mm = nData.Text.Substring(3, 2);
aa = nData.Text.Substring(6, 4);
trc = "-";
data = aa + trc + mm + trc + dd;
"Select * From bdPedidos Where Data Like '%" + data + "%'";
You can either use:
<button onclick="window.history.back()">Back</button>
or..
<button onclick="window.history.go(-1)">Back</button>
The difference, of course, is back()
only goes back 1 page but go()
goes back/forward the number of pages you pass as a parameter, relative to your current page.
I don't know if I understand very well what you are trying to do, but I had to use jQuery plugins that required jQuery to be in the global context (window) and I put the following in my entry.js
:
var $ = require('jquery');
window.jQuery = $;
window.$ = $;
The I just have to require wherever i want the jqueryplugin.min.js
and window.$
is extended with the plugin as expected.
Here is the complete C# 7 solution...
switch (value)
{
case var s when new[] { 1,2,3 }.Contains(s):
// Do something
break;
case var s when new[] { 4,5,6 }.Contains(s):
// Do something
break;
default:
// Do the default
break;
}
It works with strings too...
switch (mystring)
{
case var s when new[] { "Alpha","Beta","Gamma" }.Contains(s):
// Do something
break;
...
}
If you wish to use CV2, you need to use the resize
function.
For example, this will resize both axes by half:
small = cv2.resize(image, (0,0), fx=0.5, fy=0.5)
and this will resize the image to have 100 cols (width) and 50 rows (height):
resized_image = cv2.resize(image, (100, 50))
Another option is to use scipy
module, by using:
small = scipy.misc.imresize(image, 0.5)
There are obviously more options you can read in the documentation of those functions (cv2.resize, scipy.misc.imresize).
Update:
According to the SciPy documentation:
imresize
is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.
Useskimage.transform.resize
instead.
Note that if you're looking to resize by a factor, you may actually want skimage.transform.rescale
.
To make print view look like tablet or desktop include bootstrap as .less, not as .css and then you can overwrite bootstrap responsive classes in the end of bootstrap_variables file for example like this:
@container-sm: 1200px;
@container-md: 1200px;
@container-lg: 1200px;
@screen-sm: 0;
Don't worry about putting this variables in the end of the file. LESS supports lazy loading of variables so they will be applied.
The cleanest and simplest way to do this:
First some CSS:
div.image-wrapper {
height: 230px; /* Suggestive number; pick your own height as desired */
position: relative;
overflow: hidden; /* This will do the magic */
width: 300px; /* Pick an appropriate width as desired, unless you already use a grid, in that case use 100% */
}
img {
width: 100%;
position: absolute;
left: 0;
top: 0;
height: auto;
}
The HTML:
<div class="image-wrapper">
<img src="yourSource.jpg">
</div>
This should do the trick!
Check the link Regular Expression Demo
use the below reg exp
[a-z] + [^0-9\s.]+|.(?!\d)
if you replace in the function SimpleDateFormat("hh") with ("HH") will format the hour in 24 hours instead of 12.
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
that's all you need
childView.frame = parentView.bounds
There is no jquery needed:
var matchedPosition = str.search(/[a-z]/i);
if(matchedPosition != -1) {
alert('found');
}
What is the difference between web service and WCF?
Web service use only HTTP protocol while transferring data from one application to other application.
But WCF supports more protocols for transporting messages than ASP.NET Web services. WCF supports sending messages by using HTTP, as well as the Transmission Control Protocol (TCP), named pipes, and Microsoft Message Queuing (MSMQ).
To develop a service in Web Service, we will write the following code
[WebService]
public class Service : System.Web.Services.WebService
{
[WebMethod]
public string Test(string strMsg)
{
return strMsg;
}
}
To develop a service in WCF, we will write the following code
[ServiceContract]
public interface ITest
{
[OperationContract]
string ShowMessage(string strMsg);
}
public class Service : ITest
{
public string ShowMessage(string strMsg)
{
return strMsg;
}
}
Web Service is not architecturally more robust. But WCF is architecturally more robust and promotes best practices.
Web Services use XmlSerializer but WCF uses DataContractSerializer. Which is better in performance as compared to XmlSerializer?
For internal (behind firewall) service-to-service calls we use the net:tcp binding, which is much faster than SOAP.
WCF is 25%—50% faster than ASP.NET Web Services, and approximately 25% faster than .NET Remoting.
When would I opt for one over the other?
WCF is used to communicate between other applications which has been developed on other platforms and using other Technology.
For example, if I have to transfer data from .net platform to other application which is running on other OS (like Unix or Linux) and they are using other transfer protocol (like WAS, or TCP) Then it is only possible to transfer data using WCF.
Here is no restriction of platform, transfer protocol of application while transferring the data between one application to other application.
Security is very high as compare to web service
The answer is "No, one can't find the median of an arbitrary, unsorted dataset in linear time". The best one can do as a general rule (as far as I know) is Median of Medians (to get a decent start), followed by Quickselect. Ref: [https://en.wikipedia.org/wiki/Median_of_medians][1]
It's pretty simple really:
a[start:stop] # items start through stop-1
a[start:] # items start through the rest of the array
a[:stop] # items from the beginning through stop-1
a[:] # a copy of the whole array
There is also the step
value, which can be used with any of the above:
a[start:stop:step] # start through not past stop, by step
The key point to remember is that the :stop
value represents the first value that is not in the selected slice. So, the difference between stop
and start
is the number of elements selected (if step
is 1, the default).
The other feature is that start
or stop
may be a negative number, which means it counts from the end of the array instead of the beginning. So:
a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items
Similarly, step
may be a negative number:
a[::-1] # all items in the array, reversed
a[1::-1] # the first two items, reversed
a[:-3:-1] # the last two items, reversed
a[-3::-1] # everything except the last two items, reversed
Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2]
and a
only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.
slice()
objectThe slicing operator []
is actually being used in the above code with a slice()
object using the :
notation (which is only valid within []
), i.e.:
a[start:stop:step]
is equivalent to:
a[slice(start, stop, step)]
Slice objects also behave slightly differently depending on the number of arguments, similarly to range()
, i.e. both slice(stop)
and slice(start, stop[, step])
are supported.
To skip specifying a given argument, one might use None
, so that e.g. a[start:]
is equivalent to a[slice(start, None)]
or a[::-1]
is equivalent to a[slice(None, None, -1)]
.
While the :
-based notation is very helpful for simple slicing, the explicit use of slice()
objects simplifies the programmatic generation of slicing.
It's very simple steps to push your node js application from local to GitHub.
Steps:
git clone repo-url
git add -A
git commit -a -m "First Commit"
git push origin master
This might also help:
void ButtQuitClick(object sender, EventArgs e)
{
QuitWin form = new QuitWin();
form.Show();
}
Change ButtQuit to your button name and also change QuitWin to the name of the form that you made.
When the button is clicked it will open another window, you will need to make another form and a button on your main form for it to work.
An update to @malcubierre for Cordova 4 (and later)-
Create a file called release-signing.properties
and put in APPFOLDER\platforms\android
folder
Contents of the file: edit after = for all except 2nd line
storeFile=C:/yourlocation/app.keystore
storeType=jks
keyAlias=aliasname
keyPassword=aliaspass
storePassword=password
Then this command should build a release version:
cordova build android --release
UPDATE - This was not working for me Cordova 10 with android 9
- The build was replacing the release-signing.properties file. I had to make a build.json
file and drop it in the appfolder, same as root. And this is the contents - replace as above:
{
"android": {
"release": {
"keystore": "C:/yourlocation/app.keystore",
"storePassword": "password",
"alias": "aliasname",
"password" : "aliaspass",
"keystoreType": ""
}
}
}
Run it and it will generate one of those release-signing.properties
in the android folder
I found a solution for my problem while writing my question !
Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)
I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)
So it seems the problem comes from the use of RDP (windows7 and 8)
Update 2017: Problem occurs on Windows 10 aswell.
$key
is the index for the current array element, and $val
is the value of that array element.
The first element has an index of 0. Therefore, to access it, use $arr[0]
To get the first element of the array, use this
$firstFound = false;
foreach($arr as $key=>$val)
{
if (!$firstFound)
$first = $val;
else
$firstFound = true;
// do whatever you want here
}
// now ($first) has the value of the first element in the array
elem.offsetWdith VS ele.scrollWidth This work for me! https://jsfiddle.net/gustavojuan/210to9p1/
$(function() {
$('.endtext').each(function(index, elem) {
debugger;
if(elem.offsetWidth !== elem.scrollWidth){
$(this).css({color: '#FF0000'})
}
});
});
To maven, the build process is arranged as a set of artifacts. Artifacts include:
Artifacts live in repositories.
It looks like you have a typo on your array, it should read:
int my_array[3][3] = {...
You don't have the _
or the {
.
Also my_array[3][3]
is an invalid location. Since computers begin counting at 0
, you are accessing position 4
. (Arrays are weird like that).
If you want just the last element:
printf("%d\n", my_array[2][2]);
If you want the entire array:
for(int i = 0; i < my_array.length; i++) {
for(int j = 0; j < my_array[i].length; j++)
printf("%d ", my_array[i][j]);
printf("\n");
}
Make sure this is placed in the head element of your index.html:
<base href="/">
The Example in the Angular2 Routing & Navigation documentation uses the following code in the head instead (they explain why in the live example note of the documentation):
<script>document.write('<base href="' + document.location + '" />');</script>
When you refresh a page this will dynamically set the base href to your current document.location. I could see this causing some confusion for people skimming the documentation and trying to replicate the plunker.
You don`t have to setup variable, you can just set if it is moving in data-attribute
$youtubeSlider.find('a')
.on('mousedown', function (e) {
$(this).data('moving', false);
})
.on('mousemove', function (e) {
$(this).data('moving', true);
})
.on('mouseup', function (e) {
if (!$(this).data('moving')) {
// Open link
}
});
You can also use unzip to iterate through the columns
for col in zip(*array):
some_function(col)
QTip has bug with jQuery 1.4.2. I had to switch to jQuery Bubble Pop up http://www.vegabit.com/jquery_bubble_popup_v2/#examples and it works great!
These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".
The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.
ffmpeg
vs the fake oneFor a while both Libav and FFmpeg separately developed their own version of ffmpeg
.
Libav then renamed their bizarro ffmpeg
to avconv
to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv
instead of their counterfeit version of ffmpeg
. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.
This message was removed upstream when the fake "ffmpeg
" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.
In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1
. Unfortunately the new "deprecated" message has caused additional user confusion.
Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg
is back in the repositories again.
To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.
If you are using avconv
then you are using Libav. If you are using ffmpeg
you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.
Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h
header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg
or avconv
and viewing the console output.
ffmpeg
The real ffmpeg
is in the repository, so you can install it with:
apt-get install ffmpeg
Your options are:
ffmpeg
,ffmpeg
,These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.
Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg
from the repository.
For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.
use count instead of sum in your original formula u will get your result
Original One
=SUM(IF(MONTH('2013'!$A$2:$A$19)=4,'2013'!$D$2:$D$19,0))
Modified One
=COUNT(IF(MONTH('2013'!$A$2:$A$19)=4,'2013'!$D$2:$D$19,0))
AND USE ctrl+shift+enter
TO EXECUTE
I was able to install libc6 2.17
in Debian Wheezy
by editing the recommendations in perror's answer:
IMPORTANT
You need to exit out of your display manager by pressing CTRL-ALT-F1.
Then you can stop x (slim
) with sudo /etc/init.d/slim stop
(replace slim with mdm
or lightdm
or whatever)
Add the following line to the file /etc/apt/sources.list
:
deb http://ftp.debian.org/debian experimental main
Should be changed to:
deb http://ftp.debian.org/debian sid main
Then follow the rest of perror's post:
Update your package database:
apt-get update
Install the eglibc
package:
apt-get -t sid install libc6-amd64 libc6-dev libc6-dbg
IMPORTANT
After done updating libc6
, restart computer, and you should comment out or remove the sid source you just added (deb http://ftp.debian.org/debian sid main
), or else you risk upgrading your whole distro to sid.
Hope this helps. It took me a while to figure out.
LINQ doesn't prohibit the use of stored procedures. I've used mixed mode with LINQ-SQL and LINQ-storedproc. Personally, I'm glad I don't have to write the stored procs....pwet-tu.
I searched lots of methods and i did it my own way. You have to open a connection between two machine via command prompt NET USE command and after finishing your work clear the connection with command prompt NET USE "myconnection" /delete.
You must use Command Prompt process from code behind like this:
var savePath = @"\\servername\foldername\myfilename.jpg";
var filePath = @"C:\\temp\myfileTosave.jpg";
Usage is simple:
SaveACopyfileToServer(filePath, savePath);
Here is functions:
using System.IO
using System.Diagnostics;
public static void SaveACopyfileToServer(string filePath, string savePath)
{
var directory = Path.GetDirectoryName(savePath).Trim();
var username = "loginusername";
var password = "loginpassword";
var filenameToSave = Path.GetFileName(savePath);
if (!directory.EndsWith("\\"))
filenameToSave = "\\" + filenameToSave;
var command = "NET USE " + directory + " /delete";
ExecuteCommand(command, 5000);
command = "NET USE " + directory + " /user:" + username + " " + password;
ExecuteCommand(command, 5000);
command = " copy \"" + filePath + "\" \"" + directory + filenameToSave + "\"";
ExecuteCommand(command, 5000);
command = "NET USE " + directory + " /delete";
ExecuteCommand(command, 5000);
}
And also ExecuteCommand function is:
public static int ExecuteCommand(string command, int timeout)
{
var processInfo = new ProcessStartInfo("cmd.exe", "/C " + command)
{
CreateNoWindow = true,
UseShellExecute = false,
WorkingDirectory = "C:\\",
};
var process = Process.Start(processInfo);
process.WaitForExit(timeout);
var exitCode = process.ExitCode;
process.Close();
return exitCode;
}
This functions worked very fast and stable for me.
select * from
(select
ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_FruitType DESC) as tt
,*
from tblFruit
) a
where a.tt=1
For me installing the jdk 1.8
solved the issue.
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Fork(value = 1)
@Measurement(iterations = 5, time = 1)
public class StringFirstCharBenchmark {
private String source;
@Setup
public void init() {
source = "MALE";
}
@Benchmark
public String substring() {
return source.substring(0, 1);
}
@Benchmark
public String indexOf() {
return String.valueOf(source.indexOf(0));
}
}
Results:
+----------------------------------------------------------------------+
| Benchmark Mode Cnt Score Error Units |
+----------------------------------------------------------------------+
| StringFirstCharBenchmark.indexOf avgt 5 23.777 ? 5.788 ns/op |
| StringFirstCharBenchmark.substring avgt 5 11.305 ? 1.411 ns/op |
+----------------------------------------------------------------------+
FWIW Microsoft has added an extension for __super in their compiler.
If you have Java 1.8 then
You need this xml part in pom.xml and update project.
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
Here You Go:
HTML
<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</body>
</html>
Script:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
try something like this:
a = buffer[3];
a = a*256 + buffer[2];
a = a*256 + buffer[1];
a = a*256 + buffer[0];
this is assuming that the lowest byte comes first. if the highest byte comes first you might have to swap the indices (go from 0 to 3).
basically for each byte you want to add, you first multiply a by 256 (which equals a shift to the left by 8 bits) and then add the new byte.
I very recently had the some problem and just figured out how to do this. Assuming you have three classes, Primary, B, C and that B,C have a foreign key to primary
class PrimaryForm(ModelForm):
class Meta:
model = Primary
class BForm(ModelForm):
class Meta:
model = B
exclude = ('primary',)
class CForm(ModelForm):
class Meta:
model = C
exclude = ('primary',)
def generateView(request):
if request.method == 'POST': # If the form has been submitted...
primary_form = PrimaryForm(request.POST, prefix = "primary")
b_form = BForm(request.POST, prefix = "b")
c_form = CForm(request.POST, prefix = "c")
if primary_form.is_valid() and b_form.is_valid() and c_form.is_valid(): # All validation rules pass
print "all validation passed"
primary = primary_form.save()
b_form.cleaned_data["primary"] = primary
b = b_form.save()
c_form.cleaned_data["primary"] = primary
c = c_form.save()
return HttpResponseRedirect("/viewer/%s/" % (primary.name))
else:
print "failed"
else:
primary_form = PrimaryForm(prefix = "primary")
b_form = BForm(prefix = "b")
c_form = Form(prefix = "c")
return render_to_response('multi_model.html', {
'primary_form': primary_form,
'b_form': b_form,
'c_form': c_form,
})
This method should allow you to do whatever validation you require, as well as generating all three objects on the same page. I have also used javascript and hidden fields to allow the generation of multiple B,C objects on the same page.
Working example. Notes below.
class Animal {
constructor(public name) {
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
move() {
alert(this.name + " is Slithering...");
super.move(5);
}
}
class Horse extends Animal {
move() {
alert(this.name + " is Galloping...");
super.move(45);
}
}
var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
You don't need to manually assign the name to a public variable. Using public name
in the constructor definition does this for you.
You don't need to call super(name)
from the specialised classes.
Using this.name
works.
Notes on use of super
.
This is covered in more detail in section 4.9.2 of the language specification.
The behaviour of the classes inheriting from Animal
is not dissimilar to the behaviour in other languages. You need to specify the super
keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move()
or this.move()
you would be dealing with the specialised Snake
or Horse
function, so using super.move()
explicitly calls the base class function.
There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name
and this.name
- there is simply this.name
. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.
This is the simple way:
text = "the little red hen"
count = text.Split("e").Length -1 ' Equals 4
count = text.Split("t").Length -1 ' Equals 3
Yes, it is intended. Here you can read detailed explanation. It is possible to override this behavior by setting SO_REUSEADDR option on a socket. For example:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Linq-to-SQL
It is provider it supports SQL Server only. It's a mapping technology to map SQL Server database tables to .NET objects. Is Microsoft's first attempt at an ORM - Object-Relational Mapper.
Linq-to-Entities
Is the same idea, but using Entity Framework in the background, as the ORM - again from Microsoft, It supporting multiple database main advantage of entity framework is developer can work on any database no need to learn syntax to perform any operation on different different databases
According to my personal experience Ef is better (if you have no idea about SQL) performance in LINQ is little bit faster as compare to EF reason LINQ language written in lambda.
This solved my problem after I made a minor change to it. I added the following in my html page in order to fix the IE9 problem:
<script type="text/javascript">
// IE9 fix
if(!window.console) {
var console = {
log : function(){},
warn : function(){},
error : function(){},
time : function(){},
timeEnd : function(){}
}
}
</script>
The question is trickier than it appears, because in many cases there isn't "an IP address for the local computer" so much as a number of different IP addresses. For example, the Mac I'm typing on right now (which is a pretty basic, standard Mac setup) has the following IP addresses associated with it:
fe80::1%lo0
127.0.0.1
::1
fe80::21f:5bff:fe3f:1b36%en1
10.0.0.138
172.16.175.1
192.168.27.1
... and it's not just a matter of figuring out which of the above is "the real IP address", either... they are all "real" and useful; some more useful than others depending on what you are going to use the addresses for.
In my experience often the best way to get "an IP address" for your local computer is not to query the local computer at all, but rather to ask the computer your program is talking to what it sees your computer's IP address as. e.g. if you are writing a client program, send a message to the server asking the server to send back as data the IP address that your request came from. That way you will know what the relevant IP address is, given the context of the computer you are communicating with.
That said, that trick may not be appropriate for some purposes (e.g. when you're not communicating with a particular computer) so sometimes you just need to gather the list of all the IP addresses associated with your machine. The best way to do that under Unix/Mac (AFAIK) is by calling getifaddrs() and iterating over the results. Under Windows, try GetAdaptersAddresses() to get similar functionality. For example usages of both, see the GetNetworkInterfaceInfos() function in this file.
A simpler approach, which I have been using (assuming you want to move 4 commits):
git format-patch HEAD~4
(Look in the directory from which you executed the last command for the 4 .patch
files)
git reset HEAD~4 --hard
git checkout -b tmp/my-new-branch
Then:
git apply /path/to/patch.patch
In whatever order you wanted.