If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.
In your case, you might do better to have a generic draw()
method, and rely on the subclasses (Rectangle
, Ellipse
) to implement the draw()
method as what you had been thinking of as "drawEllipse" and "drawRectangle".
If you are using git and have a correct .gitignore
in your project, you can
git clean -xdf --dry-run
to remove absolutely every file on the .gitignore
list, i.e. it will clean obj
, and bin
folders (the x
triggers this behavior)
How about this? It's simple and worked the best for me :)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class IP {
public static void main(String args[]) {
new IP();
}
public IP() {
URL ipAdress;
try {
ipAdress = new URL("http://myexternalip.com/raw");
BufferedReader in = new BufferedReader(new InputStreamReader(ipAdress.openStream()));
String ip = in.readLine();
System.out.println(ip);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It should be noted that unset()
will keep indexes untouched, which is what you'd expect when using string indexes (array as hashtable), but can be quite surprising when dealing with integer indexed arrays:
$array = array(0, 1, 2, 3);
unset($array[2]);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[3]=>
int(3)
} */
$array = array(0, 1, 2, 3);
array_splice($array, 2, 1);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */
So array_splice()
can be used if you'd like to normalize your integer keys. Another option is using array_values()
after unset()
:
$array = array(0, 1, 2, 3);
unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */
Try this:
$("div.subtab_left li.notebook a").click(function(e) {
e.preventDefault();
});
If you look at the code for the component you can see that it uses the className
prop passed to it to combine with the row
class to get the resulting set of classes (<Row className="aaa bbb"...
works).Also, if you provide the id
prop like <Row id="444" ...
it will actually set the id attribute for the element.
I found that this works if wanting in a (123) - 456-7890 format.
UPDATE table
SET Phone_number = '(' +
SUBSTRING(Phone_number, 1, 3)
+ ') '
+ '- ' +
SUBSTRING(Phone_number, 4, 3)
+ '-' +
SUBSTRING(Phone_number, 7, 4)
Another good option for handling this kind of option is the pprint
module, which (among other things) pretty prints long lists with one element per line:
>>> import sys
>>> import pprint
>>> pprint.pprint(sys.path)
['',
'/usr/lib/python27.zip',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/lib/python2.7/site-packages',
'/usr/lib/python2.7/site-packages/PIL',
'/usr/lib/python2.7/site-packages/gst-0.10',
'/usr/lib/python2.7/site-packages/gtk-2.0',
'/usr/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg-info',
'/usr/lib/python2.7/site-packages/webkit-1.0']
>>>
The following expression worked for me:
SELECT CONVERT(VARCHAR(1000), varbinary_value, 2);
Here are more details on the choice of style (the third parameter).
This works with multiple statements:
if condition1 Then stmt1:stmt2 Else if condition2 Then stmt3:stmt4 Else stmt5:stmt6
Or you can split it over multiple lines:
if condition1 Then stmt1:stmt2
Else if condition2 Then stmt3:stmt4
Else stmt5:stmt6
php's email()
function hands the email over to a underlying mail transfer agent
which is usually postfix
on linux systems
so the preferred method on linux is to configure your postfix to use a relayhost, which is done by a line of
relayhost = smtp.example.com
in /etc/postfix/main.cf
however in the OP's scenario I somehow suspect that it's a job that his hosting team
should have done
No need to care of whether before/after this digit having other type of words
To just match the pattern of 5 digits number anywhere in the string, no matter it is separated by space or not, use this regular expression (?<!\d)\d{5}(?!\d)
.
Sample JavaScript codes:
var regexp = new RegExp(/(?<!\d)\d{5}(?!\d)/g);
var matches = yourstring.match(regexp);
if (matches && matches.length > 0) {
for (var i = 0, len = matches.length; i < len; i++) {
// ... ydo something with matches[i] ...
}
}
Here's some quick results.
abc12345xyz (?)
12345abcd (?)
abcd12345 (?)
0000aaaa2 (?)
a1234a5 (?)
12345 (?)
<space>
12345<space>
12345 (??)
A CTE worked for me:
with cte as (
select 1 col1
from temptable
group by column_1
)
select COUNT(col1)
from cte;
Same error can raise by mixing: tabs + spaces.
with open('/foo', 'w') as f:
(spaces OR tab) print f <-- success
(spaces AND tab) print f <-- fail
If you are avoiding stored procedures
like the plague, or are unable to do a mysql_dump
due to permissions, or running into other various reasons.
I would suggest a three-step approach like this:
1) Where this query builds a bunch of queries as a result set.
# =================
# VAR/CHAR SEARCH
# =================
# BE ADVISED USE ANY OF THESE WITH CAUTION
# DON'T RUN ON YOUR PRODUCTION SERVER
# ** USE AN ALTERNATE BACKUP **
SELECT
CONCAT('SELECT * FROM ', A.TABLE_SCHEMA, '.', A.TABLE_NAME,
' WHERE ', A.COLUMN_NAME, ' LIKE \'%stuff%\';')
FROM INFORMATION_SCHEMA.COLUMNS A
WHERE
A.TABLE_SCHEMA != 'mysql'
AND A.TABLE_SCHEMA != 'innodb'
AND A.TABLE_SCHEMA != 'performance_schema'
AND A.TABLE_SCHEMA != 'information_schema'
AND
(
A.DATA_TYPE LIKE '%text%'
OR
A.DATA_TYPE LIKE '%char%'
)
;
.
# =================
# NUMBER SEARCH
# =================
# BE ADVISED USE WITH CAUTION
SELECT
CONCAT('SELECT * FROM ', A.TABLE_SCHEMA, '.', A.TABLE_NAME,
' WHERE ', A.COLUMN_NAME, ' IN (\'%1234567890%\');')
FROM INFORMATION_SCHEMA.COLUMNS A
WHERE
A.TABLE_SCHEMA != 'mysql'
AND A.TABLE_SCHEMA != 'innodb'
AND A.TABLE_SCHEMA != 'performance_schema'
AND A.TABLE_SCHEMA != 'information_schema'
AND A.DATA_TYPE IN ('bigint','int','smallint','tinyint','decimal','double')
;
.
# =================
# BLOB SEARCH
# =================
# BE ADVISED THIS IS CAN END HORRIFICALLY IF YOU DONT KNOW WHAT YOU ARE DOING
# YOU SHOULD KNOW IF YOU HAVE FULL TEXT INDEX ON OR NOT
# MISUSE AND YOU COULD CRASH A LARGE SERVER
SELECT
CONCAT('SELECT CONVERT(',A.COLUMN_NAME, ' USING utf8) FROM ', A.TABLE_SCHEMA, '.', A.TABLE_NAME,
' WHERE CONVERT(',A.COLUMN_NAME, ' USING utf8) IN (\'%someText%\');')
FROM INFORMATION_SCHEMA.COLUMNS A
WHERE
A.TABLE_SCHEMA != 'mysql'
AND A.TABLE_SCHEMA != 'innodb'
AND A.TABLE_SCHEMA != 'performance_schema'
AND A.TABLE_SCHEMA != 'information_schema'
AND A.DATA_TYPE LIKE '%blob%'
;
Results should look like this:
2) You can then just Right Click
and use the Copy Row (tab-separated)
3) Paste results in a new query window and run to your heart's content.
Detail: I exclude system schema's that you may not usually see in your workbench unless you have the option Show Metadata and Internal Schemas
checked.
I did this to provide a quick way to ANALYZE
an entire HOST or DB if needed or to run OPTIMIZE
statements to support performance improvements.
I'm sure there are different ways you may go about doing this but here’s what works for me:
-- ========================================== DYNAMICALLY FIND TABLES AND CREATE A LIST OF QUERIES IN THE RESULTS TO ANALYZE THEM
SELECT CONCAT('ANALYZE TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ';') FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbname';
-- ========================================== DYNAMICALLY FIND TABLES AND CREATE A LIST OF QUERIES IN THE RESULTS TO OPTIMIZE THEM
SELECT CONCAT('OPTIMIZE TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ';') FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbname';
Tested On MySQL Version: 5.6.23
WARNING: DO NOT RUN THIS IF:
- You are concerned with causing Table-locks (keep an eye on your client-connections)
You are unsure about what you are doing.
You are trying to anger you DBA. (you may have people at your desk with the quickness.)
Cheers, Jay ;-]
this how you reset the enitityManager in Symfony3. It should reopen the em if it has been closed:
In a Controller:
$em = $this->getDoctrine()->resetEntityManager();
In a service:
if (!$this->em->isOpen()) {
$this->managerRegistry->resetManager('managername');
$this->em = $this->managerRegistry->getManager('default');
}
$this->em->persist(...);
Don't forget to inject the '@doctrine' as a service argument in service.yml!
I'm wondering, if this problem happens if different methodes concurrently tries to access the same entity at the same time?
Try this:
import time
while True:
print("Hi ", end="\r")
time.sleep(1)
print("Bob", end="\r")
time.sleep(1)
It worked for me. The end="\r"
part is making it overwrite the previous line.
WARNING!
If you print out hi
, then print out hello
using \r
, you’ll get hillo
because the output wrote over the previous two letters. If you print out hi
with spaces (which don’t show up here), then it will output hi
. To fix this, print out spaces using \r
.
var uri = "my test.asp?name=ståle&car=saab";_x000D_
console.log(encodeURI(uri));
_x000D_
Amazing, there are dozens of answers here with javascript and viewports, and only one other mentions text-size-adjust
which is what I believe is the best solution.
You can just set this to none
.
Add the following CSS:
* {
-webkit-text-size-adjust: none;
text-size-adjust: none;
}
No, sorry. User-defined functions in SQL Server are really limited, because of a requirement that they be deterministic. No way round it, as far as I know.
Have you tried debugging the SQL code with Visual Studio?
Check whether you have declared the method where this code is executing as static
. If it is static
there may be some other thread resetting the ResultSet
.
This is what I came up to when trying to copy-paste excel ranges with it's sizes and cell groups. It might be a little too specific for my problem but...:
'** 'Copies a table from one place to another 'TargetRange: where to put the new LayoutTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**
Sub CopyLayout(TargetRange As Range, typee As Integer)
Application.ScreenUpdating = False
Dim ncolumn As Integer
Dim nrow As Integer
SheetLayout.Activate
If (typee = 1) Then 'is installation
Range("installationlayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
ElseIf (typee = 2) Then 'is package
Range("PackageLayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
End If
Sheet2.Select 'SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
If typee = 1 Then
nrow = SheetLayout.Range("installationlayout").Rows.Count
ncolumn = SheetLayout.Range("installationlayout").Columns.Count
Call RowHeightCorrector(SheetLayout.Range("installationlayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
ElseIf typee = 2 Then
nrow = SheetLayout.Range("PackageLayout").Rows.Count
ncolumn = SheetLayout.Range("PackageLayout").Columns.Count
Call RowHeightCorrector(SheetLayout.Range("PackageLayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
End If
Range("A1").Select 'Deselect the created table
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
'** 'Receives the Pasted Table Range and rearranjes it's properties 'accordingly to the original CopiedTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**
Function RowHeightCorrector(CopiedTable As Range, PastedTable As Range, typee As Integer, RowCount As Integer, ColumnCount As Integer)
Dim R As Long, C As Long
For R = 1 To RowCount
PastedTable.Rows(R).RowHeight = CopiedTable.CurrentRegion.Rows(R).RowHeight
If R >= 2 And R < RowCount Then
PastedTable.Rows(R).Group 'Main group of the table
End If
If R = 2 Then
PastedTable.Rows(R).Group 'both type of tables have a grouped section at relative position "2" of Rows
ElseIf (R = 4 And typee = 1) Then
PastedTable.Rows(R).Group 'If it is an installation materials table, it has two grouped sections...
End If
Next R
For C = 1 To ColumnCount
PastedTable.Columns(C).ColumnWidth = CopiedTable.CurrentRegion.Columns(C).ColumnWidth
Next C
End Function
Sub test ()
Call CopyLayout(Sheet2.Range("A18"), 2)
end sub
Simplest way - This will keep the image size as it is and fill the other area with space, this way all the images will take same specified space regardless of the image size without stretching
.img{
width:100px;
height:100px;
/*Scale down will take the necessary specified space that is 100px x 100px without stretching the image*/
object-fit:scale-down;
}
Here is simple way using HTML5 and jQuery:
1) include two JS file
<script src="jslibs/jquery.js" type="text/javascript"></script>
<script src="jslibs/ajaxupload-min.js" type="text/javascript"></script>
2) include CSS to have cool buttons
<link rel="stylesheet" href="css/baseTheme/style.css" type="text/css" media="all" />
3) create DIV or SPAN
<div class="demo" > </div>
4) write this code in your HTML page
$('.demo').ajaxupload({
url:'upload.php'
});
5) create you upload.php file to have PHP code to upload data.
You can download required JS file from here Here is Example
Its too cool and too fast And easy too! :)
This works too and also demonstrates how to change the legend title:
ggplot(df, aes(x, y, colour=g)) +
geom_line(stat="identity") +
theme(legend.position="bottom") +
scale_color_discrete(name="")
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
To use the class ActionBarOverlayLayout
you need to include this in the dependencies section of build.gradle file:
compile 'com.android.support:design:24.1.1'
Sync the project once again and then you will find no problem
According to the release-notes, Java 11 removed the Java EE modules:
java.xml.bind (JAXB) - REMOVED
See JEP 320 for more info.
You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.3</version>
<scope>runtime</scope>
</dependency>
Use latest release of Eclipse Implementation of JAXB 3.0.0:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>3.0.0</version>
<scope>runtime</scope>
</dependency>
Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*
, so update import statements:
javax.xml.bind -> jakarta.xml.bind
Here's yet another idea - this method allows to specify any working week and holidays.
The idea here is that we find the core of the date range from the first first working day of the week to the last weekend day of the week. This enables us to calculate the whole weeks easily (without iterating over all of the dates). All we need to do then is to add the working days that fall before the start and end of this core range.
public static int CalculateWorkingDays(
DateTime startDate,
DateTime endDate,
IList<DateTime> holidays,
DayOfWeek firstDayOfWeek,
DayOfWeek lastDayOfWeek)
{
// Make sure the defined working days run contiguously
if (lastDayOfWeek < firstDayOfWeek)
{
throw new Exception("Last day of week cannot fall before first day of week!");
}
// Create a list of the days of the week that make-up the weekend by working back
// from the firstDayOfWeek and forward from lastDayOfWeek to get the start and end
// the weekend
var weekendStart = lastDayOfWeek == DayOfWeek.Saturday ? DayOfWeek.Sunday : lastDayOfWeek + 1;
var weekendEnd = firstDayOfWeek == DayOfWeek.Sunday ? DayOfWeek.Saturday : firstDayOfWeek - 1;
var weekendDays = new List<DayOfWeek>();
var w = weekendStart;
do {
weekendDays.Add(w);
if (w == weekendEnd) break;
w = (w == DayOfWeek.Saturday) ? DayOfWeek.Sunday : w + 1;
} while (true);
// Force simple dates - no time
startDate = startDate.Date;
endDate = endDate.Date;
// Ensure a progessive date range
if (endDate < startDate)
{
var t = startDate;
startDate = endDate;
endDate = t;
}
// setup some working variables and constants
const int daysInWeek = 7; // yeah - really!
var actualStartDate = startDate; // this will end up on startOfWeek boundary
var actualEndDate = endDate; // this will end up on weekendEnd boundary
int workingDaysInWeek = daysInWeek - weekendDays.Count;
int workingDays = 0; // the result we are trying to find
int leadingDays = 0; // the number of working days leading up to the firstDayOfWeek boundary
int trailingDays = 0; // the number of working days counting back to the weekendEnd boundary
// Calculate leading working days
// if we aren't on the firstDayOfWeek we need to step forward to the nearest
if (startDate.DayOfWeek != firstDayOfWeek)
{
var d = startDate;
do {
if (d.DayOfWeek == firstDayOfWeek || d >= endDate)
{
actualStartDate = d;
break;
}
if (!weekendDays.Contains(d.DayOfWeek))
{
leadingDays++;
}
d = d.AddDays(1);
} while(true);
}
// Calculate trailing working days
// if we aren't on the weekendEnd we step back to the nearest
if (endDate >= actualStartDate && endDate.DayOfWeek != weekendEnd)
{
var d = endDate;
do {
if (d.DayOfWeek == weekendEnd || d < actualStartDate)
{
actualEndDate = d;
break;
}
if (!weekendDays.Contains(d.DayOfWeek))
{
trailingDays++;
}
d = d.AddDays(-1);
} while(true);
}
// Calculate the inclusive number of days between the actualStartDate and the actualEndDate
var coreDays = (actualEndDate - actualStartDate).Days + 1;
var noWeeks = coreDays / daysInWeek;
// add together leading, core and trailing days
workingDays += noWeeks * workingDaysInWeek;
workingDays += leadingDays;
workingDays += trailingDays;
// Finally remove any holidays that fall within the range.
if (holidays != null)
{
workingDays -= holidays.Count(h => h >= startDate && (h <= endDate));
}
return workingDays;
}
I found this to work flawlessly if you want to share whole screen.
@IBAction func shareButton(_ sender: Any) {
let bounds = UIScreen.main.bounds
UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
self.view.drawHierarchy(in: bounds, afterScreenUpdates: false)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let activityViewController = UIActivityViewController(activityItems: [img!], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
Ran into this problem using the same .htaccess configuration. I realized that my server was serving javascript files as text/javascript
instead of application/javascript
. Once I added text/javascript
to the AddOutputFilterByType
declaration, gzip started working.
As to why javascript was being served as text/javascript
: there was an AddType 'text/javascript' js
declaration at the top of my root .htaccess file. After removing it (it had been added in error), javascript starting serving as application/javascript
.
Maybe it is simple, try this if you have a DataFrame. then make sure that both matrices or vectros that you're trying to combine have the same rows_name/index
I had the same issue. I changed the name indices of the rows to make them match each other here is an example for a matrix (principal component) and a vector(target) have the same row indicies (I circled them in the blue in the leftside of the pic)
Before, "when it was not working", I had the matrix with normal row indicies (0,1,2,3) while I had the vector with row indices (ID0, ID1, ID2, ID3) then I changed the vector's row indices to (0,1,2,3) and it worked for me.
Because you are doing integer division.
As @Noldorin says, if both operators are integers, then integer division is used.
The result 0.33333333 can't be represented as an integer, therefore only the integer part (0) is assigned to the result.
If any of the operators is a double
/ float
, then floating point arithmetic will take place. But you'll have the same problem if you do that:
int n = 1.0 / 3.0;
0. Prerequisite: openssl
should be installed. On Windows, if Git Bash
is installed, try that! Alternate binaries can be found here.
1. Extract .key
from .pem
:
openssl pkey -in cert.pem -out cert.key
2. Extract .crt
from .pem
:
openssl crl2pkcs7 -nocrl -certfile cert.pem | openssl pkcs7 -print_certs -out cert.crt
For me the solution was to set the version of the maven compiler plugin to 3.8.0 and specify the release (9 for in your case, 11 in mine)
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
You're using curvy-braces when you should be using parentheses.
A where statement is kept inside a scriptblock, which is defined using curvy baces { }
. To isolate/wrap you tests, you should use parentheses ()
.
I would also suggest trying to do the filtering on the remote computer. Try:
Invoke-Command -computername SERVERNAME {
Get-ChildItem -path E:\dfsroots\datastore2\public |
Where-Object { ($_.extension -eq "xls" -or $_.extension -eq "xlk") -and $_.creationtime -ge "06/01/2014" }
}
For unit test:
spyOn(component.form, 'valid').and.returnValue(true);
For those who need to return the data thru Jsonify with Flask:
cursor = db.collection.find()
data = []
for doc in cursor:
doc['_id'] = str(doc['_id']) # This does the trick!
data.append(doc)
return jsonify(data)
Adegoke A, Amit
I guess one crucial point you people are missing is difference between data and pointers as explained in this section.
Pointer : pointer to other nodes.
Data :- In context of database indexes, data is just another pointer to real data (row) which reside somewhere else.
Hence in case of B tree each node has three information keys, pointers to data associated with the keys and pointer to child nodes.
In B+ tree internal node keep keys and pointers to child node while leaf node keep keys and pointers to associated data. This allows more number of key for a given size of node. Size of node is determined mainly by block size.
Advantage of having more key per node is explained well above so I will save my typing effort.
You need to merge the remote branch into your current branch by running git pull
.
If your local branch is already up-to-date, you may also need to run git pull --rebase
.
A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.
This situation happens when you have several implementations. Let me explain. Supppose you have several sorting algorithm and you want to choose at runtime the one to implement, or you want to give to someone else the capability to add his implementation. To solve this problem you usually create an abstract class (Parent) and have different implementation (Child). If you write:
Child c = new Child();
you bind your implementation to Child class and you can't change it anymore. Otherwise if you use:
Parent p = new Child();
as long as Child extends Parent you can change it in the future without modifying the code.
The same thing can be done using interfaces: Parent isn't anymore a class but a java Interface.
In general you can use this approch in DAO pattern where you want to have several DB dependent implementations. You can give a look at FactoryPatter or AbstractFactory Pattern. Hope this can help you.
Others have already given thorough answers, but if you're looking for even more information, the Oracle Java tutorials are always a good resource. Here's the Java tutorial for Exceptions, which covers all of your questions in great detail; https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html
Convert the image to a byte[]
and store that in the database.
Add this column to your model:
public byte[] Content { get; set; }
Then convert your image to a byte array and store that like you would any other data:
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using(var ms = new MemoryStream())
{
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
}
public Image ByteArrayToImage(byte[] byteArrayIn)
{
using(var ms = new MemoryStream(byteArrayIn))
{
var returnImage = Image.FromStream(ms);
return returnImage;
}
}
Source: Fastest way to convert Image to Byte array
var image = new ImageEntity()
{
Content = ImageToByteArray(image)
};
_context.Images.Add(image);
_context.SaveChanges();
When you want to get the image back, get the byte array from the database and use the ByteArrayToImage
and do what you wish with the Image
This stops working when the byte[]
gets to big. It will work for files under 100Mb
The rules about how much memory is consumed depend on the JVM implementation and the CPU architecture (32 bit versus 64 bit for example).
For the detailed rules for the SUN JVM check my old blog
Regards, Markus
FYI this kind of code works (you can find it ugly, it is your right :) ) :
def list = null
list.each { println it }
soSomething()
In other words, this code has null/empty checks both useless:
if (members && !members.empty) {
members.each { doAnotherThing it }
}
def doAnotherThing(def member) {
// Some work
}
You can set up a meta-table to track the number of entries, this may be faster than iteration if this information is a needed frequently.
You would need a mapping provider for MySQL. That is an extra thing the Entity Framework needs to make the magic happen. This blog talks about other mapping providers besides the one Microsoft is supplying. I haven't found any mentionings of MySQL.
How about wait-notify
private Boolean bool = true;
private final Object lock = new Object();
private Boolean getChange(){
synchronized(lock){
while (bool) {
bool.wait();
}
}
return bool;
}
public void setChange(){
synchronized(lock){
bool = false;
bool.notify();
}
}
You only need ng-model when you need to access the model's $viewValue or $modelValue. See NgModelController. And in that case, you would use require: '^ngModel'
.
For the rest, see Roys answer.
How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...
If you want to have element with visible blank text just do this:
$('#doc_title').html(' ');
In the MySQL interactive client you can type:
source yourfile.sql
Alternatively you can pipe the data into mysql from the command line:
mysql < yourfile.sql
If the file doesn't specify a database then you will also need to add that:
mysql db_name < yourfile.sql
See the documentation for more details:
My Hackie way to solve this was by modifying the swagger.go file in the echo-swagger package in my case:
At the bottom of the file update the window.onload function to include a requestInterceptor which correctly formats the token.
window.onload = function() {
// Build a system
const ui = SwaggerUIBundle({
url: "{{.URL}}",
dom_id: '#swagger-ui',
validatorUrl: null,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
,
layout: "StandaloneLayout",
requestInterceptor: (req) => {
req.headers.Authorization = "Bearer " + req.headers.Authorization
return req
}
})
window.ui = ui
}
You can also work with a so called boolean vector, aka logical
:
row_to_keep = c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE)
myData = myData[row_to_keep,]
Note that the !
operator acts as a NOT, i.e. !TRUE == FALSE
:
myData = myData[!row_to_keep,]
This seems a bit cumbersome in comparison to @mrwab's answer (+1 btw :)), but a logical vector can be generated on the fly, e.g. where a column value exceeds a certain value:
myData = myData[myData$A > 4,]
myData = myData[!myData$A > 4,] # equal to myData[myData$A <= 4,]
You can transform a boolean vector to a vector of indices:
row_to_keep = which(myData$A > 4)
Finally, a very neat trick is that you can use this kind of subsetting not only for extraction, but also for assignment:
myData$A[myData$A > 4,] <- NA
where column A
is assigned NA
(not a number) where A
exceeds 4.
One classic root cause for this message is:
git init lis4368/assignments
),Ie, if you don't have added and committed at least once, there won't be a local master
branch to push to.
Try first to create a commit:
git add .
) then git commit -m "first commit"
git commit --allow-empty -m "Initial empty commit"
And then try git push -u origin master
again.
See "Why do I need to explicitly push a new branch?" for more.
It is a general vision. Details are depended on real language realisation
lock
- thread synchronization tool. When thread get a lock it becomes a single thread which is able to execute a block of code. All others thread are blocked. Only thread which owns by lock can unlock it
mutex
- mutual exclusion lock. It is a kind of lock. On some languages it is inter-process mechanism, on some languages it is a synonym of lock
. For example Java uses lock
in synchronised
and java.util.concurrent.locks.Lock
semaphore
- allows a number of threads to access a shared resource. You can find that mutex
also can be implemented by semaphore
. It is a standalone object which manage an access to shared resource. You can find that any thread can signal
and unblock. Also it is used for signalling
to @BalusC answer I would add how to convert the response in a String:
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
}
As an improvement to the accepted answer, in order to reduce nesting, you could do this instead, provided that the key is not inherited:
for (var key in dictionary) {
if (!dictionary.hasOwnProperty(key)) {
continue;
}
console.log(key, dictionary[key]);
}
Edit: info about Object.hasOwnProperty
here
this code probable help you .
<iframe src="" onload="this.width=screen.width;this.height=screen.height;">
The "!" sign is the key element. If you have a cell object (like "mycell" in following code sample) and link a cell to this object you must pay attention to ! element.
You must do something like this:
.Cells(i, 2).Hyperlinks.Add Anchor:=.Range(Cells(i, 2).Address), Address:="", _
SubAddress:= "'" & ws.Name & "'" & _
"!" & mycell.Address
No you can't; datetime will be stored in default format only while creating table and then you can change the display format in you select
query the way you want using the Mysql Date Time Functions
<div class="row" style="padding-left:21px;">
<ul class="nav nav-tabs" style="padding-left:40px;">
<li class="active filter"><a href="#month" onclick="Data(this)">This Month</a></li>
<li class="filter"><a href="#year" onclick="Data(this)">Year</a></li>
<li class="filter"><a href="#last60" onclick="Data(this)">60 Days</a></li>
<li class="filter"><a href="#last90" onclick="Data(this)">90 Days</a></li>
</ul>
</div>
<script>
function Data(element)
{
element.removeClass('active');
element.addClass('active') ;
}
</script>
You should be able to do this with JavaScript:
<input type="button" value="Click Me!" onclick="submitForms()" />
If your forms have IDs:
submitForms = function(){
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
If your forms don't have IDs but have names:
submitForms = function(){
document.forms["form1"].submit();
document.forms["form2"].submit();
}
What is currentWorksheet
? It works if you use the built-in ActiveSheet
.
dataStartRow=1
dataStartCol=1
dataEndRow=4
dataEndCol=4
Set currentWorksheet=ActiveSheet
dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, dataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))
The following is Peter Lyons' answer verbatim, ported over to vanilla JS from Coffeescript, as requested by several others. Peter's answer is very able, and anyone voting on my answer should vote on his as well.
Config
What you are doing is fine. I like to have my own config namespace set up in a top-level config.js
file with a nested namespace like this.
// Set the current environment to true in the env object
var currentEnv = process.env.NODE_ENV || 'development';
exports.appName = "MyApp";
exports.env = {
production: false,
staging: false,
test: false,
development: false
};
exports.env[currentEnv] = true;
exports.log = {
path: __dirname + "/var/log/app_#{currentEnv}.log"
};
exports.server = {
port: 9600,
// In staging and production, listen loopback. nginx listens on the network.
ip: '127.0.0.1'
};
if (currentEnv != 'production' && currentEnv != 'staging') {
exports.enableTests = true;
// Listen on all IPs in dev/test (for testing from other machines)
exports.server.ip = '0.0.0.0';
};
exports.db {
URL: "mongodb://localhost:27017/#{exports.appName.toLowerCase()}_#{currentEnv}"
};
This is friendly for sysadmin editing. Then when I need something, like the DB connection info, it`s
require('./config').db.URL
Routes/Controllers
I like to leave my routes with my controllers and organize them in an app/controllers
subdirectory. Then I can load them up and let them add whatever routes they need.
In my app/server.js
javascript file I do:
[
'api',
'authorization',
'authentication',
'domains',
'users',
'stylesheets',
'javascripts',
'tests',
'sales'
].map(function(controllerName){
var controller = require('./controllers/' + controllerName);
controller.setup(app);
});
So I have files like:
app/controllers/api.js
app/controllers/authorization.js
app/controllers/authentication.js
app/controllers/domains.js
And for example in my domains controller, I have a setup
function like this.
exports.setup = function(app) {
var controller = new exports.DomainController();
var route = '/domains';
app.post(route, controller.create);
app.put(route, api.needId);
app.delete(route, api.needId);
route = '/domains/:id';
app.put(route, controller.loadDomain, controller.update);
app.del(route, controller.loadDomain, function(req, res){
res.sendJSON(req.domain, status.OK);
});
}
Views
Putting views in app/views
is becoming the customary place. I lay it out like this.
app/views/layout.jade
app/views/about.jade
app/views/user/EditUser.jade
app/views/domain/EditDomain.jade
Static Files
Go in a public
subdirectory.
Github/Semver/NPM
Put a README.md markdown file at your git repo root for github.
Put a package.json file with a semantic version number in your git repo root for NPM.
Convert string to ascii values.
String test = "ABCD";
for ( int i = 0; i < test.length(); ++i ) {
char c = test.charAt( i );
int j = (int) c;
System.out.println(j);
}
just run the following command in the node project
npm install
its worked for me
After iOS 13 you should detect iOS devices like this, since iPad will not be detected as iOS devices by old ways (due to new "desktop" options, enabled by default):
let isIOS = /iPad|iPhone|iPod/.test(navigator.platform)
|| (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
The first condition for iOS < 13 or iPhone or iPad with disabled Desktop mode, the second condition for iPadOS 13 in the default configuration, since it position itself like Macintosh Intel, but actually is the only Macintosh with multi-touch.
Rather a hack than a real solution, but work reliably for me
P.S. As being said earlier, you probably should add IE checkup
let isIOS = (/iPad|iPhone|iPod/.test(navigator.platform) ||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) &&
!window.MSStream
So easy we can get the String from files by method: getText();
public class Main {
static int countOfWords(String str) {
if (str.equals("") || str == null) {
return 0;
}else{
int numberWords = 0;
for (char c : str.toCharArray()) {
if (c == ' ') {
numberWords++;
}
}
return ++numberWordss;
}
}
}
I had the same issue, I found most of the answers here out dated. I ended up writing a wrapper on FFMPEG to access from Android with a single line of code.
I believe that you're looking for numpy.split
or possibly numpy.array_split
if the number of sections doesn't need to divide the size of the array properly.
SQL Server doesn't have regular expressions. It uses the LIKE pattern matching syntax which isn't the same.
As it happens, you are close. Just need leading+trailing wildcards and move the NOT
WHERE whatever NOT LIKE '%[a-z0-9]%'
The instantclient works only by defining the folder in the windows PATH environment variable. But you can "install" manually to create some keys in the Windows registry. How?
1) Download instantclient (http://www.oracle.com/technetwork/topics/winsoft-085727.html)
2) Unzip the ZIP file (eg c:\oracle\instantclient).
3) Include the above path in the PATH.
4) Create the registry key:
[HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE]
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE]
5) In the above registry key, create a sub-key starts with "KEY_" followed by the name of the installation you want:
[HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\KEY_INSTANTCLIENT]
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE\KEY_INSTANTCLIENT]
6) Now create at least three string values ??in the above key:
NLS_LANG = BRAZILIAN PORTUGUESE_BRAZIL.WE8MSWIN1252
(complete list here: http://docs.oracle.com/cd/B19306_01/install.102/b14317/gblsupp.htm)ORACLE_HOME = c:\oracle\instantclient
(the same folder in PATH)ORACLE_HOME_NAME = MY_INSTANTCLIENT
(choose any name)For those who use Quest SQL Navigator or Quest Toad for Oracle will see that it works. Displays the message "Home is valid.":
The registry keys are now displayed for selecting the oracle client:
I don't think putting %AppData% in a string like that will work.
try
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString()
Why to invent the wheel?
There is a very popular NPM package, that let you do things like that easy.
var recursive = require("recursive-readdir");
recursive("some/path", function (err, files) {
// `files` is an array of file paths
console.log(files);
});
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
here is a great article of how to vetical align.. I like the float way.
http://www.vanseodesign.com/css/vertical-centering/
The HTML:
<div id="main">
<div id="floater"></div>
<div id="inner">Content here</div>
</div>
And the corresponding style:
#main {
height: 250px;
}
#floater {
float: left;
height: 50%;
width: 100%;
margin-bottom: -50px;
}
#inner {
clear: both;
height: 100px;
}
This is to help anyone who comes here looking for a solution that wants a pure approach. I would recommend understanding this problem because it can happen in lots of different places not just with a JS Buffer object. By understanding why the problem exists and how to solve it you will improve your ability to solve other problems in the future since this one is so fundamental.
For those of us that have to deal with these problems in other languages it is quite natural to devise a solution, but there are people who may not realize how to abstract away the complexities and implement a generally efficient dynamic buffer. The code below may have potential to be optimized further.
I have left the read method unimplemented to keep the example small in size.
The realloc
function in C (or any language dealing with intrinsic allocations) does not guarantee that the allocation will be expanded in size with out moving the existing data - although sometimes it is possible. Therefore most applications when needing to store a unknown amount of data will use a method like below and not constantly reallocate, unless the reallocation is very infrequent. This is essentially how most file systems handle writing data to a file. The file system simply allocates another node and keeps all the nodes linked together, and when you read from it the complexity is abstracted away so that the file/buffer appears to be a single contiguous buffer.
For those of you who wish to understand the difficulty in just simply providing a high performance dynamic buffer you only need to view the code below, and also do some research on memory heap algorithms and how the memory heap works for programs.
Most languages will provide a fixed size buffer for performance reasons, and then provide another version that is dynamic in size. Some language systems opt for a third-party system where they keep the core functionality minimal (core distribution) and encourage developers to create libraries to solve additional or higher level problems. This is why you may question why a language does not provide some functionality. This small core functionality allows costs to be reduced in maintaining and enhancing the language, however you end up having to write your own implementations or depending on a third-party.
var Buffer_A1 = function (chunk_size) {
this.buffer_list = [];
this.total_size = 0;
this.cur_size = 0;
this.cur_buffer = [];
this.chunk_size = chunk_size || 4096;
this.buffer_list.push(new Buffer(this.chunk_size));
};
Buffer_A1.prototype.writeByteArrayLimited = function (data, offset, length) {
var can_write = length > (this.chunk_size - this.cur_size) ? (this.chunk_size - this.cur_size) : length;
var lastbuf = this.buffer_list.length - 1;
for (var x = 0; x < can_write; ++x) {
this.buffer_list[lastbuf][this.cur_size + x] = data[x + offset];
}
this.cur_size += can_write;
this.total_size += can_write;
if (this.cur_size == this.chunk_size) {
this.buffer_list.push(new Buffer(this.chunk_size));
this.cur_size = 0;
}
return can_write;
};
/*
The `data` parameter can be anything that is array like. It just must
support indexing and a length and produce an acceptable value to be
used with Buffer.
*/
Buffer_A1.prototype.writeByteArray = function (data, offset, length) {
offset = offset == undefined ? 0 : offset;
length = length == undefined ? data.length : length;
var rem = length;
while (rem > 0) {
rem -= this.writeByteArrayLimited(data, length - rem, rem);
}
};
Buffer_A1.prototype.readByteArray = function (data, offset, length) {
/*
If you really wanted to implement some read functionality
then you would have to deal with unaligned reads which could
span two buffers.
*/
};
Buffer_A1.prototype.getSingleBuffer = function () {
var obuf = new Buffer(this.total_size);
var cur_off = 0;
var x;
for (x = 0; x < this.buffer_list.length - 1; ++x) {
this.buffer_list[x].copy(obuf, cur_off);
cur_off += this.buffer_list[x].length;
}
this.buffer_list[x].copy(obuf, cur_off, 0, this.cur_size);
return obuf;
};
What about little simpler approach.
Item last = null;
foreach (Item result in Model.Results)
{
// do something with each item
last = result;
}
//Here Item 'last' contains the last object that came in the last of foreach loop.
DoSomethingOnLastElement(last);
To scale an image, you need to create a new image and draw into it. One way is to use the filter()
method of an AffineTransferOp
, as suggested here. This allows you to choose the interpolation technique.
private static BufferedImage scale1(BufferedImage before, double scale) {
int w = before.getWidth();
int h = before.getHeight();
// Create a new image of the proper size
int w2 = (int) (w * scale);
int h2 = (int) (h * scale);
BufferedImage after = new BufferedImage(w2, h2, BufferedImage.TYPE_INT_ARGB);
AffineTransform scaleInstance = AffineTransform.getScaleInstance(scale, scale);
AffineTransformOp scaleOp
= new AffineTransformOp(scaleInstance, AffineTransformOp.TYPE_BILINEAR);
scaleOp.filter(before, after);
return after;
}
Another way is to simply draw the original image into the new image, using a scaling operation to do the scaling. This method is very similar, but it also illustrates how you can draw anything you want in the final image. (I put in a blank line where the two methods start to differ.)
private static BufferedImage scale2(BufferedImage before, double scale) {
int w = before.getWidth();
int h = before.getHeight();
// Create a new image of the proper size
int w2 = (int) (w * scale);
int h2 = (int) (h * scale);
BufferedImage after = new BufferedImage(w2, h2, BufferedImage.TYPE_INT_ARGB);
AffineTransform scaleInstance = AffineTransform.getScaleInstance(scale, scale);
AffineTransformOp scaleOp
= new AffineTransformOp(scaleInstance, AffineTransformOp.TYPE_BILINEAR);
Graphics2D g2 = (Graphics2D) after.getGraphics();
// Here, you may draw anything you want into the new image, but we're
// drawing a scaled version of the original image.
g2.drawImage(before, scaleOp, 0, 0);
g2.dispose();
return after;
}
Addendum: Results
To illustrate the differences, I compared the results of the five methods below. Here is what the results look like, scaled both up and down, along with performance data. (Performance varies from one run to the next, so take these numbers only as rough guidelines.) The top image is the original. I scale it double-size and half-size.
As you can see, AffineTransformOp.filter()
, used in scaleBilinear()
, is faster than the standard drawing method of Graphics2D.drawImage()
in scale2()
. Also BiCubic interpolation is the slowest, but gives the best results when expanding the image. (For performance, it should only be compared with scaleBilinear()
and scaleNearest().
) Bilinear seems to be better for shrinking the image, although it's a tough call. And NearestNeighbor is the fastest, with the worst results. Bilinear seems to be the best compromise between speed and quality. The Image.getScaledInstance()
, called in the questionable()
method, performed very poorly, and returned the same low quality as NearestNeighbor. (Performance numbers are only given for expanding the image.)
public static BufferedImage scaleBilinear(BufferedImage before, double scale) {
final int interpolation = AffineTransformOp.TYPE_BILINEAR;
return scale(before, scale, interpolation);
}
public static BufferedImage scaleBicubic(BufferedImage before, double scale) {
final int interpolation = AffineTransformOp.TYPE_BICUBIC;
return scale(before, scale, interpolation);
}
public static BufferedImage scaleNearest(BufferedImage before, double scale) {
final int interpolation = AffineTransformOp.TYPE_NEAREST_NEIGHBOR;
return scale(before, scale, interpolation);
}
@NotNull
private static
BufferedImage scale(final BufferedImage before, final double scale, final int type) {
int w = before.getWidth();
int h = before.getHeight();
int w2 = (int) (w * scale);
int h2 = (int) (h * scale);
BufferedImage after = new BufferedImage(w2, h2, before.getType());
AffineTransform scaleInstance = AffineTransform.getScaleInstance(scale, scale);
AffineTransformOp scaleOp = new AffineTransformOp(scaleInstance, type);
scaleOp.filter(before, after);
return after;
}
/**
* This is a more generic solution. It produces the same result, but it shows how you
* can draw anything you want into the newly created image. It's slower
* than scaleBilinear().
* @param before The original image
* @param scale The scale factor
* @return A scaled version of the original image
*/
private static BufferedImage scale2(BufferedImage before, double scale) {
int w = before.getWidth();
int h = before.getHeight();
// Create a new image of the proper size
int w2 = (int) (w * scale);
int h2 = (int) (h * scale);
BufferedImage after = new BufferedImage(w2, h2, before.getType());
AffineTransform scaleInstance = AffineTransform.getScaleInstance(scale, scale);
AffineTransformOp scaleOp
= new AffineTransformOp(scaleInstance, AffineTransformOp.TYPE_BILINEAR);
Graphics2D g2 = (Graphics2D) after.getGraphics();
// Here, you may draw anything you want into the new image, but we're just drawing
// a scaled version of the original image. This is slower than
// calling scaleOp.filter().
g2.drawImage(before, scaleOp, 0, 0);
g2.dispose();
return after;
}
/**
* I call this one "questionable" because it uses the questionable getScaledImage()
* method. This method is no longer favored because it's slow, as my tests confirm.
* @param before The original image
* @param scale The scale factor
* @return The scaled image.
*/
private static Image questionable(final BufferedImage before, double scale) {
int w2 = (int) (before.getWidth() * scale);
int h2 = (int) (before.getHeight() * scale);
return before.getScaledInstance(w2, h2, Image.SCALE_FAST);
}
Neither <iostream>
nor <iostream.h>
are standard C header files. Your code is meant to be C++, where <iostream>
is a valid header. Use g++
(and a .cpp
file extension) for C++ code.
Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream>
and using namespace std;
, and replace cout << endl;
with putchar('\n');
... I advise compiling using C99 (eg. gcc -std=c99
)
One important application of Kruskal's algorithm is in single link clustering.
Consider n vertices and you have a complete graph.To obtain a k clusters of those n points.Run Kruskal's algorithm over the first n-(k-1) edges of the sorted set of edges.You obtain k-cluster of the graph with maximum spacing.
After linking up your jquery and bootstrap write your code just below the Script tags of jquery and bootstrap.
$(document).ready(function($) {_x000D_
$("#div").on("click", "a", function(event) {_x000D_
event.preventDefault();_x000D_
jQuery.noConflict();_x000D_
$('#myModal').modal('show');_x000D_
_x000D_
});_x000D_
});
_x000D_
<!-- jQuery library -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
_x000D_
<!-- Latest compiled JavaScript -->_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
_x000D_
First Of All Firebase.ServerValue.TIMESTAMP
is not working anymore for me.
So for adding timestamp you have to use Firebase.database.ServerValue.TIMESTAMP
And the timestamp is in long millisecond format.To convert millisecond to simple dateformat .
Ex- dd/MM/yy HH:mm:ss
You can use the following code in java:
To get the timestamp value in string from the firebase database
String x = dataSnapshot.getValue (String.class);
The data is in string now. You can convert the string
to long
long milliSeconds= Long.parseLong(x);
Then create SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
Now convert your millisecond timestamp to ur sdf format
String dateAsString = sdf.format (milliSeconds);
After that you can parse it to ur Date
variable
date = sdf.parse (dateAsString);
insertRow2 <- function(existingDF, newrow, r) {
existingDF <- rbind(existingDF,newrow)
existingDF <- existingDF[order(c(1:(nrow(existingDF)-1),r-0.5)),]
row.names(existingDF) <- 1:nrow(existingDF)
return(existingDF)
}
insertRow2(existingDF,newrow,r)
V1 V2 V3 V4
1 1 6 11 16
2 2 7 12 17
3 1 2 3 4
4 3 8 13 18
5 4 9 14 19
6 5 10 15 20
microbenchmark(
+ rbind(existingDF[1:r,],newrow,existingDF[-(1:r),]),
+ insertRow(existingDF,newrow,r),
+ insertRow2(existingDF,newrow,r)
+ )
Unit: microseconds
expr min lq median uq max
1 insertRow(existingDF, newrow, r) 513.157 525.6730 531.8715 544.4575 1409.553
2 insertRow2(existingDF, newrow, r) 430.664 443.9010 450.0570 461.3415 499.988
3 rbind(existingDF[1:r, ], newrow, existingDF[-(1:r), ]) 606.822 625.2485 633.3710 653.1500 1489.216
Note: You don't need to check if your service is running, CheckIfServiceIsRunning()
, because bindService()
will start it if it isn't running.
Also: if you rotate the phone you don't want it to bindService()
again, because onCreate()
will be called again. Be sure to define onConfigurationChanged()
to prevent this.
I don't know if you can automatically change the color, but you could exploit your loop to generate different colors:
for i in range(20):
ax1.plot(x, y, color = (0, i / 20.0, 0, 1)
In this case, colors will vary from black to 100% green, but you can tune it if you want.
See the matplotlib plot() docs and look for the color
keyword argument.
If you want to feed a list of colors, just make sure that you have a list big enough and then use the index of the loop to select the color
colors = ['r', 'b', ...., 'w']
for i in range(20):
ax1.plot(x, y, color = colors[i])
Hi i have a shorter version. this does same as a best answer. (it works on chrome 74.03)
document.querySelectorAll('*').forEach(e => e.oncontextmenu = null)
The virtual
keyword in C# enables a method or property to be overridden by child classes. For more information please refer to the MSDN documentation on the 'virtual' keyword
UPDATE: This doesn't answer the question as currently asked, but I'll leave it here for anyone looking for a simple answer to the original, non-descriptive question asked.
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
To call a function inside a same controller in any laravel version follow as bellow
$role = $this->sendRequest('parameter');
// sendRequest is a public function
You can escape by doubling the quotes
g="abcd """ & a & """"
or write an explicit chr()
call
g="abcd " & chr(34) & a & chr(34)
For MongoDB 3.6 and newer:
The $expr
operator allows the use of aggregation expressions within the query language, thus you can leverage the use of $strLenCP
operator to check the length of the string as follows:
db.usercollection.find({
"name": { "$exists": true },
"$expr": { "$gt": [ { "$strLenCP": "$name" }, 40 ] }
})
For MongoDB 3.4 and newer:
You can also use the aggregation framework with the $redact
pipeline operator that allows you to proccess the logical condition with the $cond
operator and uses the special operations $$KEEP
to "keep" the document where the logical condition is true or $$PRUNE
to "remove" the document where the condition was false.
This operation is similar to having a $project
pipeline that selects the fields in the collection and creates a new field that holds the result from the logical condition query and then a subsequent $match
, except that $redact
uses a single pipeline stage which is more efficient.
As for the logical condition, there are String Aggregation Operators that you can use $strLenCP
operator to check the length of the string. If the length is $gt
a specified value, then this is a true match and the document is "kept". Otherwise it is "pruned" and discarded.
Consider running the following aggregate operation which demonstrates the above concept:
db.usercollection.aggregate([
{ "$match": { "name": { "$exists": true } } },
{
"$redact": {
"$cond": [
{ "$gt": [ { "$strLenCP": "$name" }, 40] },
"$$KEEP",
"$$PRUNE"
]
}
},
{ "$limit": 2 }
])
If using $where
, try your query without the enclosing brackets:
db.usercollection.find({$where: "this.name.length > 40"}).limit(2);
A better query would be to to check for the field's existence and then check the length:
db.usercollection.find({name: {$type: 2}, $where: "this.name.length > 40"}).limit(2);
or:
db.usercollection.find({name: {$exists: true}, $where: "this.name.length >
40"}).limit(2);
MongoDB evaluates non-$where
query operations before $where
expressions and non-$where
query statements may use an index. A much better performance is to store the length of the string as another field and then you can index or search on it; applying $where
will be much slower compared to that. It's recommended to use JavaScript expressions and the $where
operator as a last resort when you can't structure the data in any other way, or when you are dealing with a
small subset of data.
A different and faster approach that avoids the use of the $where
operator is the $regex
operator. Consider the following pattern which searches for
db.usercollection.find({"name": {"$type": 2, "$regex": /^.{41,}$/}}).limit(2);
Note - From the docs:
If an index exists for the field, then MongoDB matches the regular expression against the values in the index, which can be faster than a collection scan. Further optimization can occur if the regular expression is a “prefix expression”, which means that all potential matches start with the same string. This allows MongoDB to construct a “range” from that prefix and only match against those values from the index that fall within that range.
A regular expression is a “prefix expression” if it starts with a caret
(^)
or a left anchor(\A)
, followed by a string of simple symbols. For example, the regex/^abc.*/
will be optimized by matching only against the values from the index that start withabc
.Additionally, while
/^a/, /^a.*/,
and/^a.*$/
match equivalent strings, they have different performance characteristics. All of these expressions use an index if an appropriate index exists; however,/^a.*/
, and/^a.*$/
are slower./^a/
can stop scanning after matching the prefix.
Use
=~
for regular expression check Regular Expressions Tutorial Table of Contents
I think below link might help you -
Use curl
to fetch the HTTP-header only (not the whole file) and parse it:
$ curl -I --stderr /dev/null http://www.google.co.uk/index.html | head -1 | cut -d' ' -f2
200
Best and simple approach.
DECLARE @AccumulateKeywordCopy NVARCHAR(2000),@IDDupCopy NVARCHAR(50);
SET @AccumulateKeywordCopy ='';
SET @IDDupCopy ='';
SET @IDDup = (SELECT CONVERT(VARCHAR(MAX), <columnName>) FROM <tableName> WHERE <clause>)
SET @AccumulateKeywordCopy = ','+@AccumulateKeyword+',';
SET @IDDupCopy = ','+@IDDup +',';
SET @IDDupCheck = CHARINDEX(@IDDupCopy,@AccumulateKeywordCopy)
You can create a Task with cancellation token, when you app goto background you can cancel this token.
You can do this in PCL https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/app-lifecycle
var cancelToken = new CancellationTokenSource();
Task.Factory.StartNew(async () => {
await Task.Delay(10000);
// call web API
}, cancelToken.Token);
//this stops the Task:
cancelToken.Cancel(false);
Anther solution is user Timer in Xamarin.Forms, stop timer when app goto background https://xamarinhelp.com/xamarin-forms-timer/
Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings
or use:
tr '\r\n' ' '
Solution:
var answerInt = [];
var answerString = "1,2,3,4";
answerString.split(',').forEach(function (item) {
answerInt.push(parseInt(item))
});
For this purpose you need to make the connection result set
ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE
Connection con=null;
//initialize connection variable to connect to your database...
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String query="Select MYCLOB from TABLE_NAME for update";
con.setAutoCommit(false);
ResultSet resultset=stmt.executeQuery(query);
if(resultset.next()){
oracle.sql.CLOB clobnew = ((OracleResultSet) rss).getCLOB("MYCLOB");
PrintWriter pw = new PrintWriter(clobnew.getCharacterOutputStream() );
BufferedReader br = new BufferedReader( new FileReader( new File("filename.xml") ) );
String lineIn = null;
while( ( lineIn = br.readLine() ) != null )
pw.println( lineIn );
pw.close();
br.close();
}
con.setAutoCommit(true);
con.commit();
}
Note: its important that you add the phrase for update at the end of the query that is written to select the row...
Follow the above code to insert the XML file
you can use this command
mysql> UPDATE mysql.user SET Password=PASSWORD('Your new Password') WHERE User='root';
check the links http://www.kirupa.com/forum/showthread.php?279644-How-to-reset-password-in-WAMP-server http://www.phpmytutor.com/blogs/2012/08/27/change-mysql-root-password-in-wamp-server/
Find your config.inc.php file under the phpMyAdmin installation directory and update the line that looks like
this:
$cfg['Servers'][$i]['password'] = 'password';
... to this:
$cfg['Servers'][$i]['password'] = 'newpassword';
On windows, you can use PuttyGen to load the private key file, remove the passphrase and then overwrite the existing private key file.
This was how I added a tracking branch so I can pull from it into my new branch:
git branch --set-upstream-to origin/Development new-branch
Bootstrap 4 (4.0.0-alpha.2) uses the css property column-count
in the card-columns
class to define how many columns of cards would be displayed inside the div
element.
But this property has only two values:
max-width: 34em
)min-width: 34em
)Here's how it is implemented in bootstrap.min.css :
@media (min-width: 34em) {
.card-columns {
-webkit-column-count:3;
-moz-column-count:3;
column-count:3;
?
}
?
}
To make the card stacking responsive, you can add the following media queries to your css file and modify the values for min-width
as per your requirements :
@media (min-width: 34em) {
.card-columns {
-webkit-column-count: 2;
-moz-column-count: 2;
column-count: 2;
}
}
@media (min-width: 48em) {
.card-columns {
-webkit-column-count: 3;
-moz-column-count: 3;
column-count: 3;
}
}
@media (min-width: 62em) {
.card-columns {
-webkit-column-count: 4;
-moz-column-count: 4;
column-count: 4;
}
}
@media (min-width: 75em) {
.card-columns {
-webkit-column-count: 5;
-moz-column-count: 5;
column-count: 5;
}
}
This trick worked for me (for min-sdk >= 18).
I used android:includeFontPadding="false"
and a negative margin like android:layout_marginTop="-11dp"
and put my TextView
inside a FrameLayout
( or any ViewGroup...)
and finally sample codes:
<LinearLayout
android:layout_width="60dp"
android:layout_height="wrap_content"
>
<TextView
style="@style/MyTextViews.Bold"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/yellow"
android:textSize="48sp"
android:layout_marginTop="-11dp"
android:includeFontPadding="false"
tools:text="1"/>
</LinearLayout>
You're asking it to parse the JSON text something
(not "something"
). That's invalid JSON, strings must be in double quotes.
If you want an equivalent to your first example:
var s = '"something"';
var result = JSON.parse(s);
For SwiftUI
If you are making your own TextView using UIViewRepresentable
and want to control the padding, in your makeUIView
function, simply do:
uiTextView.textContainerInset = UIEdgeInsets(top: 10, left: 18, bottom: 0, right: 18)
or whatever you want.
You can pass the JVM this param
-Duser.timezone
For example
-Duser.timezone=Europe/Sofia
and this should do the trick. Setting the environment variable TZ also does the trick on Linux.
This is for extra information.
Imagine this scenario
ActivityB launch a new ActivityAPrime by
Intent intent = new Intent(getApplicationContext(), ActivityA.class);
startActivity(intent);
ActivityAPrime has no relationship with ActivityA.
In this case the Bundle in ActivityAPrime.onCreate() will be null.
If ActivityA and ActivityAPrime should be the same activity instead of different activities, ActivityB should call finish() than using startActivity().
This will work:
var myColumnDefs = new Object();
for (var i = 0; i < oFullResponse.results.length; i++) {
myColumnDefs[i] = ({key:oFullResponse.results[i].label, sortable:true, resizeable:true});
}
My only, yet essential, use for a comma is in a for loop:
for (var i = 0, n = a.length; i < n; i++) {
var e = a[i];
console.log(e);
}
I went here to look up whether this is OK in JavaScript.
Even seeing it work, a question remained whether n
is local to the function.
This verifies n
is local:
a = [3, 5, 7, 11];
(function l () { for (var i = 0, n = a.length; i < n; i++) {
var e = a[i];
console.log(e);
}}) ();
console.log(typeof n == "undefined" ?
"as expected, n was local" : "oops, n was global");
For a moment I wasn't sure, switching between languages.
It probably means that your MySQL server is only listening the localhost interface.
If you have lines like this :
bind-address = 127.0.0.1
In your my.cnf
configuration file, you should comment them (add a # at the beginning of the lines), and restart MySQL.
sudo service mysql restart
Of course, to do this, you must be the administrator of the server.
If you mean an in-place sort (i.e. the list is updated):
people.Sort((x, y) => string.Compare(x.LastName, y.LastName));
If you mean a new list:
var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional
I think the load event is right. What is not right is the way you use to retreive the content from iframe content dom.
What you need is the html of the page loaded in the iframe not the html of the iframe object.
What you have to do is to access the content document with iFrameObj.contentDocument
.
This returns the dom of the page loaded inside the iframe, if it is on the same domain of the current page.
I would retreive the content before removing the iframe.
I've tested in firefox and opera.
Then i think you can retreive your data with $(childDom).html()
or $(childDom).find('some selector') ...
You cannot use iOS APIs alone to capture the phone number (even in a private app with private APIs), as all known methods of doing this have been patched and blocked as of iOS 11. Even if a new exploit is found, Apple has made clear that they will reject any apps from the app store for using private APIs to do this. See @Dylan's answer for details.
However, there is a legal way to capture the phone number without any user data entry. This is similar to what Snapchat does, but easier, as it does not require the user to type in their own phone number.
The idea is to have the app programmatically send a SMS message to a server with the app’s unique installation code. The app can then query the same server to see if it has recently received a SMS message from a device with this unique app installation code. If it has, it can read the phone number that sent it. Here’s a demo video showing the process. As you can see, it works like a charm!
This is not super easy to set up, but it be configured in a few hours at no charge on a free AWS tier with the sample code provided in the tutorial here.
It depends on the task you want to do, but I wouldn't use it. Also, check if the thread-save-ness you want to accompish couldn't be done by synchronize(this) in the first place? There are also some nice locks in the API that might help you :)
Taking some of the things you have described:
"So you could be sure that some fields in a class are defined for every implementation of this interface."
"If a define a Interface for this class so that I can have more classes which implement the message interface, I can only define the send method and not the constructor"
...these requirements are exactly what abstract classes are for.
Abstraction means to show only the necessary details to the client of the object
Actually that is encapsulation. also see the first part of the wikipedia article in order to not be confused by encapsulation and data hiding. http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)
keep in mind that by simply hiding all you class members 1:1 behind properties is not encapsulation at all. encapsulation is all about protecting invariants and hiding of implementation details.
here a good article about that. http://blog.ploeh.dk/2012/11/27/Encapsulationofproperties/ also take a look at the articles linked in that article.
classes, properties and access modifiers are tools to provide encapsulation in c#.
you do encapsulation in order to reduce complexity.
Abstraction is "the process of identifying common patterns that have systematic variations; an abstraction represents the common pattern and provides a means for specifying which variation to use" (Richard Gabriel).
Yes, that is a good definition for abstraction.
They are different concepts. Abstraction is the process of refining away all the unneeded/unimportant attributes of an object and keep only the characteristics best suitable for your domain.
Yes, they are different concepts. keep in mind that abstraction is actually the opposite of making an object suitable for YOUR domain ONLY. it is in order to make the object suitable for the domain in general!
if you have a actual problem and provide a specific solution, you can use abstraction to formalize a more generic solution that can also solve more problems that have the same common pattern. that way you can increase the re-usability for your components or use components made by other programmers that are made for the same domain, or even for different domains.
good examples are classes provided by the .net framework, for example list or collection. these are very abstract classes that you can use almost everywhere and in a lot of domains. Imagine if .net only implemented a EmployeeList class and a CompanyList that could only hold a list of employees and companies with specific properties. such classes would be useless in a lot of cases. and what a pain would it be if you had to re-implement the whole functionality for a CarList for example. So the "List" is ABSTRACTED away from Employee, Company and Car. The List by itself is an abstract concept that can be implemented by its own class.
Interfaces, abstract classes or inheritance and polymorphism are tools to provide abstraction in c#.
you do abstraction in order to provide reusability.
What you are looking for is called Geocoding.
Google provides a Geocoding Web Service which should do what you're looking for. You will be able to do geocoding on your server.
JSON Example:
http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA
XML Example:
http://maps.google.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA
Edit:
Please note that this is now a deprecated method and you must provide your own Google API key to access this data.
With ES6 MDN docs .includes()
"FooBar".includes("oo"); // true
"FooBar".includes("foo"); // false
"FooBar".includes("oo", 2); // false
E: Not suported by IE - instead you can use the Tilde opperator ~
(Bitwise NOT) with .indexOf()
~"FooBar".indexOf("oo"); // -2 -> true
~"FooBar".indexOf("foo"); // 0 -> false
~"FooBar".indexOf("oo", 2); // 0 -> false
Used with a number, the Tilde operator effective does
~N => -(N+1)
. Use it with double negation !!
(Logical NOT) to convert the numbers in bools:
!!~"FooBar".indexOf("oo"); // true
!!~"FooBar".indexOf("foo"); // false
!!~"FooBar".indexOf("oo", 2); // false
For replace you can use vbCrLf
:
Replace(string, vbCrLf, "")
You can also use chr(13)+chr(10)
.
I seem to remember in some odd cases that chr(10)
comes before chr(13)
.
Apparently no one has come up with a multi-platform* solution for over a decade since [the] year 2008, so I shall append mine . Plz upvote. (Joking. I don’t care.)
lltoa()
How to use:
#include <stdlib.h> /* lltoa() */
// ...
char dummy[255];
printf("Over 4 bytes: %s\n", lltoa(5555555555, dummy, 10));
printf("Another one: %s\n", lltoa(15555555555, dummy, 10));
OP’s example:
#include <stdio.h>
#include <stdlib.h> /* lltoa() */
int main() {
unsigned long long int num = 285212672; // fits in 29 bits
char dummy[255];
int normalInt = 5;
printf("My number is %d bytes wide and its value is %s. "
"A normal number is %d.\n",
sizeof(num), lltoa(num, dummy, 10), normalInt);
return 0;
}
Unlike the %lld
print format string, this one works for me under 32-bit GCC on Windows.
*) Well, almost multi-platform. In MSVC, you apparently need _ui64toa()
instead of lltoa()
.
You can remove the fragments when destroy the viewpager, in my case, I removed them on onDestroyView()
of my fragment:
@Override
public void onDestroyView() {
if (getChildFragmentManager().getFragments() != null) {
for (Fragment fragment : getChildFragmentManager().getFragments()) {
getChildFragmentManager().beginTransaction().remove(fragment).commitAllowingStateLoss();
}
}
super.onDestroyView();
}
Looks like the solution is to set the value of the properties inside the default constructor. So in this case the java class is:
class JavaObject {
public JavaObject() {
optionalMember = "Value";
}
@NotNull
public String notNullMember;
public String optionalMember;
}
After the mapping with Jackson, if the optionalMember
is missing from the JSON its value in the Java class is "Value"
.
However, I am still interested to know if there is a solution with annotations and without the default constructor.
Based on the other users' answers, I wrote these custom mixins for easier usage:
.when-xs(@rules) { @media (max-width: @screen-xs-max) { @rules(); } }
.when-sm(@rules) { @media (min-width: @screen-sm-min) { @rules(); } }
.when-md(@rules) { @media (min-width: @screen-md-min) { @rules(); } }
.when-lg(@rules) { @media (min-width: @screen-lg-min) { @rules(); } }
Example usage
body {
.when-lg({
background-color: red;
});
}
@mixin when-xs() { @media (max-width: $screen-xs-max) { @content; } }
@mixin when-sm() { @media (min-width: $screen-sm-min) { @content; } }
@mixin when-md() { @media (min-width: $screen-md-min) { @content; } }
@mixin when-lg() { @media (min-width: $screen-lg-min) { @content; } }
Example usage:
body {
@include when-md {
background-color: red;
}
}
@media (min-width:1200px) {
body {
background-color: red;
}
}
This is useful when textfield superview is view
class AdminLoginViewController: UIViewController,
UITextFieldDelegate{
@IBOutlet weak var txtUserName: UITextField!
@IBOutlet weak var txtUserPassword: UITextField!
@IBOutlet weak var btnAdminLogin: UIButton!
private var activeField : UIView?
var param:String!
var adminUser : Admin? = nil
var kbHeight: CGFloat!
override func viewDidLoad()
{
self.addKeyBoardObserver()
self.addGestureForHideKeyBoard()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func addGestureForHideKeyBoard()
{
let tapGesture = UITapGestureRecognizer(target: self, action: Selector("hideKeyboard"))
tapGesture.cancelsTouchesInView = false
view.addGestureRecognizer(tapGesture)
}
func hideKeyboard() {
self.view.endEditing(true)
}
func addKeyBoardObserver(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeKeyboardFrame:",
name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeKeyboardFrame:",
name:UIKeyboardWillHideNotification, object: nil)
}
func removeObserver(){
NSNotificationCenter.defaultCenter().removeObserver(self)
}
//MARK:- textfiled Delegate
func textFieldShouldBeginEditing(textField: UITextField) -> Bool
{
activeField = textField
return true
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool
{
if activeField == textField
{
activeField = nil
}
return true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if txtUserName == textField
{
txtUserPassword.becomeFirstResponder()
}
else if (textField == txtUserPassword)
{
self.btnAdminLoginAction(nil)
}
return true;
}
func willChangeKeyboardFrame(aNotification : NSNotification)
{
if self.activeField != nil && self.activeField!.isFirstResponder()
{
if let keyboardSize = (aNotification.userInfo![UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
{
let dy = (self.activeField?.superview?.convertRect((self.activeField?.frame)!, toView: view).origin.y)!
let height = (self.view.frame.size.height - keyboardSize.size.height)
if dy > height
{
var frame = self.view.frame
frame.origin.y = -((dy - height) + (self.activeField?.frame.size.height)! + 20)
self.view.frame = frame
}
}
}
else
{
var frame = self.view.frame
frame.origin.y = 0
self.view.frame = frame
}
} }
You can use a watchpoint for this (A breakpoint on data instead of code).
You can start by using watch i
.
Then set a condition for it using condition <breakpoint num> i == 5
You can get the breakpoint number by using info watch
Just copy an image into your res/drawable
folder and use
imageView.setImageResource(R.drawable.my_image);
The variety of answers can cause a little confusion. We have
setBackgroundResource()
setBackgroundDrawable()
setBackground()
setImageResource()
setImageDrawable()
setImageBitmap()
The methods with Background
in their name all belong to the View
class, not to ImageView
specifically. But since ImageView
inherits from View
you can use them, too. The methods with Image
in their name belong specifically to ImageView
.
The View
methods all do the same thing as each other (though setBackgroundDrawable()
is deprecated), so we will just focus on setBackgroundResource()
. Similarly, the ImageView
methods all do the same thing, so we will just focus on setImageResource()
. The only difference between the methods is they type of parameter you pass in.
Here is a FrameLayout
that contains an ImageView
. The ImageView
initially doesn't have any image in it. (I only added the FrameLayout
so that I could put a border around it. That way you can see the edge of the ImageView
.)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="250dp"
android:layout_height="250dp"
android:background="@drawable/border"
android:layout_centerInParent="true">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
</RelativeLayout>
Below we will compare the different methods.
If you use ImageView's setImageResource()
, then the image keeps its aspect ratio and is resized to fit. Here are two different image examples.
imageView.setImageResource(R.drawable.sky);
imageView.setImageResource(R.drawable.balloons);
Using View's setBackgroundResource()
, on the other hand, causes the image resource to be stretched to fill the view.
imageView.setBackgroundResource(R.drawable.sky);
imageView.setBackgroundResource(R.drawable.balloons);
The View's background image and the ImageView's image are drawn separately, so you can set them both.
imageView.setBackgroundResource(R.drawable.sky);
imageView.setImageResource(R.drawable.balloons);
In case you are using IntelliJ you can enable the Database view (View -> Tools Window -> Database)
Inside that view connect to your database. Then you can rightclick the database and select "Copy DDL". Other IDEs may offer a similar function.
You can pass a name to the unknown key and then write your types:
type StuffBody = {
[key: string]: string;
};
Now you can use it in your type checking:
let stuff: StuffBody = {};
But for FlowType there is no need to have name:
type StuffBody = {
[string]: string,
};
If you do not have an LDF file then:
1) put the MDF in the C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\
2) In ssms, go to Databases -> Attach
and add the MDF file. It will not let you add it this way but it will tell you the database name contained within.
3) Make sure the user you are running ssms.exe as has acccess to this MDF file.
4) Now that you know the DbName, run
EXEC sp_attach_single_file_db @dbname = 'DbName',
@physname = N'C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\yourfile.mdf';
Reference: https://dba.stackexchange.com/questions/12089/attaching-mdf-without-ldf
The virtual mechanism only works when you have a based class pointer to a derived class object. Construction has it's own rules for the calling of base class constructors, basically base class to derived. How could a virtual constructor be useful or called? I don't know what other languages do, but I can't see how a virtual constructor could be useful or even implemented. Construction needs to have taken place for the virtual mechanism to make any sense and construction also needs to have taken place for the vtable structures to have been created which provides the mechanics of the polymorphic behaviour.
Install Node js - https://nodejs.org/en/
go to folder where you have html file:
npm install http-server -g
http-server
If you have specific html file. Run following command in CMD.- http-server fileName
by default port is 8080
Go to your browser and type localhost:8080
. Your Application should
run there.
If you want to run on different port: http-server fileName -p 9000
Note : To run your .js file run:
node fileName.js
As of iOS 5 this one is far more easy:
[newView setAlpha:0.0];
[UIView animateWithDuration:0.4 animations:^{
[newView setAlpha:0.5];
}];
Using .attr
method
.attr(attribute,value); // syntax
.attr("required", true);
// required="required"
.attr("required", false);
//
Using .prop
.prop(property,value) // syntax
.prop("required", true);
// required=""
.prop("required", false);
//
Read more from here
VB is full of things like that trying to make it both "like English" and comfortable for people who are used to languages that use () and {} a lot. And on the other side, as you already probably know, most of the time you can use () with function calls if you want to, but don't have to.
I prefer IsNothing()... but I use C and C#, so that's just what is comfortable. And I think it's more readable. But go with whatever feels more comfortable to you.
I've successfully used pdftk to remove pages I didn't want/need in pdfs. You can download the program here
You might try something like the following. Taken from here under examples
Remove 'page 13' from in1.pdf to create out1.pdf pdftk in.pdf cat 1-12 14-end output out1.pdf
or:
pdftk A=in1.pdf cat A1-12 A14-end output out1.pdf
Another simple and quick solution
.giveMeEllipsis {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: N; /* number of lines to show */
line-height: X; /* fallback */
max-height: X*N; /* fallback */
}
The reference to the original question and answer is here
Run java
with -d64
or -d32
specified, it will give you an error message if it doesn't support 64-bit or 32-bit respectively. Your JVM may support both.
if you just type
$ git update
on bash git will inform you that 'update' command is no longer working and will display the correct command which is 'update-git-for-windows'
but still the update will continue you just have to press " y "
if you are having issues on it run the bashh as administrator or add the 'git.exe' path to the "allowed apps through controlled folder access".
<Program files>\Android\Android-sdk\platforms\<platform SDK's>
On a 32bit machine:
"<Program files>
" will be \Program Files\
On a 64bit machine:
If you installed the 32bit ADT, "<Program files>
" will be \Program Files (x86)\
If you installed the 64bit ADT, "<Program files>
" will be \Program Files\
The latest version of .Net (v4.6) just added built-in support for Unix time conversions. That includes both to and from Unix time represented by either seconds or milliseconds.
DateTimeOffset
:DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(1000);
DateTimeOffset
to Unix time in seconds:long unixTimeStampInSeconds = dateTimeOffset.ToUnixTimeSeconds();
DateTimeOffset
:DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(1000000);
DateTimeOffset
to Unix time in milliseconds:long unixTimeStampInMilliseconds= dateTimeOffset.ToUnixTimeMilliseconds();
Note: These methods convert to and from DateTimeOffset
. To get a DateTime
representation simply use the DateTimeOffset.DateTime
property:
DateTime dateTime = dateTimeOffset.UtcDateTime;
The normal, Pythonic, preferred solution is almost invariably "duck typing": try using the argument as if it was of a certain desired type, do it in a try/except statement catching all exceptions that could arise if the argument was not in fact of that type (or any other type nicely duck-mimicking it;-), and in the except clause, try something else (using the argument "as if" it was of some other type).
Read the rest of his post for helpful information.
I have tried to make note about these and have collected and written examples from a java perspective.
Putting it here for any java developer who is looking into the same subject.
Try this out:
<script type="text/javascript">
function test
{
alert("hello world"); //write your logic here like ajax
}
</script>
<form action="javascript:test();" >
firstName : <input type="text" name="firstName" id="firstName" required/><br/>
lastName : <input type="text" name="lastName" id="lastName" required/><br/>
email : <input type="email" name="email" id="email"/><br/>
<input type="submit" value="Get It!" name="submit" id="submit"/>
</form>
This will do the trick
.gallery-item
{
opacity:1;
}
.gallery-item:hover
{
opacity:0;
transition: opacity .2s ease-out;
-moz-transition: opacity .2s ease-out;
-webkit-transition: opacity .2s ease-out;
-o-transition: opacity .2s ease-out;
}
Add this one to your header file:
template <typename T> vector<T> concat(vector<T> &a, vector<T> &b) {
vector<T> ret = vector<T>();
copy(a.begin(), a.end(), back_inserter(ret));
copy(b.begin(), b.end(), back_inserter(ret));
return ret;
}
and use it this way:
vector<int> a = vector<int>();
vector<int> b = vector<int>();
a.push_back(1);
a.push_back(2);
b.push_back(62);
vector<int> r = concat(a, b);
r will contain [1,2,62]
You should stop the task that you have scheduled on the timer: Your timer:
Timer t = new Timer();
TimerTask tt = new TimerTask() {
@Override
public void run() {
//do something
};
}
t.schedule(tt,1000,1000);
In order to stop:
tt.cancel();
t.cancel(); //In order to gracefully terminate the timer thread
Notice that just cancelling the timer will not terminate ongoing timertasks.
Now I solved this issue in this way,
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.OutputStream;
// Create a trust manager that does not validate certificate chains like the
default TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
//No need to implement.
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
//No need to implement.
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
System.out.println(e);
}
np.append needs the array as the first argument and the list you want to append as the second:
mean_data = np.append(mean_data, [ur, ua, np.mean(data[samepoints,-1])])
You can use the with_entities()
method to restrict which columns you'd like to return in the result. (documentation)
result = SomeModel.query.with_entities(SomeModel.col1, SomeModel.col2)
Depending on your requirements, you may also find deferreds useful. They allow you to return the full object but restrict the columns that come over the wire.
For me, this error was caused when I tried to duplicate an existing res/menu
instead of creating one with the wizard
.
Vivaldi Chromium-based Browser can hide the address bar for my Home Theather PC. Using that app you can show/hide a floating bar with F8 key. Other answers are unrelated to what was asked!
Based on @ArchCodeMonkey answer.
If you have declare(strict_types=1)
you must cast second argument to string
I think may be this is also acceptable and simple.
Guid.NewGuid().ToString()
Use Calendar.
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) - 1);
Here are another 2 options that allow you to invoke SaveChanges() in a for each loop.
The first option is use one DBContext to generate your list objects to iterate through, and then create a 2nd DBContext to call SaveChanges() on. Here is an example:
//Get your IQueryable list of objects from your main DBContext(db)
IQueryable<Object> objects = db.Object.Where(whatever where clause you desire);
//Create a new DBContext outside of the foreach loop
using (DBContext dbMod = new DBContext())
{
//Loop through the IQueryable
foreach (Object object in objects)
{
//Get the same object you are operating on in the foreach loop from the new DBContext(dbMod) using the objects id
Object objectMod = dbMod.Object.Find(object.id);
//Make whatever changes you need on objectMod
objectMod.RightNow = DateTime.Now;
//Invoke SaveChanges() on the dbMod context
dbMod.SaveChanges()
}
}
The 2nd option is to get a list of database objects from the DBContext, but to select only the id's. And then iterate through the list of id's (presumably an int) and get the object corresponding to each int, and invoke SaveChanges() that way. The idea behind this method is grabbing a large list of integers, is a lot more efficient then getting a large list of db objects and calling .ToList() on the entire object. Here is an example of this method:
//Get the list of objects you want from your DBContext, and select just the Id's and create a list
List<int> Ids = db.Object.Where(enter where clause here)Select(m => m.Id).ToList();
var objects = Ids.Select(id => db.Objects.Find(id));
foreach (var object in objects)
{
object.RightNow = DateTime.Now;
db.SaveChanges()
}
Add the param declation at the top of ps1 file
test.ps1
param(
# Our preferred encoding
[parameter(Mandatory=$false)]
[ValidateSet("UTF8","Unicode","UTF7","ASCII","UTF32","BigEndianUnicode")]
[string]$Encoding = "UTF8"
)
write ("Encoding : {0}" -f $Encoding)
result
C:\temp> .\test.ps1 -Encoding ASCII
Encoding : ASCII
After reading the article from Marc Cliament's comment above, I've now changed my all-purpose cross-browser console.log function to look like this:
function log()
{
"use strict";
if (typeof(console) !== "undefined" && console.log !== undefined)
{
try
{
console.log.apply(console, arguments);
}
catch (e)
{
var log = Function.prototype.bind.call(console.log, console);
log.apply(console, arguments);
}
}
}
Generally you have'got an answer now but maybe my class I created will be also helpfull. For me it solves all my requirements I have ever had in my Pyhon projects.
class GetDate:
def __init__(self, date, format="%Y-%m-%d"):
self.tz = pytz.timezone("Europe/Warsaw")
if isinstance(date, str):
date = datetime.strptime(date, format)
self.date = date.astimezone(self.tz)
def time_delta_days(self, days):
return self.date + timedelta(days=days)
def time_delta_hours(self, hours):
return self.date + timedelta(hours=hours)
def time_delta_seconds(self, seconds):
return self.date + timedelta(seconds=seconds)
def get_minimum_time(self):
return datetime.combine(self.date, time.min).astimezone(self.tz)
def get_maximum_time(self):
return datetime.combine(self.date, time.max).astimezone(self.tz)
def get_month_first_day(self):
return datetime(self.date.year, self.date.month, 1).astimezone(self.tz)
def current(self):
return self.date
def get_month_last_day(self):
lastDay = calendar.monthrange(self.date.year, self.date.month)[1]
date = datetime(self.date.year, self.date.month, lastDay)
return datetime.combine(date, time.max).astimezone(self.tz)
How to use it
self.tz = pytz.timezone("Europe/Warsaw")
- here you define Time Zone you want to use in projectGetDate("2019-08-08").current()
- this will convert your string date to time aware object with timezone you defined in pt 1. Default string format is format="%Y-%m-%d"
but feel free to change it. (eg. GetDate("2019-08-08 08:45", format="%Y-%m-%d %H:%M").current()
)GetDate("2019-08-08").get_month_first_day()
returns given date (string or object) month first dayGetDate("2019-08-08").get_month_last_day()
returns given date month last dayGetDate("2019-08-08").minimum_time()
returns given date day startGetDate("2019-08-08").maximum_time()
returns given date day endGetDate("2019-08-08").time_delta_days({number_of_days})
returns given date + add {number of days} (you can also call: GetDate(timezone.now()).time_delta_days(-1)
for yesterday)GetDate("2019-08-08").time_delta_haours({number_of_hours})
similar to pt 7 but working on hoursGetDate("2019-08-08").time_delta_seconds({number_of_seconds})
similar to pt 7 but working on secondsAssuming you have empty values of types one approach would be this:
var x = (((objectA ?? A.Empty).PropertyOfB ?? B.Empty).PropertyOfC ?? C.Empty).PropertyOfString;
I'm a big fan of C# but a very nice thing in new Java (1.7?) is the .? operator:
var x = objectA.?PropertyOfB.?PropertyOfC.?PropertyOfString;
You can do this by using the recursive function. This will work even if you don't know all nested Object keys name.
function FetchKeys(obj) {
let objKeys = [];
let keyValues = Object.entries(obj);
for (let i in keyValues) {
objKeys.push(keyValues[i][0]);
if (typeof keyValues[i][1] == "object") {
var keys = FetchKeys(keyValues[i][1])
objKeys = objKeys.concat(keys);
}
}
return objKeys;
}
let test = { level1: { level2: { level3: "level3" } } };
let keyToCheck = "level2";
let keys = FetchKeys(test); //Will return an array of Keys
if (keys.indexOf(keyToCheck) != -1) {
//Key Exists logic;
}
else {
//Key Not Found logic;
}
String jsonErrorString=((HttpClientErrorException)exception).getResponseBodyAsString();
JSONObject jsonObj=null;
String errorDetails=null;
String status=null;
try {
jsonObj = new JSONObject(jsonErrorString);
int index =jsonObj.getString("detail").indexOf(":");
errorDetails=jsonObj.getString("detail").substring(index);
status=jsonObj.getString("status");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
item.put("status", status);
item.put("errordetailMsg", errorDetails);
This seems simple enough and works both in python 2 and 3
try: subprocess.check_output('which executable',shell=True)
except: sys.exit('ERROR: executable not found')
Putting some of the given solutions together, knowing that readlink is available on most systems, but needs different arguments, this works well for me on OSX and Debian. I'm not sure about BSD systems. Maybe the condition needs to be [[ $OSTYPE != darwin* ]]
to exclude -f
from OSX only.
#!/bin/bash
MY_DIR=$( cd $(dirname $(readlink `[[ $OSTYPE == linux* ]] && echo "-f"` $0)) ; pwd -P)
echo "$MY_DIR"
Form nesting can be achieved with new HTML5 input element's form attribute. Although we don't nest forms structurally, inputs are evaluated as they are in their own form. In my tests, 3 major browsers support this except IE(IE11). Form nesting limitation was a big obstacle for HTML UI design.
Here is a sample code, when you click Save button you should see "2 3 success" (Original http://www.impressivewebs.com/html5-form-attribute/):
<form id="saveForm" action="/post/dispatch/save" method="post"></form>
<form id="deleteForm" action="/post/dispatch/delete" method="post"></form>
<div id="toolbar">
<input type="text" name="foo" form="saveForm" />
<input type="hidden" value="some_id" form="deleteForm" />
<input type="text" name="foo2" id="foo2" form="saveForm" value="success" />
<input type="submit" name="save" value="Save" form="saveForm" onclick="alert(document.getElementById('deleteForm').elements.length + ' ' + document.getElementById('saveForm').elements.length + ' ' + document.getElementById('saveForm').elements['foo2'].value);return false;" />
<input type="submit" name="delete" value="Delete" form="deleteForm" />
<a href="/home/index">Cancel</a>
</div>
To go along with what v01d said:
Using Android Studio for Mac OS X, the SDK folder could also be at /Users/{user}/Library/Android/sdk
, where {user} is your username.
To find out where the partial SDK installation is, go to Configure > SDK Manager in Android Studio, then click edit at the top. This should pop up a window and show the location.
Copy this path and paste it front of the cd
command in a terminal. Finally execute sudo ./android sdk
to launch the standalone SDK manager.
EDIT (July 14, 2016):
The "android" binary file could also be at /Users/{user}/Library/Android/sdk/tools
.
You must put the updatepanel id in the first argument if the control causing the script is inside the updatepanel else use the keyword 'this' instead of update panel here is the code
ScriptManager.RegisterStartupScript(UpdatePanel3, this.GetType(), UpdatePanel3.UniqueID, "showError();", true);
You can copy subscribers dictionary object to a same type of temporary dictionary object and then iterate the temporary dictionary object using foreach loop.
I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:
div.hardware-accelarate {
-webkit-transform: translate3d(0,0,0);
-moz-transform: translate3d(0,0,0);
-ms-transform: translate3d(0,0,0);
-o-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
I've made a plunkr setup for ya'll to test and tweak...
PHP's Laravel framework, I am using search first_name, last_name Fields consider like Full Name Search
Using || symbol Or concat_ws(), concat() methods
$names = str_replace(" ", "", $searchKey);
$customers = Customer::where('organization_id',$this->user->organization_id)
->where(function ($q) use ($searchKey, $names) {
$q->orWhere('phone_number', 'ilike', "%{$searchKey}%");
$q->orWhere('email', 'ilike', "%{$searchKey}%");
$q->orWhereRaw('(first_name || last_name) LIKE ? ', '%' . $names. '%');
})->orderBy('created_at','desc')->paginate(20);
This worked charm!!!
I have tried several solutions today, the one working best for me is Jo-Geek/jQuery-ResizableColumns. Is is very simple, yet it handles tables placed in flex containers, which many of the other ones fail with.
<table class="resizable">
</table>
$('table.resizable').resizableColumns();
$(function() {_x000D_
$('table.resizable').resizableColumns();_x000D_
})
_x000D_
body {_x000D_
margin: 0px;_x000D_
}_x000D_
_x000D_
table {_x000D_
width: 100%;_x000D_
table-layout: fixed;_x000D_
border-collapse: collapse;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://jo-geek.github.io/jQuery-ResizableColumns/demo/resizableColumns.min.js"></script>_x000D_
<table class="resizable" border="true">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>col 1</th><th>col 2</th><th>col 3</th><th>col 4</th>_x000D_
</tr>_x000D_
</thead>_x000D_
_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
This image displayed below gives a clear understanding and shows the exact difference between .append()
, .prepend()
, .after()
and .before()
You can see from the image that .append()
and .prepend()
adds the new elements as child elements (brown colored) to the target.
And .after()
and .before()
adds the new elements as sibling elements (black colored) to the target.
Here is a DEMO for better understanding.
EDIT: the flipped versions of those functions:
Using this code:
var $target = $('.target');
$target.append('<div class="child">1. append</div>');
$target.prepend('<div class="child">2. prepend</div>');
$target.before('<div class="sibling">3. before</div>');
$target.after('<div class="sibling">4. after</div>');
$('<div class="child flipped">or appendTo</div>').appendTo($target);
$('<div class="child flipped">or prependTo</div>').prependTo($target);
$('<div class="sibling flipped">or insertBefore</div>').insertBefore($target);
$('<div class="sibling flipped">or insertAfter</div>').insertAfter($target);
on this target:
<div class="target">
This is the target div to which new elements are associated using jQuery
</div>
So although these functions flip the parameter order, each creates the same element nesting:
var $div = $('<div>').append($('<img>'));
var $img = $('<img>').appendTo($('<div>'))
...but they return a different element. This matters for method chaining.
SELECT rest.field1
FROM mastertable as m
INNER JOIN table1 at t1 on t1.field1 = m.field
INNER JOIN table2 at t2 on t2.field = t1.field
WHERE t1.field3 = (SELECT MAX(field3) FROM table1)
You have two objects both named bank_holiday
-- one a list and one a function. Disambiguate the two.
bank_holiday[month]
is raising an error because Python thinks bank_holiday
refers to the function (the last object bound to the name bank_holiday
), whereas you probably intend it to mean the list.
You'll need to use UNION
to combine the results of two queries. In your case:
SELECT ChargeNum, CategoryID, SUM(Hours)
FROM KnownHours
GROUP BY ChargeNum, CategoryID
UNION ALL
SELECT ChargeNum, 'Unknown' AS CategoryID, SUM(Hours)
FROM UnknownHours
GROUP BY ChargeNum
Note - If you use UNION ALL
as in above, it's no slower than running the two queries separately as it does no duplicate-checking.
Try with paramter
.....................
.....................
using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = " + @IDNumber, con))
{
command.Paramter.Add("@IDNumber",IDNumber)
command.ExecuteNonQuery();
}
.....................
.....................
No need to close connection in using statement
The answer of pratt is bit uncomplete, because when you restart your device your app will working stop, recording stop, its become useless.
i m adding some line that copy in your project for complete working of Pratt answer.
<receiver
android:name=".DeviceAdminDemo"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data
android:name="android.app.admin"
android:resource="@xml/device_admin" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLE_REQUESTED" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
put this code in onReceive of DeviceAdminDemo
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
context.stopService(new Intent(context, TService.class));
Intent myIntent = new Intent(context, TService.class);
context.startService(myIntent);
}
Check if the module is available with php -m | grep pdo_mysql
.
If not, for PHP 7.2, you can install relevant package with sudo apt install php7.2-mysql
.
Use similar command on other PHP versions and package managers.
I rewrote the accepted answer and facile it for the newbies.
#break it down and understand it intuitively.
new = {}
for (key, value) in data:
if key not in new:
new[key] = [] # this is core of setdefault equals to new.setdefault(key, [])
new[key].append(value)
else:
new[key].append(value)
# easy with setdefault
new = {}
for (key, value) in data:
group = new.setdefault(key, []) # it is new[key] = []
group.append(value)
# even simpler with defaultdict
new = defaultdict(list)
for (key, value) in data:
new[key].append(value) # all keys have a default value of empty list []
Additionally,I categorized the methods as reference:
dict_methods_11 = {
'views':['keys', 'values', 'items'],
'add':['update','setdefault'],
'remove':['pop', 'popitem','clear'],
'retrieve':['get',],
'copy':['copy','fromkeys'],}
Swift 4.2
I also delete my last character from String (i.e. UILabel text) in IOS app
@IBOutlet weak var labelText: UILabel! // Do Connection with UILabel
@IBAction func whenXButtonPress(_ sender: UIButton) { // Do Connection With X Button
labelText.text = String((labelText.text?.dropLast())!) // Delete the last caracter and assign it
}
The provided answers didn't work for me. I'm adding another answer because this is where I ended up when searching for radio stream urls.
Radio Browser is a searchable site with streaming urls for radio stations around the world:
http://www.radio-browser.info/
Search for a station like FIP, Pinguin Radio or Radio Paradise, then click the save button, which downloads a PLS file that you can open in your radioplayer (Rhythmbox), or you open the file in a text editor and copy the URL to add in Goodvibes.
You can use Scanner class like this:
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner scan= new Scanner(System.in);
//For string
String text= scan.nextLine();
System.out.println(text);
//for int
int num= scan.nextInt();
System.out.println(num);
}
}
The solution for PyMongo (Python mongo):
db.example.update({}, {'$unset': {'tags.words':1}}, multi=True);
I only change/remove the class:
function removeClass() {
var element = angular.element('#nameInput');
element.removeClass('nameClass');
};
If you have a container and two sub containers, you can do like this
jQuery
$("#previousbutton").click(function() {
$("#form_sub_container1").show();
$("#form_sub_container2").hide(); })
$("#nextbutton").click(function() {
$("#form_container").find(":hidden").show().next();
$("#form_sub_container1").hide();
})
HTML
<div id="form_container">
<div id="form_sub_container1" style="display: block;">
</div>
<div id="form_sub_container2" style="display: none;">
</div>
</div>
I think this way is the simplier. The output displays the id and the payer's email where the payer's email is in more than one record at this table. The results are sorted by id.
SELECT id, payer_email
FROM paypal_ipn_orders
WHERE COUNT( payer_email )>1
SORT BY id;
If your web application is configured to impersonate a client, then using a trusted connection will potentially have a negative performance impact. This is because each client must use a different connection pool (with the client's credentials).
Most web applications don't use impersonation / delegation, and hence don't have this problem.
See this MSDN article for more information.
if you are interested in a ready solution then you may look at HumanizerCpp library (https://github.com/trodevel/HumanizerCpp) - it is a port of C# Humanizer library and it does exactly what you want.
It can even convert to ordinals and currently supports 3 languages: English, German and Russian.
Example:
const INumberToWordsConverter * e = Configurator::GetNumberToWordsConverter( "en" );
std::cout << e->Convert( 123 ) << std::endl;
std::cout << e->Convert( 1234 ) << std::endl;
std::cout << e->Convert( 12345 ) << std::endl;
std::cout << e->Convert( 123456 ) << std::endl;
std::cout << std::endl;
std::cout << e->ConvertToOrdinal( 1001 ) << std::endl;
std::cout << e->ConvertToOrdinal( 1021 ) << std::endl;
const INumberToWordsConverter * g = Configurator::GetNumberToWordsConverter( "de" );
std::cout << std::endl;
std::cout << g->Convert( 123456 ) << std::endl;
const INumberToWordsConverter * r = Configurator::GetNumberToWordsConverter( "ru" );
std::cout << r->ConvertToOrdinal( 1112 ) << std::endl;
Output:
one hundred and twenty-three
one thousand two hundred and thirty-four
twelve thousand three hundred and forty-five
one hundred and twenty-three thousand four hundred and fifty-six
thousand and first
thousand and twenty-first
einhundertdreiundzwanzigtausendvierhundertsechsundfünfzig
???? ?????? ??? ???????????
In any case you may take a look at the source code and reuse in your project or try to understand the logic. It is written in pure C++ without external libraries.
Regards, Serge
A few comments:
import sun.misc.*;
Don't do this. It is non-standard and not guaranteed to be the same between implementations. There are other libraries with Base64 conversion available.
byte[] encVal = c.doFinal(Data.getBytes());
You are relying on the default character encoding here. Always specify what character encoding you are using: byte[] encVal = c.doFinal(Data.getBytes("UTF-8"));
Defaults might be different in different places.
As @thegrinner pointed out, you need to explicitly check the length of your byte arrays. If there is a discrepancy, then compare them byte by byte to see where the difference is creeping in.
Here's a solution for more extreme cases:
if [ `command | head -c1 | wc -c` -gt 0 ]; then ...; fi
This will work
however,