A variable prefixed with @
is an instance variable, while one prefixed with @@
is a class variable. Check out the following example; its output is in the comments at the end of the puts
lines:
class Test
@@shared = 1
def value
@@shared
end
def value=(value)
@@shared = value
end
end
class AnotherTest < Test; end
t = Test.new
puts "t.value is #{t.value}" # 1
t.value = 2
puts "t.value is #{t.value}" # 2
x = Test.new
puts "x.value is #{x.value}" # 2
a = AnotherTest.new
puts "a.value is #{a.value}" # 2
a.value = 3
puts "a.value is #{a.value}" # 3
puts "t.value is #{t.value}" # 3
puts "x.value is #{x.value}" # 3
You can see that @@shared
is shared between the classes; setting the value in an instance of one changes the value for all other instances of that class and even child classes, where a variable named @shared
, with one @
, would not be.
[Update]
As Phrogz mentions in the comments, it's a common idiom in Ruby to track class-level data with an instance variable on the class itself. This can be a tricky subject to wrap your mind around, and there is plenty of additional reading on the subject, but think about it as modifying the Class
class, but only the instance of the Class
class you're working with. An example:
class Polygon
class << self
attr_accessor :sides
end
end
class Triangle < Polygon
@sides = 3
end
class Rectangle < Polygon
@sides = 4
end
class Square < Rectangle
end
class Hexagon < Polygon
@sides = 6
end
puts "Triangle.sides: #{Triangle.sides.inspect}" # 3
puts "Rectangle.sides: #{Rectangle.sides.inspect}" # 4
puts "Square.sides: #{Square.sides.inspect}" # nil
puts "Hexagon.sides: #{Hexagon.sides.inspect}" # 6
I included the Square
example (which outputs nil
) to demonstrate that this may not behave 100% as you expect; the article I linked above has plenty of additional information on the subject.
Also keep in mind that, as with most data, you should be extremely careful with class variables in a multithreaded environment, as per dmarkow's comment.
It is possible to have static
class variables, but probably not worth the effort.
Here's a proof-of-concept written in Python 3 -- if any of the exact details are wrong the code can be tweaked to match just about whatever you mean by a static variable
:
class Static:
def __init__(self, value, doc=None):
self.deleted = False
self.value = value
self.__doc__ = doc
def __get__(self, inst, cls=None):
if self.deleted:
raise AttributeError('Attribute not set')
return self.value
def __set__(self, inst, value):
self.deleted = False
self.value = value
def __delete__(self, inst):
self.deleted = True
class StaticType(type):
def __delattr__(cls, name):
obj = cls.__dict__.get(name)
if isinstance(obj, Static):
obj.__delete__(name)
else:
super(StaticType, cls).__delattr__(name)
def __getattribute__(cls, *args):
obj = super(StaticType, cls).__getattribute__(*args)
if isinstance(obj, Static):
obj = obj.__get__(cls, cls.__class__)
return obj
def __setattr__(cls, name, val):
# check if object already exists
obj = cls.__dict__.get(name)
if isinstance(obj, Static):
obj.__set__(name, val)
else:
super(StaticType, cls).__setattr__(name, val)
and in use:
class MyStatic(metaclass=StaticType):
"""
Testing static vars
"""
a = Static(9)
b = Static(12)
c = 3
class YourStatic(MyStatic):
d = Static('woo hoo')
e = Static('doo wop')
and some tests:
ms1 = MyStatic()
ms2 = MyStatic()
ms3 = MyStatic()
assert ms1.a == ms2.a == ms3.a == MyStatic.a
assert ms1.b == ms2.b == ms3.b == MyStatic.b
assert ms1.c == ms2.c == ms3.c == MyStatic.c
ms1.a = 77
assert ms1.a == ms2.a == ms3.a == MyStatic.a
ms2.b = 99
assert ms1.b == ms2.b == ms3.b == MyStatic.b
MyStatic.a = 101
assert ms1.a == ms2.a == ms3.a == MyStatic.a
MyStatic.b = 139
assert ms1.b == ms2.b == ms3.b == MyStatic.b
del MyStatic.b
for inst in (ms1, ms2, ms3):
try:
getattr(inst, 'b')
except AttributeError:
pass
else:
print('AttributeError not raised on %r' % attr)
ms1.c = 13
ms2.c = 17
ms3.c = 19
assert ms1.c == 13
assert ms2.c == 17
assert ms3.c == 19
MyStatic.c = 43
assert ms1.c == 13
assert ms2.c == 17
assert ms3.c == 19
ys1 = YourStatic()
ys2 = YourStatic()
ys3 = YourStatic()
MyStatic.b = 'burgler'
assert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a
assert ys1.b == ys2.b == ys3.b == YourStatic.b == MyStatic.b
assert ys1.d == ys2.d == ys3.d == YourStatic.d
assert ys1.e == ys2.e == ys3.e == YourStatic.e
ys1.a = 'blah'
assert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a
ys2.b = 'kelp'
assert ys1.b == ys2.b == ys3.b == YourStatic.b == MyStatic.b
ys1.d = 'fee'
assert ys1.d == ys2.d == ys3.d == YourStatic.d
ys2.e = 'fie'
assert ys1.e == ys2.e == ys3.e == YourStatic.e
MyStatic.a = 'aargh'
assert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a
Down-casting and up-casting was as follows:
Upcasting: When we want to cast a Sub class to Super class, we use Upcasting(or widening). It happens automatically, no need to do anything explicitly.
Downcasting : When we want to cast a Super class to Sub class, we use Downcasting(or narrowing), and Downcasting is not directly possible in Java, explicitly we have to do.
Dog d = new Dog();
Animal a = (Animal) d; //Explicitly you have done upcasting. Actually no need, we can directly type cast like Animal a = d; compiler now treat Dog as Animal but still it is Dog even after upcasting
d.callme();
a.callme(); // It calls Dog's method even though we use Animal reference.
((Dog) a).callme2(); // Downcasting: Compiler does know Animal it is, In order to use Dog methods, we have to do typecast explicitly.
// Internally if it is not a Dog object it throws ClassCastException
Instance variable on a class:
class Parent
@things = []
def self.things
@things
end
def things
self.class.things
end
end
class Child < Parent
@things = []
end
Parent.things << :car
Child.things << :doll
mom = Parent.new
dad = Parent.new
p Parent.things #=> [:car]
p Child.things #=> [:doll]
p mom.things #=> [:car]
p dad.things #=> [:car]
Class variable:
class Parent
@@things = []
def self.things
@@things
end
def things
@@things
end
end
class Child < Parent
end
Parent.things << :car
Child.things << :doll
p Parent.things #=> [:car,:doll]
p Child.things #=> [:car,:doll]
mom = Parent.new
dad = Parent.new
son1 = Child.new
son2 = Child.new
daughter = Child.new
[ mom, dad, son1, son2, daughter ].each{ |person| p person.things }
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
With an instance variable on a class (not on an instance of that class) you can store something common to that class without having sub-classes automatically also get them (and vice-versa). With class variables, you have the convenience of not having to write self.class
from an instance object, and (when desirable) you also get automatic sharing throughout the class hierarchy.
Merging these together into a single example that also covers instance variables on instances:
class Parent
@@family_things = [] # Shared between class and subclasses
@shared_things = [] # Specific to this class
def self.family_things
@@family_things
end
def self.shared_things
@shared_things
end
attr_accessor :my_things
def initialize
@my_things = [] # Just for me
end
def family_things
self.class.family_things
end
def shared_things
self.class.shared_things
end
end
class Child < Parent
@shared_things = []
end
And then in action:
mama = Parent.new
papa = Parent.new
joey = Child.new
suzy = Child.new
Parent.family_things << :house
papa.family_things << :vacuum
mama.shared_things << :car
papa.shared_things << :blender
papa.my_things << :quadcopter
joey.my_things << :bike
suzy.my_things << :doll
joey.shared_things << :puzzle
suzy.shared_things << :blocks
p Parent.family_things #=> [:house, :vacuum]
p Child.family_things #=> [:house, :vacuum]
p papa.family_things #=> [:house, :vacuum]
p mama.family_things #=> [:house, :vacuum]
p joey.family_things #=> [:house, :vacuum]
p suzy.family_things #=> [:house, :vacuum]
p Parent.shared_things #=> [:car, :blender]
p papa.shared_things #=> [:car, :blender]
p mama.shared_things #=> [:car, :blender]
p Child.shared_things #=> [:puzzle, :blocks]
p joey.shared_things #=> [:puzzle, :blocks]
p suzy.shared_things #=> [:puzzle, :blocks]
p papa.my_things #=> [:quadcopter]
p mama.my_things #=> []
p joey.my_things #=> [:bike]
p suzy.my_things #=> [:doll]
A solution would be to declare your key as nvarchar(20)
.
See full query from SHOW PROCESSLIST :
SHOW FULL PROCESSLIST;
Or
SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST;
Your data types are mismatched when you are retrieving the field values. Check your code and ensure that for each field that you are retrieving that the java object matches that type. For example, retrieving a date into and int. If you are doing a select * then it is possible a change in the fields of the table has happened causing this error to occur. Your SQL should only select the fields you specifically want in order to avoid this error.
Hope this helps.
Try this one -
Query:
SELECT
database_name = DB_NAME(database_id)
, log_size_mb = CAST(SUM(CASE WHEN type_desc = 'LOG' THEN size END) * 8. / 1024 AS DECIMAL(8,2))
, row_size_mb = CAST(SUM(CASE WHEN type_desc = 'ROWS' THEN size END) * 8. / 1024 AS DECIMAL(8,2))
, total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))
FROM sys.master_files WITH(NOWAIT)
WHERE database_id = DB_ID() -- for current db
GROUP BY database_id
Output:
-- my query
name log_size_mb row_size_mb total_size_mb
-------------- ------------ ------------- -------------
xxxxxxxxxxx 512.00 302.81 814.81
-- sp_spaceused
database_name database_size unallocated space
---------------- ------------------ ------------------
xxxxxxxxxxx 814.81 MB 13.04 MB
Function:
ALTER FUNCTION [dbo].[GetDBSize]
(
@db_name NVARCHAR(100)
)
RETURNS TABLE
AS
RETURN
SELECT
database_name = DB_NAME(database_id)
, log_size_mb = CAST(SUM(CASE WHEN type_desc = 'LOG' THEN size END) * 8. / 1024 AS DECIMAL(8,2))
, row_size_mb = CAST(SUM(CASE WHEN type_desc = 'ROWS' THEN size END) * 8. / 1024 AS DECIMAL(8,2))
, total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))
FROM sys.master_files WITH(NOWAIT)
WHERE database_id = DB_ID(@db_name)
OR @db_name IS NULL
GROUP BY database_id
UPDATE 2016/01/22:
Show information about size, free space, last database backups
IF OBJECT_ID('tempdb.dbo.#space') IS NOT NULL
DROP TABLE #space
CREATE TABLE #space (
database_id INT PRIMARY KEY
, data_used_size DECIMAL(18,2)
, log_used_size DECIMAL(18,2)
)
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = STUFF((
SELECT '
USE [' + d.name + ']
INSERT INTO #space (database_id, data_used_size, log_used_size)
SELECT
DB_ID()
, SUM(CASE WHEN [type] = 0 THEN space_used END)
, SUM(CASE WHEN [type] = 1 THEN space_used END)
FROM (
SELECT s.[type], space_used = SUM(FILEPROPERTY(s.name, ''SpaceUsed'') * 8. / 1024)
FROM sys.database_files s
GROUP BY s.[type]
) t;'
FROM sys.databases d
WHERE d.[state] = 0
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
EXEC sys.sp_executesql @SQL
SELECT
d.database_id
, d.name
, d.state_desc
, d.recovery_model_desc
, t.total_size
, t.data_size
, s.data_used_size
, t.log_size
, s.log_used_size
, bu.full_last_date
, bu.full_size
, bu.log_last_date
, bu.log_size
FROM (
SELECT
database_id
, log_size = CAST(SUM(CASE WHEN [type] = 1 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
, data_size = CAST(SUM(CASE WHEN [type] = 0 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
, total_size = CAST(SUM(size) * 8. / 1024 AS DECIMAL(18,2))
FROM sys.master_files
GROUP BY database_id
) t
JOIN sys.databases d ON d.database_id = t.database_id
LEFT JOIN #space s ON d.database_id = s.database_id
LEFT JOIN (
SELECT
database_name
, full_last_date = MAX(CASE WHEN [type] = 'D' THEN backup_finish_date END)
, full_size = MAX(CASE WHEN [type] = 'D' THEN backup_size END)
, log_last_date = MAX(CASE WHEN [type] = 'L' THEN backup_finish_date END)
, log_size = MAX(CASE WHEN [type] = 'L' THEN backup_size END)
FROM (
SELECT
s.database_name
, s.[type]
, s.backup_finish_date
, backup_size =
CAST(CASE WHEN s.backup_size = s.compressed_backup_size
THEN s.backup_size
ELSE s.compressed_backup_size
END / 1048576.0 AS DECIMAL(18,2))
, RowNum = ROW_NUMBER() OVER (PARTITION BY s.database_name, s.[type] ORDER BY s.backup_finish_date DESC)
FROM msdb.dbo.backupset s
WHERE s.[type] IN ('D', 'L')
) f
WHERE f.RowNum = 1
GROUP BY f.database_name
) bu ON d.name = bu.database_name
ORDER BY t.total_size DESC
Output:
database_id name state_desc recovery_model_desc total_size data_size data_used_size log_size log_used_size full_last_date full_size log_last_date log_size
----------- -------------------------------- ------------ ------------------- ------------ ----------- --------------- ----------- -------------- ----------------------- ------------ ----------------------- ---------
24 StackOverflow ONLINE SIMPLE 66339.88 65840.00 65102.06 499.88 5.05 NULL NULL NULL NULL
11 AdventureWorks2012 ONLINE SIMPLE 16404.13 15213.00 192.69 1191.13 15.55 2015-11-10 10:51:02.000 44.59 NULL NULL
10 locateme ONLINE SIMPLE 1050.13 591.00 2.94 459.13 6.91 2015-11-06 15:08:34.000 17.25 NULL NULL
8 CL_Documents ONLINE FULL 793.13 334.00 333.69 459.13 12.95 2015-11-06 15:08:31.000 309.22 2015-11-06 13:15:39.000 0.01
1 master ONLINE SIMPLE 554.00 492.06 4.31 61.94 5.20 2015-11-06 15:08:12.000 0.65 NULL NULL
9 Refactoring ONLINE SIMPLE 494.32 366.44 308.88 127.88 34.96 2016-01-05 18:59:10.000 37.53 NULL NULL
3 model ONLINE SIMPLE 349.06 4.06 2.56 345.00 0.97 2015-11-06 15:08:12.000 0.45 NULL NULL
13 sql-format.com ONLINE SIMPLE 216.81 181.38 149.00 35.44 3.06 2015-11-06 15:08:39.000 23.64 NULL NULL
23 users ONLINE FULL 173.25 73.25 3.25 100.00 5.66 2015-11-23 13:15:45.000 0.72 NULL NULL
4 msdb ONLINE SIMPLE 46.44 20.25 19.31 26.19 4.09 2015-11-06 15:08:12.000 2.96 NULL NULL
21 SSISDB ONLINE FULL 45.06 40.00 4.06 5.06 4.84 2014-05-14 18:27:11.000 3.08 NULL NULL
27 tSQLt ONLINE SIMPLE 9.00 5.00 3.06 4.00 0.75 NULL NULL NULL NULL
2 tempdb ONLINE SIMPLE 8.50 8.00 4.50 0.50 1.78 NULL NULL NULL NULL
This worked for me.
mElement.sendKeys(Keys.HOME,Keys.chord(Keys.SHIFT,Keys.END),MY_VALUE);
Since C++17 you can use range-based for loops together with structured bindings for iterating over your map. This improves readability, as you reduce the amount of needed first
and second
members in your code:
std::map<std::string, std::pair<std::string, std::string>> myMap;
myMap["x"] = { "a", "b" };
myMap["y"] = { "c", "d" };
for (const auto &[k, v] : myMap)
std::cout << "m[" << k << "] = (" << v.first << ", " << v.second << ") " << std::endl;
Output:
m[x] = (a, b)
m[y] = (c, d)
Try executing:
ActiveSheet.Calculate
I use it in a worksheet in which control buttons change values of a dataset. On each click, Excel runs through this command and the graph updates immediately.
I had the same issue here. As Magnus said above, for me it was happening due to an SDK update to version 22.0.5.
After performing a full update in my Android SDK (including Google Play Services) and Android plugins in Eclipse, I was able to use play services lib in my application.
Remove warnings.filterwarnings and add:
numpy.seterr(all='raise')
It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.
Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:
SQL> select * from dba_directories;
... and if not, create one
SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
SQL> grant all on directory DATA_PUMP_DIR to myuser; -- DBAs dont need this grant
Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:
$ expdp system/manager schemas=user1 dumpfile=user1.dpdmp
Or specifying a specific directory, add directory=<directory name>
:
C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR
With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:
$ exp system/manager owner=user1 file=user1.dmp
Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.
Example for American UTF8 (UNIX):
$ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8
Windows uses SET, example using Japanese UTF8:
C:\> set NLS_LANG=Japanese_Japan.AL32UTF8
More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624
I have tried everything - but nothing helped. After searching for several hours I found this information:
Apache 2.4.18 for some reason does not load php 7.2 curl. I updated my Apache to 2.4.29 and curl loaded instantly
http://forum.wampserver.com/read.php?2,149346,149348
What should I say: I updated Apache and curl was running like charm
Simply use the following command,
For Export:
mysqldump -u [user] -p [db_name] | gzip > [filename_to_compress.sql.gz]
For Import:
gunzip < [compressed_filename.sql.gz] | mysql -u [user] -p[password] [databasename]
Note: There is no space between the keyword '-p' and your password.
If you're getting this, you may have forgotten to put #include <thread>
at the beginning of your file. OP's signature seems like it should work.
newlist=[] #make an empty list
for i in list: # loop to hv a dict in list
s={} # make an empty dict to store new dict data
for k in i.keys(): # to get keys in the dict of the list
s[k]=int(i[k]) # change the values from string to int by int func
newlist.append(s) # to add the new dict with integer to the list
In my case I had an Activity file imported from Eclipse that had the line:
import android.R;
So all of my R classes were resolving to the SDK, as soon as I commented out that line everything compiled correctly to my package. I only noticed the issue when I was moving the project from my Mac to my Windows machine.
Another possible solution, in case the column has not only strings but numbers too, is to use astype(str).str.lower()
or to_string(na_rep='')
because otherwise, given that a number is not a string, when lowered it will return NaN
, therefore:
import pandas as pd
import numpy as np
df=pd.DataFrame(['ONE','Two', np.nan,2],columns=['x'])
xSecureLower = df['x'].to_string(na_rep='').lower()
xLower = df['x'].str.lower()
then we have:
>>> xSecureLower
0 one
1 two
2
3 2
Name: x, dtype: object
and not
>>> xLower
0 one
1 two
2 NaN
3 NaN
Name: x, dtype: object
edit:
if you don't want to lose the NaNs, then using map will be better, (from @wojciech-walczak, and @cs95 comment) it will look something like this
xSecureLower = df['x'].map(lambda x: x.lower() if isinstance(x,str) else x)
The excellent Pandas library adds features to numpy that make these kinds of operations more intuitive IMO. For example:
import numpy as np
import pandas as pd
# column
df = pd.DataFrame([1,2,3])
# row
df2 = pd.DataFrame([[1,2,3]])
You can even define a DataFrame and make a spreadsheet-like pivot table.
Calculator SOAP service test from SoapUI, Online SoapClient Calculator
Generate the SoapMessage
object form the input SoapEnvelopeXML
and SoapDataXml
.
SoapEnvelopeXML
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
<tem:Add xmlns:tem="http://tempuri.org/">
<tem:intA>3</tem:intA>
<tem:intB>4</tem:intB>
</tem:Add>
</soapenv:Body>
</soapenv:Envelope>
use the following code to get SoapMessage Object.
MessageFactory messageFactory = MessageFactory.newInstance();
MimeHeaders headers = new MimeHeaders();
ByteArrayInputStream xmlByteStream = new ByteArrayInputStream(SoapEnvelopeXML.getBytes());
SOAPMessage soapMsg = messageFactory.createMessage(headers, xmlByteStream);
SoapDataXml
<tem:Add xmlns:tem="http://tempuri.org/">
<tem:intA>3</tem:intA>
<tem:intB>4</tem:intB>
</tem:Add>
use below code to get SoapMessage Object.
public static SOAPMessage getSOAPMessagefromDataXML(String saopBodyXML) throws Exception {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
dbFactory.setIgnoringComments(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource ips = new org.xml.sax.InputSource(new StringReader(saopBodyXML));
Document docBody = dBuilder.parse(ips);
System.out.println("Data Document: "+docBody.getDocumentElement());
MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
SOAPMessage soapMsg = messageFactory.createMessage();
SOAPBody soapBody = soapMsg.getSOAPPart().getEnvelope().getBody();
soapBody.addDocument(docBody);
return soapMsg;
}
By getting the SoapMessage Object. It is clear that the Soap XML is valid. Then prepare to hit the service to get response. It can be done in many ways.
java.net.URL endpointURL = new java.net.URL(endPointUrl);
javax.xml.rpc.Service service = new org.apache.axis.client.Service();
((org.apache.axis.client.Service) service).setTypeMappingVersion("1.2");
CalculatorSoap12Stub obj_axis = new CalculatorSoap12Stub(endpointURL, service);
int add = obj_axis.add(10, 20);
System.out.println("Response: "+ add);
javax.xml.soap.SOAPConnection
.public static void getSOAPConnection(SOAPMessage soapMsg) throws Exception {
System.out.println("===== SOAPConnection =====");
MimeHeaders headers = soapMsg.getMimeHeaders(); // new MimeHeaders();
headers.addHeader("SoapBinding", serverDetails.get("SoapBinding") );
headers.addHeader("MethodName", serverDetails.get("MethodName") );
headers.addHeader("SOAPAction", serverDetails.get("SOAPAction") );
headers.addHeader("Content-Type", serverDetails.get("Content-Type"));
headers.addHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));
if (soapMsg.saveRequired()) {
soapMsg.saveChanges();
}
SOAPConnectionFactory newInstance = SOAPConnectionFactory.newInstance();
javax.xml.soap.SOAPConnection connection = newInstance.createConnection();
SOAPMessage soapMsgResponse = connection.call(soapMsg, getURL( serverDetails.get("SoapServerURI"), 5*1000 ));
getSOAPXMLasString(soapMsgResponse);
}
org.apache.commons.httpclient
.public static void getHttpConnection(SOAPMessage soapMsg) throws SOAPException, IOException {
System.out.println("===== HttpClient =====");
HttpClient httpClient = new HttpClient();
HttpConnectionManagerParams params = httpClient.getHttpConnectionManager().getParams();
params.setConnectionTimeout(3 * 1000); // Connection timed out
params.setSoTimeout(3 * 1000); // Request timed out
params.setParameter("http.useragent", "Web Service Test Client");
PostMethod methodPost = new PostMethod( serverDetails.get("SoapServerURI") );
methodPost.setRequestBody( getSOAPXMLasString(soapMsg) );
methodPost.setRequestHeader("Content-Type", serverDetails.get("Content-Type") );
methodPost.setRequestHeader("SoapBinding", serverDetails.get("SoapBinding") );
methodPost.setRequestHeader("MethodName", serverDetails.get("MethodName") );
methodPost.setRequestHeader("SOAPAction", serverDetails.get("SOAPAction") );
methodPost.setRequestHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));
try {
int returnCode = httpClient.executeMethod(methodPost);
if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
System.out.println("The Post method is not implemented by this URI");
methodPost.getResponseBodyAsString();
} else {
BufferedReader br = new BufferedReader(new InputStreamReader(methodPost.getResponseBodyAsStream()));
String readLine;
while (((readLine = br.readLine()) != null)) {
System.out.println(readLine);
}
br.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
methodPost.releaseConnection();
}
}
public static void accessResource_AppachePOST(SOAPMessage soapMsg) throws Exception {
System.out.println("===== HttpClientBuilder =====");
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
URIBuilder builder = new URIBuilder( serverDetails.get("SoapServerURI") );
HttpPost methodPost = new HttpPost(builder.build());
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(5 * 1000)
.setConnectionRequestTimeout(5 * 1000)
.setSocketTimeout(5 * 1000)
.build();
methodPost.setConfig(config);
HttpEntity xmlEntity = new StringEntity(getSOAPXMLasString(soapMsg), "utf-8");
methodPost.setEntity(xmlEntity);
methodPost.setHeader("Content-Type", serverDetails.get("Content-Type"));
methodPost.setHeader("SoapBinding", serverDetails.get("SoapBinding") );
methodPost.setHeader("MethodName", serverDetails.get("MethodName") );
methodPost.setHeader("SOAPAction", serverDetails.get("SOAPAction") );
methodPost.setHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));
// Create a custom response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse( final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status <= 500) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
return "";
}
};
String execute = httpClient.execute( methodPost, responseHandler );
System.out.println("AppachePOST : "+execute);
}
Full Example:
public class SOAP_Calculator {
static HashMap<String, String> serverDetails = new HashMap<>();
static {
// Calculator
serverDetails.put("SoapServerURI", "http://www.dneonline.com/calculator.asmx");
serverDetails.put("SoapWSDL", "http://www.dneonline.com/calculator.asmx?wsdl");
serverDetails.put("SoapBinding", "CalculatorSoap"); // <wsdl:binding name="CalculatorSoap12" type="tns:CalculatorSoap">
serverDetails.put("MethodName", "Add"); // <wsdl:operation name="Add">
serverDetails.put("SOAPAction", "http://tempuri.org/Add"); // <soap12:operation soapAction="http://tempuri.org/Add" style="document"/>
serverDetails.put("SoapXML", "<tem:Add xmlns:tem=\"http://tempuri.org/\"><tem:intA>2</tem:intA><tem:intB>4</tem:intB></tem:Add>");
serverDetails.put("Accept-Encoding", "gzip,deflate");
serverDetails.put("Content-Type", "");
}
public static void callSoapService( ) throws Exception {
String xmlData = serverDetails.get("SoapXML");
SOAPMessage soapMsg = getSOAPMessagefromDataXML(xmlData);
System.out.println("Requesting SOAP Message:\n"+ getSOAPXMLasString(soapMsg) +"\n");
SOAPEnvelope envelope = soapMsg.getSOAPPart().getEnvelope();
if (envelope.getElementQName().getNamespaceURI().equals("http://schemas.xmlsoap.org/soap/envelope/")) {
System.out.println("SOAP 1.1 NamespaceURI: http://schemas.xmlsoap.org/soap/envelope/");
serverDetails.put("Content-Type", "text/xml; charset=utf-8");
} else {
System.out.println("SOAP 1.2 NamespaceURI: http://www.w3.org/2003/05/soap-envelope");
serverDetails.put("Content-Type", "application/soap+xml; charset=utf-8");
}
getHttpConnection(soapMsg);
getSOAPConnection(soapMsg);
accessResource_AppachePOST(soapMsg);
}
public static void main(String[] args) throws Exception {
callSoapService();
}
private static URL getURL(String endPointUrl, final int timeOutinSeconds) throws MalformedURLException {
URL endpoint = new URL(null, endPointUrl, new URLStreamHandler() {
protected URLConnection openConnection(URL url) throws IOException {
URL clone = new URL(url.toString());
URLConnection connection = clone.openConnection();
connection.setConnectTimeout(timeOutinSeconds);
connection.setReadTimeout(timeOutinSeconds);
//connection.addRequestProperty("Developer-Mood", "Happy"); // Custom header
return connection;
}
});
return endpoint;
}
public static String getSOAPXMLasString(SOAPMessage soapMsg) throws SOAPException, IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
soapMsg.writeTo(out);
// soapMsg.writeTo(System.out);
String strMsg = new String(out.toByteArray());
System.out.println("Soap XML: "+ strMsg);
return strMsg;
}
}
@See list of some WebServices at http://sofa.uqam.ca/soda/webservices.php
You're close. A really simple solution is just to get the length from the 'run' objects returned. No need to bother with 'load' or 'loads':
len(data['result'][0]['run'])
Go to apache-tomcat\conf folder add these lines in
tomcat-users.xml file
<role rolename="manager-gui"/>
<user username="admin" password="admin" roles="manager-gui"/>
and restart server
I chose @nrodic's answer (thanks, by the way), but it has several drawbacks:
1) If you have rows containing "cat", "dog", "mouse", "cat dog", "cat dog mouse" (each on separate row), then when you search explicitly for "cat dog mouse", you'll be displayed "cat", "dog", "mouse", "cat dog", "cat dog mouse" rows.
2) .toLowerCase() was not implemented, that is, when you enter lower case string, rows with matching upper case text will not be showed.
So I came up with a fork of @nrodic's code, where
var data = this.value; //plain text, not an array
and
jo.filter(function (i, v) {
var $t = $(this);
var stringsFromRowNodes = $t.children("td:nth-child(n)")
.text().toLowerCase();
var searchText = data.toLowerCase();
if (stringsFromRowNodes.contains(searchText)) {
return true;
}
return false;
})
//show the rows that match.
.show();
Here goes the full code: http://jsfiddle.net/jumasheff/081qyf3s/
setTimout on 0 is also very useful in the pattern of setting up a deferred promise, which you want to return right away:
myObject.prototype.myMethodDeferred = function() {
var deferredObject = $.Deferred();
var that = this; // Because setTimeout won't work right with this
setTimeout(function() {
return myMethodActualWork.call(that, deferredObject);
}, 0);
return deferredObject.promise();
}
In Swift 3 / iOS 10+ this now looks like
if let url = URL(string: "App-Prefs:root=LOCATION_SERVICES") {
UIApplication.shared.open(url, completionHandler: .none)
}
MultiProgramming - In a multiprogramming system, there are more than one programs loaded in main memory which are ready to execute. Only one program at a time is able to get the CPU for executing its instructions while all others are waiting their turn. The main idea of multiprogramming is to maximize the use of CPU time. Suppose currently running process is performing an I/O task, then OS may interrupt that process and give the control to one of the other in - main memory programs that are ready to execute (i.e. process context switching). In this way, no CPU time is wasted by system waiting for the I/O task to be completed.
MultiProcessing - Multiprocessing is the ability of an operating system to execute more than one process simultaneously on a multi processor machine. In multiprocessing system, a computer uses more than one CPU at a tme.
Multitasking - Multitasking is the ability of an operating system to execute more than one task simultaneously on single processor machine, these multiple tasks share common resources such as CPU and memory. In multitasking system, CPU switches from one task to next task so quickly that appears as all tasks are executing at the same time.
There are differences between multitasking and multiprogramming. A task in a multitasking system is not whole application program but it can refres to a "thread of execution" when one process is divided into sub-tasks. Each smaller task does not hijack the CPU until it finishes, they share a small amount of the CPU time called Quantum. Multiprogramming and multitasking operating systems are time sharing systems.
Multithreading - Multithreading is the extension of multitasking. Multithreading is the ability of an operating system to subdivide the specific operation within a single application into individual threads. Each of these threads can run in parallel. The OS divides processing time not only among different applications but also among each thread within an application.
C# compiler is a two phase compiler. In the first phase it just checks namespaces, class hierarchies, Method signatures etc. Method bodies are compiled only during the second phase.
Anonymous types are not determined until the method body is compiled.
So the compiler has no way of determining the return type of the method during the first phase.
That is the reason why anonymous types can not be used as return type.
As others have suggested if you are using .net 4.0 or grater, you can use Dynamic
.
If I were you I would probably create a type and return that type from the method. That way it is easy for the future programmers who maintains your code and more readable.
A 'fun' way to learn socket.io is to play BrowserQuest by mozilla and look at its source code :-)
JFrame
is the window; it can have one or more JPanel
instances inside it. JPanel
is not the window.
You need a Swing tutorial:
Try
yum list installed | grep reponame
On one of my servers:
yum list installed | grep remi ImageMagick2.x86_64 6.6.5.10-1.el5.remi installed memcache.x86_64 1.4.5-2.el5.remi installed mysql.x86_64 5.1.54-1.el5.remi installed mysql-devel.x86_64 5.1.54-1.el5.remi installed mysql-libs.x86_64 5.1.54-1.el5.remi installed mysql-server.x86_64 5.1.54-1.el5.remi installed mysqlclient15.x86_64 5.0.67-1.el5.remi installed php.x86_64 5.3.5-1.el5.remi installed php-cli.x86_64 5.3.5-1.el5.remi installed php-common.x86_64 5.3.5-1.el5.remi installed php-domxml-php4-php5.noarch 1.21.2-1.el5.remi installed php-fpm.x86_64 5.3.5-1.el5.remi installed php-gd.x86_64 5.3.5-1.el5.remi installed php-mbstring.x86_64 5.3.5-1.el5.remi installed php-mcrypt.x86_64 5.3.5-1.el5.remi installed php-mysql.x86_64 5.3.5-1.el5.remi installed php-pdo.x86_64 5.3.5-1.el5.remi installed php-pear.noarch 1:1.9.1-6.el5.remi installed php-pecl-apc.x86_64 3.1.6-1.el5.remi installed php-pecl-imagick.x86_64 3.0.1-1.el5.remi.1 installed php-pecl-memcache.x86_64 3.0.5-1.el5.remi installed php-pecl-xdebug.x86_64 2.1.0-1.el5.remi installed php-soap.x86_64 5.3.5-1.el5.remi installed php-xml.x86_64 5.3.5-1.el5.remi installed remi-release.noarch 5-8.el5.remi installed
It works.
If you want to enable CORS without using filters or without config file just add
@CrossOrigin
to the top of your controller and it work.
The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.
The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.
Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.
Lombok does not support that also indicated by making any @Value
annotated class final
(as you know by using @NonFinal
).
The only workaround I found is to declare all members final yourself and use the @Data
annotation instead. Those subclasses need to be annotated by @EqualsAndHashCode
and need an explicit all args constructor as Lombok doesn't know how to create one using the all args one of the super class:
@Data
public class A {
private final int x;
private final int y;
}
@Data
@EqualsAndHashCode(callSuper = true)
public class B extends A {
private final int z;
public B(int x, int y, int z) {
super(x, y);
this.z = z;
}
}
Especially the constructors of the subclasses make the solution a little untidy for superclasses with many members, sorry.
On Selenium >= 3.41 (C#) the rigth syntax is:
webDriver = webDriver.SwitchTo().Frame(webDriver.FindElement(By.Name("icontent")));
How to setup and run a Rails 4 app in Production mode (step-by-step) using Apache and Phusion Passenger:
Normally you would be able to enter your Rails project, rails s
, and get a development version of your app at http://something.com:3000. Production mode is a little trickier to configure.
I've been messing around with this for a while, so I figured I'd write this up for the newbies (such as myself). There are a few little tweaks which are spread throughout the internet and figured this might be easier.
Refer to this guide for core setup of the server (CentOS 6, but it should apply to nearly all Linux flavors): https://www.digitalocean.com/community/tutorials/how-to-setup-a-rails-4-app-with-apache-and-passenger-on-centos-6
Make absolute certain that after Passenger is set up you've edited the /etc/httpd/conf/httpd.conf
file to reflect your directory structure. You want to point DocumentRoot to your Rails project /public folder Anywhere in the httpd.conf
file that has this sort of dir: /var/www/html/your_application/public
needs to be updated or everything will get very frustrating. I cannot stress this enough.
Reboot the server (or Apache at the very least - service httpd restart
)
Enter your Rails project folder /var/www/html/your_application
and start the migration with rake db:migrate
. Make certain that a database table exists, even if you plan on adding tables later (this is also part of step 1).
RAILS_ENV=production rake secret
- this will create a secret_key that you can add to config/secrets.yml
. You can copy/paste this into config/secrets.yml for the sake of getting things running, although I'd recommend you don't do this. Personally, I do this step to make sure everything else is working, then change it back and source it later.
RAILS_ENV=production rake db:migrate
RAILS_ENV=production rake assets:precompile
if you are serving static assets. This will push js, css, image files into the /public
folder.
RAILS_ENV=production rails s
At this point your app should be available at http://something.com/whatever
instead of :3000
. If not, passenger-memory-stats
and see if there an entry like 908 469.7 MB 90.9 MB Passenger RackApp: /var/www/html/projectname
I've probably missed something heinous, but this has worked for me in the past.
Use $.on()
to bind your chosen event to the input, don't use the shortcuts like $.keydown()
etc because as of jQuery 1.7 $.on()
is the preferred method to attach event handlers (see here: http://api.jquery.com/on/ and http://api.jquery.com/bind/).
$.keydown()
is just a shortcut to $.bind('keydown')
, and $.bind()
is what $.on()
replaces (among others).
To answer your question, as far as I'm aware, unless you need to fire an event on keydown
specifically, the change
event should do the trick for you.
$('element').on('change', function(){
console.log('change');
});
To respond to the below comment, the javascript change
event is documented here: https://developer.mozilla.org/en-US/docs/Web/Events/change
And here is a working example of the change
event working on an input element, using jQuery: http://jsfiddle.net/p1m4xh08/
The exception you get is telling you filedialog
is not in your namespace.
filedialog
(and btw messagebox
) is a tkinter module, so it is not imported just with from tkinter import *
>>> from tkinter import *
>>> filedialog
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'filedialog' is not defined
>>>
you should use for example:
>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>
>>>
or
>>> import tkinter.filedialog as fdialog
or
>>> from tkinter.filedialog import askopenfilename
So this would do for your browse button:
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
class MyFrame(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("Example")
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=10)
self.button.grid(row=1, column=0, sticky=W)
def load_file(self):
fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
("HTML files", "*.html;*.htm"),
("All files", "*.*") ))
if fname:
try:
print("""here it comes: self.settings["template"].set(fname)""")
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return
if __name__ == "__main__":
MyFrame().mainloop()
Just remove the slash after Data
and prepend the root:
<xsl:variable name="myVarA" select="/root/DataSet/Data[@Value1='2']/@Value2"/>
Sparrow Chart Toolkit a best opensource chart control for multiple platforms
-WPF
-Silverlight
-WinRT
-Windows phone
-Windows Forms
-Mono
You can find the basedir (and within maybe your my.cnf) if you do the following query in your mysql-Client (e.g. phpmyadmin)
SHOW VARIABLES
It looks like you are calling next even if the scanner no longer has a next element to provide... throwing the exception.
while(!file.next().equals(treasure)){
file.next();
}
Should be something like
boolean foundTreasure = false;
while(file.hasNext()){
if(file.next().equals(treasure)){
foundTreasure = true;
break; // found treasure, if you need to use it, assign to variable beforehand
}
}
// out here, either we never found treasure at all, or the last element we looked as was treasure... act accordingly
The container-selinux
package is available from the rhel-7-server-extras-rpms
channel. You can enable it using:
subscription-manager repos --enable=rhel-7-server-extras-rpms
Sources for the package have been exported to git.centos.org
, too, so you could rebuild it yourself using mock
:
(This is not a programming question, so you should use one of the other sites.)
Use chown
to change ownership and chmod
to change rights.
use the -R
option to apply the rights for all files inside of a directory too.
Note that both these commands just work for directories too. The -R
option makes them also change the permissions for all files and directories inside of the directory.
For example
sudo chown -R username:group directory
will change ownership (both user and group) of all files and directories inside of directory and directory itself.
sudo chown username:group directory
will only change the permission of the folder directory but will leave the files and folders inside the directory alone.
you need to use sudo to change the ownership from root to yourself.
Edit:
Note that if you use chown user: file
(Note the left-out group), it will use the default group for that user.
Also You can change the group ownership of a file or directory with the command:
chgrp group_name file/directory_name
You must be a member of the group to which you are changing ownership to.
You can find group of file as follows
# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file
# chown sujit:friends file
User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.
What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.
But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.
Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.
In a php section before the HTML section, use sprinf() to create a constant string from the variables:
$mystuff = sprinf("My name is %s and my mother's name is %s","Suzy","Caroline");
Then in the HTML section you can do whatever you like, such as:
<p>$mystuff</p>
I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:
<select [(ngModel)]="simpleValue"> // value is a string or number
<option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>
If you want to match on the actual object, I'd do it like this:
<select [(ngModel)]="objValue"> // value is an object
<option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>
Using a typedef
avoids having to write struct
every time you declare a variable of that type:
struct elem
{
int i;
char k;
};
elem user; // compile error!
struct elem user; // this is correct
After the long time research i have found the solution for above:
Firstly you change the wp-config.php> Database DB_CHARSET default to "utf8"
Click the "Export" tab for the database
Click the "Custom" radio button
Go the section titled "Format-specific options" and change the dropdown for "Database system or older MySQL server to maximize output compatibility with:" from NONE to MYSQL40.
Scroll to the bottom and click go
Then you are on.
To the best of my knowledge, JavaScript's objects are garbage collected periodically when there are no references remaining to the object. It is something that happens automatically, but if you want to see more about how it works, at the C++ level, it makes sense to take a look at the WebKit or V8 source code
Typically you don't need to think about it, however, in older browsers, like IE 5.5 and early versions of IE 6, and perhaps current versions, closures would create circular references that when unchecked would end up eating up memory. In the particular case that I mean about closures, it was when you added a JavaScript reference to a dom object, and an object to a DOM object that referred back to the JavaScript object. Basically it could never be collected, and would eventually cause the OS to become unstable in test apps that looped to create crashes. In practice these leaks are usually small, but to keep your code clean you should delete the JavaScript reference to the DOM object.
Usually it is a good idea to use the delete keyword to immediately de-reference big objects like JSON data that you have received back and done whatever you need to do with it, especially in mobile web development. This causes the next sweep of the GC to remove that object and free its memory.
If you have many factor variables, you can use select_if
funtion.
install the dplyr packages. There are many function that separates data by satisfying a condition. you can set the conditions.
Use like this.
categorical<-select_if(df,is.factor)
str(categorical)
System.out.print(a + "" + b + "" + c);
From so many answers in this website I didn't find out a clear answer so in 5-10 minutes I figured it out the answer myself. But this can be done in two cases:
So, let's assume we search for the substring "cd" in the string "abcde", and we use the simplest substr built-in function in C++
for 1:
#include <iostream>
#include <string>
using namespace std;
int i;
int main()
{
string a = "abcde";
string b = a.substr(2,2); // 2 will be c. Why? because we start counting from 0 in a string, not from 1.
cout << "substring of a is: " << b << endl;
return 0;
}
for 2:
#include <iostream>
#include <string>
using namespace std;
int i;
int main()
{
string a = "abcde";
for (i=0;i<a.length(); i++)
{
if (a.substr(i,2) == "cd")
{
cout << "substring of a is: " << a.substr(i,2) << endl; // i will iterate from 0 to 5 and will display the substring only when the condition is fullfilled
}
}
return 0;
}
Got this same error recently in a python app using requests on ubuntu 14.04LTS, that I thought had been running fine (maybe it was and some update occurred). Doing the steps below fixed it for me:
pip install --upgrade setuptools
pip install -U requests[security]
Here is a reference: https://stackoverflow.com/a/39580231/996117
Before teaching yourself Spring and Struts, you should probably learn Java. Output like this
org.classes.database.Employee@d9b02
is the result of the Object#toString()
method which all objects inherit from the Object
class, the superclass of all classes in Java.
The List
sub classes implement this by iterating over all the elements and calling toString()
on those. It seems, however, that you haven't implemented (overriden) the method in your Employee
class.
Your JSTL here
<c:forEach items="${eList}" var="employee">
<tr>
<td>Employee ID: <c:out value="${employee.eid}"/></td>
<td>Employee Pass: <c:out value="${employee.ename}"/></td>
</tr>
</c:forEach>
is fine except for the fact that you don't have a page, request, session, or application scoped attribute named eList
.
You need to add it
<% List eList = (List)session.getAttribute("empList");
request.setAttribute("eList", eList);
%>
Or use the attribute empList
in the forEach
.
<c:forEach items="${empList}" var="employee">
<tr>
<td>Employee ID: <c:out value="${employee.eid}"/></td>
<td>Employee Pass: <c:out value="${employee.ename}"/></td>
</tr>
</c:forEach>
I need to run the Postgres database and created an alias for the purpose. The work through is provided below:
$ nano ~/.bash_profile
# in the bash_profile, insert the following texts:
alias pgst="pg_ctl -D /usr/local/var/postgres start"
alias pgsp="pg_ctl -D /usr/local/var/postgres stop"
$ source ~/.bash_profile
### This will start the Postgres server
$ pgst
### This will stop the Postgres server
$ pgsp
Slight change to @rejesh-yadav wonderful answer.
html2canvas now returns a promise.
html2canvas(document.body).then(function (canvas) {
var img = canvas.toDataURL("image/png");
var doc = new jsPDF();
doc.addImage(img, 'JPEG', 10, 10);
doc.save('test.pdf');
});
Hope this helps some!
@echo off
:start
set /p var1="Enter first number: "
pause
Unless you are using Bytecode Enhancement, you cannot fetch lazily the parent-side @OneToOne
association.
However, most often, you don't even need the parent-side association if you use @MapsId
on the client side:
@Entity(name = "PostDetails")
@Table(name = "post_details")
public class PostDetails {
@Id
private Long id;
@Column(name = "created_on")
private Date createdOn;
@Column(name = "created_by")
private String createdBy;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
private Post post;
public PostDetails() {}
public PostDetails(String createdBy) {
createdOn = new Date();
this.createdBy = createdBy;
}
//Getters and setters omitted for brevity
}
With @MapsId
, the id
property in the child table serves as both Primary Key and Foreign Key to the parent table Primary Key.
So, if you have a reference to the parent Post
entity, you can easily fetch the child entity using the parent entity identifier:
PostDetails details = entityManager.find(
PostDetails.class,
post.getId()
);
This way, you won't have N+1 query issues that could be caused by the mappedBy
@OneToOne
association on the parent side.
Decode and save image as PNG
header('content-type: image/png');
ob_start();
$ret = fopen($fullurl, 'r', true, $context);
$contents = stream_get_contents($ret);
$base64 = 'data:image/PNG;base64,' . base64_encode($contents);
echo "<img src=$base64 />" ;
ob_end_flush();
perl -ne 'print if (/begin pattern/../end pattern/)' filename
In my experience moving from MATLAB to Python is an easier transition - Python with numpy/scipy is closer to MATLAB in terms of style and features than R. There are also open source direct MATLAB clones Octave and Scilab.
There is certainly much that MATLAB can do that R can't - in my area MATLAB is used a lot for real time data aquisition - most hardware companies include MATLAB interfaces. While this may be possible with R I imagine it would be a lot more involved. Also Simulink provides a whole area of functionality which I think is missing from R. I'm sure there is more but I'm not so familiar with R.
I've created an eclipse plugin for this, because I had the same problem. Feel free to download it and contribute to it.
It's still in early development, but it does its job already for me.
I had the same issue, but was quite easy to solve. Follow the next steps:
1) In the Virtual Machine (VMWare) settings:
2) Add the device into the list of allowed development devices in your Apple Developer's account. Without that step there is no way to use your device in Xcode.
Next some instructions: Register a single device
You have to be clear on what you mean by "JSON".
Some people use the term JSON incorrectly to refer to a plain old JavaScript object, such as [{a: 1}]
. This one happens to be an array. If you want to add a new element to the array, just push
it, as in
var arr = [{a: 1}];
arr.push({b: 2});
< [{a: 1}, {b: 2}]
The word JSON may also be used to refer to a string which is encoded in JSON format:
var json = '[{"a": 1}]';
Note the (single) quotation marks indicating that this is a string. If you have such a string that you obtained from somewhere, you need to first parse it into a JavaScript object, using JSON.parse
:
var obj = JSON.parse(json);
Now you can manipulate the object any way you want, including push
as shown above. If you then want to put it back into a JSON string, then you use JSON.stringify
:
var new_json = JSON.stringify(obj.push({b: 2}));
'[{"a": 1}, {"b": 1}]'
JSON is also used as a common way to format data for transmission of data to and from a server, where it can be saved (persisted). This is where ajax comes in. Ajax is used both to obtain data, often in JSON format, from a server, and/or to send data in JSON format up to to the server. If you received a response from an ajax request which is JSON format, you may need to JSON.parse
it as described above. Then you can manipulate the object, put it back into JSON format with JSON.stringify
, and use another ajax call to send the data to the server for storage or other manipulation.
You use the term "JSON file". Normally, the word "file" is used to refer to a physical file on some device (not a string you are dealing with in your code, or a JavaScript object). The browser has no access to physical files on your machine. It cannot read or write them. Actually, the browser does not even really have the notion of a "file". Thus, you cannot just read or write some JSON file on your local machine. If you are sending JSON to and from a server, then of course, the server might be storing the JSON as a file, but more likely the server would be constructing the JSON based on some ajax request, based on data it retrieves from a database, or decoding the JSON in some ajax request, and then storing the relevant data back into its database.
Do you really have a "JSON file", and if so, where does it exist and where did you get it from? Do you have a JSON-format string, that you need to parse, mainpulate, and turn back into a new JSON-format string? Do you need to get JSON from the server, and modify it and then send it back to the server? Or is your "JSON file" actually just a JavaScript object, that you simply need to manipulate with normal JavaScript logic?
$('.reset').on('click',function(){
$('#upload input, #upload select').each(
function(index){
var input = $(this);
if(input.attr('type')=='text'){
document.getElementById(input.attr('id')).value = null;
}else if(input.attr('type')=='checkbox'){
document.getElementById(input.attr('id')).checked = false;
}else if(input.attr('type')=='radio'){
document.getElementById(input.attr('id')).checked = false;
}else{
document.getElementById(input.attr('id')).value = '';
//alert('Type: ' + input.attr('type') + ' -Name: ' + input.attr('name') + ' -Value: ' + input.val());
}
}
);
});
Try this:
concat(left(datefield,10),left(timefield,8))
10 char on date field based on full date yyyy-MM-dd
.
8 char on time field based on full time hh:mm:ss
.
It depends on the format you want it. normally you can use script above and you can concat another field or string as you want it.
Because actually date and time field tread as string if you read it. But of course you will got error while update or insert it.
In order for a percentage value to work for height, the parent's height must be determined. The only exception is the root element <html>
, which can be a percentage height. .
So, you've given all of your elements height, except for the <html>
, so what you should do is add this:
html {
height: 100%;
}
And your code should work fine.
* { padding: 0; margin: 0; }_x000D_
html, body, #fullheight {_x000D_
min-height: 100% !important;_x000D_
height: 100%;_x000D_
}_x000D_
#fullheight {_x000D_
width: 250px;_x000D_
background: blue;_x000D_
}
_x000D_
<div id=fullheight>_x000D_
Lorem Ipsum _x000D_
</div>
_x000D_
in c language: #define
(e.g. #define counter 100)
in assembly language: equ (e.g. counter equ 100)
in c# language: according to msdn refrence:
You use #define
to define a symbol. When you use the symbol as the expression that's passed to the #if
directive, the expression will evaluate to true, as the following example shows:
# define DEBUG
The #define
directive cannot be used to declare constant values as is typically done in C and C++. Constants in C# are best defined as static members of a class or struct. If you have several such constants, consider creating a separate "Constants" class to hold them.
I found the similar problem and found the solution and i have blogged about how to upload the file using JSP , In that example i have used the absolute path. Note that if you want to route to some other URL based location you can put a ESB like WSO2 ESB
"In python do you generally use PEP 8 -- Style Guide for Python Code as your coding standards/guidelines? Are there any other formalized standards that you prefer?"
As mentioned by you follow PEP 8 for the main text, and PEP 257 for docstring conventions
Along with Python Style Guides, I suggest that you refer the following:
In addtion to align-self
you can also consider auto margin which will do almost the same thing
.container {_x000D_
background: red;_x000D_
height: 200px;_x000D_
flex-direction: column;_x000D_
padding: 10px;_x000D_
display: flex;_x000D_
}_x000D_
a {_x000D_
margin-right:auto;_x000D_
padding: 10px 40px;_x000D_
background: pink;_x000D_
}
_x000D_
<div class="container">_x000D_
<a href="#">Test</a>_x000D_
</div>
_x000D_
<script type="text/javascript" src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script> <script type="text/javascript"> $(document).ready(function() { function myDate(){ var now = new Date(); var outHour = now.getHours(); if (outHour >12){newHour = outHour-12;outHour = newHour;} if(outHour<10){document.getElementById('HourDiv').innerHTML="0"+outHour;} else{document.getElementById('HourDiv').innerHTML=outHour;} var outMin = now.getMinutes(); if(outMin<10){document.getElementById('MinutDiv').innerHTML="0"+outMin;} else{document.getElementById('MinutDiv').innerHTML=outMin;} var outSec = now.getSeconds(); if(outSec<10){document.getElementById('SecDiv').innerHTML="0"+outSec;} else{document.getElementById('SecDiv').innerHTML=outSec;}} myDate(); setInterval(function(){ myDate();}, 1000); }); </script> <style> body {font-family:"Comic Sans MS", cursive;} h1 {text-align:center;background: gray;color:#fff;padding:5px;padding-bottom:10px;} #Content {margin:0 auto;border:solid 1px gray;width:140px;display:table;background:gray;} #HourDiv, #MinutDiv, #SecDiv {float:left;color:#fff;width:40px;text-align:center;font-size:25px;} span {float:left;color:#fff;font-size:25px;} </style> <div id="clockDiv"></div> <h1>My jQery Clock</h1> <div id="Content"> <div id="HourDiv"></div><span>:</span><div id="MinutDiv"></div><span>:</span><div id="SecDiv"></div> </div>
You need to check your statement like this :
string url = "www.example.com/aaa/bbb.jpg";
string lenght = url.Lenght-4;
if(url.Lenght > 15)//eg 15
{
string newString = url.Substring(18, lenght);
}
int *pointer[280];
//Creates 280 pointers of type int.
In 32 bit os, 4 bytes for each pointer. so 4 * 280 = 1120 bytes.
int (*pointer)[100][280];
// Creates only one pointer which is used to point an array of [100][280] ints.
Here only 4 bytes.
Coming to your question, int (*pointer)[280];
and int (*pointer)[100][280];
are different though it points to same 2D array of [100][280].
Because if int (*pointer)[280];
is incremented, then it will points to next 1D array, but where as int (*pointer)[100][280];
crosses the whole 2D array and points to next byte. Accessing that byte may cause problem if that memory doen't belongs to your process.
If you need permissions, you cannot use 'pip' with 'sudo'. You can do a trick, so that you can use 'sudo' and install package. Just place 'sudo python -m ...' in front of your pip command.
sudo python -m pip install --user -r package_name
You are checking it the array index contains a string "undefined"
, you should either use the typeof
operator:
typeof predQuery[preId] == 'undefined'
Or use the undefined
global property:
predQuery[preId] === undefined
The first way is safer, because the undefined
global property is writable, and it can be changed to any other value.
I got a text file originally generated on a Windows Machine by way of a Mac user and needed to import it into a Linux MySQL DB using the load data
command.
Although VIM displayed the '^M' character, none of the above worked for my particular problem, the data would import but was always corrupted in some way. The solution was pretty easy in the end (after much frustration).
Solution:
Executing dos2unix
TWICE on the same file did the trick! Using the file
command shows what is happening along the way.
$ file 'file.txt'
file.txt: ASCII text, with CRLF, CR line terminators
$ dos2unix 'file.txt'
dos2unix: converting file file.txt to UNIX format ...
$ file 'file.txt'
file.txt: ASCII text, with CRLF line terminators
$ dos2unix 'file.txt'
dos2unix: converting file file.txt to UNIX format ...
$ file 'file.txt'
file.txt: ASCII text
And the final version of the file imported perfectly into the database.
I know its late, but I recently had this requirement and came up with the below code. I don't have a choice to use User defined function. Hope this helps.
SELECT
SUBSTRING(
SUBSTRING('Hello John Smith' ,0,CHARINDEX(' ','Hello John Smith',CHARINDEX(' ','Hello John Smith')+1)
),CHARINDEX(' ','Hello John Smith'),LEN('Hello John Smith')
)
Just make rdg2.nPhoneNumber varchar everywhere instead of int !
Using date()
and strtotime()
from the docs.
$date = "2012-01-05";
$year = date('Y', strtotime($date));
$month = date('F', strtotime($date));
echo $month
Learn them and slowly you'll be able to reconize and figure out when to use them. Start with something simple as the singleton pattern :)
if you want to create one instance of an object and just ONE. You use the singleton pattern. Let's say you're making a program with an options object. You don't want several of those, that would be silly. Singleton makes sure that there will never be more than one. Singleton pattern is simple, used a lot, and really effective.
I would suggest that you use a dictionary like so:
arr = {}
arr[1] = (1, 2, 4)
arr[18] = (3, 4, 5)
print(arr[1])
>>> (1, 2, 4)
If you're not sure an entry is defined in the dictionary, you'll need a validation mechanism when calling "arr[x]", e.g. try-except.
It is globally method for rounded border of UIButton
class func setRoundedBorderButton(btn:UIButton)
{
btn.layer.cornerRadius = btn.frame.size.height/2
btn.layer.borderWidth = 0.5
btn.layer.borderColor = UIColor.darkGray.cgColor
}
The current v2
registry now supports deleting via DELETE /v2/<name>/manifests/<reference>
See: https://github.com/docker/distribution/blob/master/docs/spec/api.md#deleting-an-image
Working usage: https://github.com/byrnedo/docker-reg-tool
Edit:
The manifest <reference>
above can be retrieved from requesting to
GET /v2/<name>/manifests/<tag>
and checking the Docker-Content-Digest
header in the response.
Edit 2: You may have to run your registry with the following env set:
REGISTRY_STORAGE_DELETE_ENABLED="true"
Edit3: You may have to run garbage collection to free this disk space: https://docs.docker.com/registry/garbage-collection/
I also designed a "php session value setter" solution by myself (similar to Luke Dennis' solution. No big deal here), but after setting my session value, my needs were "jumping onto another .php file". Ok, I did it, inside my jquery code... But something didn't quite work...
My problem was kind of easy:
-After you "$.post" your values onto the small .php file, you should wait for some "success/failure" return value, and ONLY AFTER READING THIS SUCCESS VALUE, perform the jump. If you just immediately jump onto the next big .php file, your session value might have not become set onto the php sessions runtime engine, and will you probably read "empty" when doing $_SESSION["my_var"]; from the destination .php file.
In my case, to correct that situation, I changed my jQuery $.post code this way:
$.post('set_session_value.php', { key: 'keyname', value: 'myvalue'}, function(ret){
if(ret==0){
window.alert("success!");
location.replace("next_page.php");
}
else{
window.alert("error!");
}
});
Of course, your "set_session_value.php" file, should return 'echo "0"; ' or 'echo "1"; ' (or whatever success values you might need).
Greetings.
----------------WARM server.
step 1: go to cmd go to directory C:\wamp\bin\mysql\mysql5.6.17 hold Shift + right click (choose "open command window here")
step 2: C:\wamp\bin\mysql\mysql5.6.17\bin>mysql -u root -p SellProduct < D:\file.sql
in this case
+ Root is username database
+ SellProduct is name database.
+ D:\file.sql is file you want to import
---------------It's work with me -------------------
The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).
WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.
For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:
ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.
Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.
In the scenarios listed below you should go for WCF:
WEB API is a framework for developing RESTful/HTTP services.
There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.
HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.
Use document.title
:
console.log(document.title)
_x000D_
<title>Title test</title>
_x000D_
Not possible in just grep I believe
for sed:
name=`echo $f | sed -E 's/([0-9]+_([a-z]+)_[0-9a-z]*)|.*/\2/'`
I'll take a stab at the bonus though:
echo "$name.jpg"
In Java 8 you can use Files.write() method with two arguments: Path
and List<String>
, something like this:
List<String> clubNames = clubs.stream()
.map(Club::getName)
.collect(Collectors.toList())
try {
Files.write(Paths.get(fileName), clubNames);
} catch (IOException e) {
log.error("Unable to write out names", e);
}
In 2018 here is what worked for me using MacOS HighSierra:
sudo lsof -nPi :yourPortNumber
then:
sudo kill -9 yourPIDnumber
For what you want I would've used
app.get('/fruit/:fruitName&:fruitColor', function(request, response) {
const name = request.params.fruitName
const color = request.params.fruitColor
});
or better yet
app.get('/fruit/:fruit', function(request, response) {
const fruit = request.params.fruit
console.log(fruit)
});
where fruit is a object. So in the client app you just call
https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"}
and as a response you should see:
// client side response
// { name: My fruit name, color:The color of the fruit}
Here's a solution that keeps things within a dplyr pipe chain. You sort the data in advance, and then using mutate_at to convert to a factor. I've modified the data slightly to show how this solution can be applied generally, given data that can be sensibly sorted:
# the data
temp <- data.frame(type=rep(c("T", "F", "P"), 4),
size=rep(c("50%", "100%", "200%", "150%"), each=3), # cannot sort this
size_num = rep(c(.5, 1, 2, 1.5), each=3), # can sort this
amount=c(48.4, 48.1, 46.8,
25.9, 26.0, 24.9,
20.8, 21.5, 16.5,
21.1, 21.4, 20.1))
temp %>%
arrange(size_num) %>% # sort
mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>% # convert to factor
ggplot() +
geom_bar(aes(x = type, y=amount, fill=type),
position="dodge", stat="identity") +
facet_grid(~ size)
You can apply this solution to arrange the bars within facets, too, though you can only choose a single, preferred order:
temp %>%
arrange(size_num) %>%
mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>%
arrange(desc(amount)) %>%
mutate_at(vars(type), funs(factor(., levels=unique(.)))) %>%
ggplot() +
geom_bar(aes(x = type, y=amount, fill=type),
position="dodge", stat="identity") +
facet_grid(~ size)
ggplot() +
geom_bar(aes(x = type, y=amount, fill=type),
position="dodge", stat="identity") +
facet_grid(~ size)
If you don't mind losing the history of your current shell terminal you could also do
bash -l
That would fork your shell and open up another child process of bash. The -l
parameter tells bash to run as a login shell, this is required because .bash_profile will not run as a non-login shell, for more info about this read here
If you want to completely replace the current shell you can also do:
exec bash -l
The above will not fork your current shell but replace it completely, so when you type exit
it will completely terminate, rather than dropping you to the previous shell.
Use "REPLACE" to remove special characters.
REPLACE(ColumnName ,' " ','')
Ex: -
--Query ---
DECLARE @STRING AS VARCHAR(100)
SET @STRING ='VI''RA""NJA "'
SELECT @STRING
SELECT REPLACE(REPLACE(@STRING,'''',''),'"','') AS MY_NAME
--Result---
VI'RA""NJA"
like that very easily
i added 10 minutes to system date and always in preference use the Db server functions not custom one .
select to_char(sysdate + NUMTODSINTERVAL(10,'MINUTE'),'DD/MM/YYYY HH24:MI:SS') from dual;
Simulator doesn't have a Camera. If you want to access a camera you need a device. You can't test camera on simulator. You can only check the photo and video gallery.
This is an UIImage extension compatible with Swift 3 and Swift 4 which scales image to given size with an aspect ratio
extension UIImage {
func scaledImage(withSize size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height))
return UIGraphicsGetImageFromCurrentImageContext()!
}
func scaleImageToFitSize(size: CGSize) -> UIImage {
let aspect = self.size.width / self.size.height
if size.width / aspect <= size.height {
return scaledImage(withSize: CGSize(width: size.width, height: size.width / aspect))
} else {
return scaledImage(withSize: CGSize(width: size.height * aspect, height: size.height))
}
}
}
Example usage
let image = UIImage(named: "apple")
let scaledImage = image.scaleImageToFitSize(size: CGSize(width: 45.0, height: 45.0))
If you have a mixture of formats in your date, don't forget to set infer_datetime_format=True
to make life easier.
df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)
Source: pd.to_datetime
or if you want a customized approach:
def autoconvert_datetime(value):
formats = ['%m/%d/%Y', '%m-%d-%y'] # formats to try
result_format = '%d-%m-%Y' # output format
for dt_format in formats:
try:
dt_obj = datetime.strptime(value, dt_format)
return dt_obj.strftime(result_format)
except Exception as e: # throws exception when format doesn't match
pass
return value # let it be if it doesn't match
df['date'] = df['date'].apply(autoconvert_datetime)
Try this (I've used Home controller and Index View):
return RedirectToAction("Index", "Home");
How about something like
import numpy as np
import matplotlib.pyplot as plt
V = np.array([[1,1], [-2,2], [4,-7]])
origin = np.array([[0, 0, 0],[0, 0, 0]]) # origin point
plt.quiver(*origin, V[:,0], V[:,1], color=['r','b','g'], scale=21)
plt.show()
Then to add up any two vectors and plot them to the same figure, do so before you call plt.show()
. Something like:
plt.quiver(*origin, V[:,0], V[:,1], color=['r','b','g'], scale=21)
v12 = V[0] + V[1] # adding up the 1st (red) and 2nd (blue) vectors
plt.quiver(*origin, v12[0], v12[1])
plt.show()
NOTE: in Python2 use origin[0], origin[1]
instead of *origin
This code sample is taken from csharp-examples.net, written by Jan Slama:
To find nodes in an XML file you can use XPath expressions. Method XmlNode.SelectNodes returns a list of nodes selected by the XPath string. Method XmlNode.SelectSingleNode finds the first node that matches the XPath string.
XML:
<Names> <Name> <FirstName>John</FirstName> <LastName>Smith</LastName> </Name> <Name> <FirstName>James</FirstName> <LastName>White</LastName> </Name> </Names>
CODE:
XmlDocument xml = new XmlDocument(); xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>" XmlNodeList xnList = xml.SelectNodes("/Names/Name"); foreach (XmlNode xn in xnList) { string firstName = xn["FirstName"].InnerText; string lastName = xn["LastName"].InnerText; Console.WriteLine("Name: {0} {1}", firstName, lastName); }
First, generate an Interface
Assuming you are using TypeScript & Angular CLI, you can generate one by using the following command
ng g interface car
After that set the data types of its properties
// car.interface.ts
export interface car {
id: number;
eco: boolean;
wheels: number;
name: string;
}
You can now import your interface in the class that you want.
import {car} from "app/interfaces/car.interface";
And update the collection/array of car objects by pushing items in the array.
this.car.push({
id: 12345,
eco: true,
wheels: 4,
name: 'Tesla Model S',
});
More on interfaces:
An interface is a TypeScript artifact, it is not part of ECMAScript. An interface is a way to define a contract on a function with respect to the arguments and their type. Along with functions, an interface can also be used with a Class as well to define custom types. An interface is an abstract type, it does not contain any code as a class does. It only defines the 'signature' or shape of an API. During transpilation, an interface will not generate any code, it is only used by Typescript for type checking during development. - https://angular-2-training-book.rangle.io/handout/features/interfaces.html
Looks like above solutions aren't using compare method and implementing total again so here is my solution and hope it works for you (It's working fine).
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
string tolow(string a)
{
for(unsigned int i=0;i<a.length();i++)
{
a[i]=tolower(a[i]);
}
return a;
}
int main()
{
string str1,str2;
cin>>str1>>str2;
int temp=tolow(str1).compare(tolow(str2));
if(temp>0)
cout<<1;
else if(temp==0)
cout<<0;
else
cout<<-1;
}
In my case, .composer
was owned by root, so I did sudo rm -fr .composer
and then my global require worked.
Be warned! You don't wanna use that command if you are not sure what you are doing.
Should it be LIBRARY_PATH
instead of LD_LIBRARY_PATH
.
gcc checks for LIBRARY_PATH
which can be seen with -v
option
The specific value in your database isn't what you should be focusing on. This is likely the result of an attacker fuzzing your system to see if it is vulnerable to a set of standard attacks, instead of a targeted attack exploiting a known vulnerability.
You should instead focus on ensuring that your application is secure against these types of attacks; OWASP is a good resource for this.
If you're using parameterized queries to access the database, then you're secure against Sql injection, unless you're using dynamic Sql in the backend as well.
If you're not doing this, you're vulnerable and you should resolve this immediately.
Also, you should consider performing some sort of validation of e-mail addresses.
Scala 2.13+
instead of "breakOut"
c.map(t => (t.getP, t)).to(Mat)
Scroll to "View": https://www.scala-lang.org/blog/2017/02/28/collections-rework.html
Check your tableview frame in storyboard or xib. Mine by default has a y position value, hence the bug
Pushwatch is a free to use online GCM and APNS push notification tester developed by myself in Django/Python as I have found myself in a similar situation while working on multiple projects. It can send both GCM
and APNS
notifications and also support JSON messages for extra arguments. Following are the links to the testers.
Please let me know if you have any questions or face issues using it.
I met the same problem and I resolved it by setting CopyLocal to true for the following libs:
System.Web.Http.dll
System.Web.Http.WebHost.dll
System.Net.Http.Formatting.dll
I must to add that I use MVC4 and NET 4
Look at this online backend.
They offer push notifications, social integration, data storage, and the ability to add rich custom logic to your app’s backend with Cloud Code.
Use port number 22 (for sftp) instead of 21 (normal ftp). Solved this problem for me.
^[^<>]+$
The caret in the character class ([^
) means match anything but, so this means, beginning of string, then one or more of anything except <
and >
, then the end of the string.
You can try with:
{% if theList.object_list.count > 0 %}
blah, blah...
{% else %}
blah, blah....
{% endif %}
You could prototype your own splice()
into String.
if (!String.prototype.splice) {
/**
* {JSDoc}
*
* The splice() method changes the content of a string by removing a range of
* characters and/or adding new characters.
*
* @this {String}
* @param {number} start Index at which to start changing the string.
* @param {number} delCount An integer indicating the number of old chars to remove.
* @param {string} newSubStr The String that is spliced in.
* @return {string} A new string with the spliced substring.
*/
String.prototype.splice = function(start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
}
String.prototype.splice = function(idx, rem, str) {_x000D_
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));_x000D_
};_x000D_
_x000D_
var result = "foo baz".splice(4, 0, "bar ");_x000D_
_x000D_
document.body.innerHTML = result; // "foo bar baz"
_x000D_
EDIT: Modified it to ensure that rem
is an absolute value.
You can use lsof
(list of open files) in most cases to find open log files without knowing the configuration.
Example:
Find the PID of httpd
(the same concept applies for nginx and other programs):
$ ps aux | grep httpd
...
root 17970 0.0 0.3 495964 64388 ? Ssl Oct29 3:45 /usr/sbin/httpd
...
Then search for open log files using lsof
with the PID:
$ lsof -p 17970 | grep log
httpd 17970 root 2w REG 253,15 2278 6723 /var/log/httpd/error_log
httpd 17970 root 12w REG 253,15 0 1387 /var/log/httpd/access_log
If lsof
prints nothing, even though you expected the log files to be found, issue the same command using sudo
.
You can read a little more here.
I've created a simple Dictionary
initializer that replaces NSDictionary(contentsOfFile: path)
. Just remove the NS
.
extension Dictionary where Key == String, Value == Any {
public init?(contentsOfFile path: String) {
let url = URL(fileURLWithPath: path)
self.init(contentsOfURL: url)
}
public init?(contentsOfURL url: URL) {
guard let data = try? Data(contentsOf: url),
let dictionary = (try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any]) ?? nil
else { return nil }
self = dictionary
}
}
You can use it like so:
let filePath = Bundle.main.path(forResource: "Preferences", ofType: "plist")!
let preferences = Dictionary(contentsOfFile: filePath)!
UserDefaults.standard.register(defaults: preferences)
I am using Ubuntu. I just disabled ssl mode of apache2 and it worked for me.
a2dismod ssl
and then restarted apache2.
service apache2 restart
The cleanest way for you to accomplish this is to use the enumitem package (https://ctan.org/pkg/enumitem). For example,
\documentclass{article}
\usepackage{enumitem}% http://ctan.org/pkg/enumitem
\begin{document}
\noindent Here is some text and I want to make sure
there is no spacing the different items.
\begin{itemize}[noitemsep]
\item Item 1
\item Item 2
\item Item 3
\end{itemize}
\noindent Here is some text and I want to make sure
there is no spacing between this line and the item
list below it.
\begin{itemize}[noitemsep,topsep=0pt]
\item Item 1
\item Item 2
\item Item 3
\end{itemize}
\end{document}
Furthermore, if you want to use this setting globally across lists, you can use
\usepackage{enumitem}% http://ctan.org/pkg/enumitem
\setlist[itemize]{noitemsep, topsep=0pt}
However, note that this package does not work well with the beamer package which is used to make presentations in Latex.
you can use the new HTML 5 file api to read file contents
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
but this won't work on every browser so you probably need a server side fallback.
Several solutions are discussed in http://blog.xelnor.net/python-mocking-datetime/. In summary:
Mock object - Simple and efficient but breaks isinstance() checks:
target = datetime.datetime(2009, 1, 1)
with mock.patch.object(datetime, 'datetime', mock.Mock(wraps=datetime.datetime)) as patched:
patched.now.return_value = target
print(datetime.datetime.now())
Mock class
import datetime
import mock
real_datetime_class = datetime.datetime
def mock_datetime_now(target, dt):
class DatetimeSubclassMeta(type):
@classmethod
def __instancecheck__(mcs, obj):
return isinstance(obj, real_datetime_class)
class BaseMockedDatetime(real_datetime_class):
@classmethod
def now(cls, tz=None):
return target.replace(tzinfo=tz)
@classmethod
def utcnow(cls):
return target
# Python2 & Python3 compatible metaclass
MockedDatetime = DatetimeSubclassMeta('datetime', (BaseMockedDatetime,), {})
return mock.patch.object(dt, 'datetime', MockedDatetime)
Use as:
with mock_datetime_now(target, datetime):
....
In some cases it is possible to define a method or a constructor of class B in the header file of class A to resolve circular dependencies involving definitions.
In this way you can avoid having to put definitions in .cc
files, for example if you want to implement a header only library.
// file: a.h
#include "b.h"
struct A {
A(const B& b) : _b(b) { }
B get() { return _b; }
B _b;
};
// note that the get method of class B is defined in a.h
A B::get() {
return A(*this);
}
// file: b.h
class A;
struct B {
// here the get method is only declared
A get();
};
// file: main.cc
#include "a.h"
int main(...) {
B b;
A a = b.get();
}
For select2 version 4 easily use this:
$('#remote').empty();
After populating select element with ajax call, you may need this line of code in the success section to update the content:
success: function(data, textStatus, jqXHR){
$('#remote').change();
}
And if you want to retain any of the aggregation info from the second level of the multiindex you can try this:
In [1]: new_cols = [''.join(t) for t in df.columns]
Out[1]:
['USAF',
'WBAN',
'day',
'month',
's_CDsum',
's_CLsum',
's_CNTsum',
's_PCsum',
'tempfamax',
'tempfamin',
'year']
In [2]: df.columns = new_cols
Second Approach :
angular.module('myApp', [])
.controller('Ctrl1', ['$scope',
function($scope) {
$scope.prop1 = "First";
$scope.clickFunction = function() {
$scope.$broadcast('update_Ctrl2_controller', $scope.prop1);
};
}
])
.controller('Ctrl2', ['$scope',
function($scope) {
$scope.prop2 = "Second";
$scope.$on("update_Ctrl2_controller", function(event, prop) {
$scope.prop = prop;
$scope.both = prop + $scope.prop2;
});
}
])
Html :
<div ng-controller="Ctrl2">
<p>{{both}}</p>
</div>
<button ng-click="clickFunction()">Click</button>
For more details see plunker :
Checked Exceptions :
The exceptions which are checked by the compiler for smooth execution of the program at runtime are called Checked Exception.
These occur at compile time.
All subclasses of Exception class except RuntimeException are Checked Exception.
Hypothetical Example - Suppose you are leaving your house for the exam, but if you check whether you took your Hall Ticket at home(compile time) then there won't be any problem at Exam Hall(runtime).
Unchecked Exception :
The exceptions which are not checked by the compiler are called Unchecked Exceptions.
These occur at runtime.
If these exceptions are not handled properly, they don’t give compile time error. But the program will be terminated prematurely at runtime.
All subclasses of RunTimeException and Error are unchecked exceptions.
Hypothetical Example - Suppose you are in your exam hall but somehow your school had a fire accident (means at runtime) where you can't do anything at that time but precautions can be made before (compile time).
If you don't have a .gitignore file. You can create a new one by
touch .gitignore
And you can exclude a folder by entering the below command in the .gitignore file
/folderName
push this file into your git repository so that when a new person clone your project he don't have to add the same again
The actual answer is "use mutation observers" (as outlined in this question: Determining if a HTML element has been added to the DOM dynamically), however support (specifically on IE) is limited (http://caniuse.com/mutationobserver).
So the actual ACTUAL answer is "Use mutation observers.... eventually. But go with Jose Faeti's answer for now" :)
This is my solution.. i hope it helps anyone. It's written on the fly instead of copypasted so forgive me for any mistakes.
$("#btn").on("click", function(ev){
ev.preventDefault();
dialog.dialog("open");
dialog.find(".btnConfirm").on("click", function(){
// trigger click under different namespace so
// click handler will not be triggered but native
// functionality is preserved
$("#btn").trigger("click.confirmed");
}
dialog.find(".btnCancel").on("click", function(){
dialog.dialog("close");
}
});
Personally I prefer this solution :)
edit: Sorry.. i really shouldve explained it more in detail. I like it because in my opinion its an elegant solution. When user clicks the button which needs to be confirmed first the event is canceled as it has to be. When the confirmation button is clicked the solution is not to simulate a link click but to trigger the same native jquery event (click) upon the original button which would have triggered if there was no confirmation dialog. The only difference being a different event namespace (in this case 'confirmed') so that the confirmation dialog is not shown again. Jquery native mechanism can then take over and things can run as expected. Another advantage being it can be used for buttons and hyperlinks. I hope i was clear enough.
Remove the 'bin' from JAVA_HOME. That solves the issue.
Another approach when you have many updates would be to use COALESCE:
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] = COALESCE(@ABC, [ABC]),
[ABCD] = COALESCE(@ABCD, [ABCD])
In your app's theme/style, add the following lines:
<item name="android:buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
<item name="android:buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
<item name="android:buttonBarNeutralButtonStyle">@style/NeutralButtonStyle</item>
Then add the following styles:
<style name="NegativeButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
<item name="android:textColor">@color/red</item>
</style>
<style name="PositiveButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
<item name="android:textColor">@color/red</item>
</style>
<style name="NeutralButtonStyle"
parent="Widget.MaterialComponents.Button.TextButton.Dialog">
<item name="android:textColor">#00f</item>
</style>
Using this method makes it unneccessary to set the theme in the AlertDialog builder.
You can go to the Start Menu and search the Node.js icon and open the shell and then install anything with
install <packagename> -g
The best way to do it I think is:
if(val != true){
//do something
}
This will be true if val is false, NaN, or undefined.
Answer is simple. when u pass value from dropdown.
Just use as if else.
for eg:
foreach($result as $row) {
$GLOBALS['output'] .='<option value="'.$row["dropdownid"].'"'.
($GLOBALS['passselectedvalueid']==$row["dropwdownid"] ? ' Selected' : '').'
>'.$row['valueetc'].'</option>';
}
new ES6:
'import' should be used with 'export' key words to share variables/arrays/objects between js files:
export default myObject;
//....in another file
import myObject from './otherFile.js';
old skool:
'require' should be used with 'module.exports'
module.exports = myObject;
//....in another file
var myObject = require('./otherFile.js');
Well you can not run code from notepad so that means you are opening up the page from the file system. aka c:/foo/bar/hello.html
When you run the code from the asp.net page, you are running it from localhost. aka http://loalhost:1234/assdf.html
Each of these run in different security zones on IE.
you can use setTextColor(int) method or add style to change text color.
<style name="ReviewScreenKbbViewMoreStyle">
<item name="android:textColor">#2F2E86</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">10dip</item>
IN SWIFT 3. Here are the NSURLErrorDomain error codes description in a Swift 3 enum: (copied from answer above and converted what i can).
enum NSURLError: Int {
case unknown = -1
case cancelled = -999
case badURL = -1000
case timedOut = -1001
case unsupportedURL = -1002
case cannotFindHost = -1003
case cannotConnectToHost = -1004
case connectionLost = -1005
case lookupFailed = -1006
case HTTPTooManyRedirects = -1007
case resourceUnavailable = -1008
case notConnectedToInternet = -1009
case redirectToNonExistentLocation = -1010
case badServerResponse = -1011
case userCancelledAuthentication = -1012
case userAuthenticationRequired = -1013
case zeroByteResource = -1014
case cannotDecodeRawData = -1015
case cannotDecodeContentData = -1016
case cannotParseResponse = -1017
//case NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022
case fileDoesNotExist = -1100
case fileIsDirectory = -1101
case noPermissionsToReadFile = -1102
//case NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) = -1103
// SSL errors
case secureConnectionFailed = -1200
case serverCertificateHasBadDate = -1201
case serverCertificateUntrusted = -1202
case serverCertificateHasUnknownRoot = -1203
case serverCertificateNotYetValid = -1204
case clientCertificateRejected = -1205
case clientCertificateRequired = -1206
case cannotLoadFromNetwork = -2000
// Download and file I/O errors
case cannotCreateFile = -3000
case cannotOpenFile = -3001
case cannotCloseFile = -3002
case cannotWriteToFile = -3003
case cannotRemoveFile = -3004
case cannotMoveFile = -3005
case downloadDecodingFailedMidStream = -3006
case downloadDecodingFailedToComplete = -3007
/*
case NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) = -1018
case NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) = -1019
case NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) = -1020
case NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) = -1021
case NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995
case NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996
case NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997
*/
}
Direct link to URLError.Code
in the Swift github repository, which contains the up to date list of error codes being used (github link).
You can create enums to deal with errors :)
enum RikhError: Error {
case unknownError
case connectionError
case invalidCredentials
case invalidRequest
case notFound
case invalidResponse
case serverError
case serverUnavailable
case timeOut
case unsuppotedURL
}
and then create a method inside enum to receive the http response code and return the corresponding error in return :)
static func checkErrorCode(_ errorCode: Int) -> RikhError {
switch errorCode {
case 400:
return .invalidRequest
case 401:
return .invalidCredentials
case 404:
return .notFound
//bla bla bla
default:
return .unknownError
}
}
Finally update your failure block to accept single parameter of type RikhError :)
I have a detailed tutorial on how to restructure traditional Objective - C based Object Oriented network model to modern Protocol Oriented model using Swift3 here https://learnwithmehere.blogspot.in Have a look :)
Hope it helps :)
I don't think you can give a path to curl, but you can CD to the location, download and CD back.
cd target/path && { curl -O URL ; cd -; }
Or using subshell.
(cd target/path && curl -O URL)
Both ways will only download if path exists. -O
keeps remote file name. After download it will return to original location.
If you need to set filename explicitly, you can use small -o
option:
curl -o target/path/filename URL
Any recommendation on how to fix this?
Several. You can use bind:
for (i = 0; i < j; i++) {
asycronouseProcess(function (i) {
alert(i);
}.bind(null, i));
}
Or, if your browser supports let (it will be in the next ECMAScript version, however Firefox already supports it since a while) you could have:
for (i = 0; i < j; i++) {
let k = i;
asycronouseProcess(function() {
alert(k);
});
}
Or, you could do the job of bind
manually (in case the browser doesn't support it, but I would say you can implement a shim in that case, it should be in the link above):
for (i = 0; i < j; i++) {
asycronouseProcess(function(i) {
return function () {
alert(i)
}
}(i));
}
I usually prefer let
when I can use it (e.g. for Firefox add-on); otherwise bind
or a custom currying function (that doesn't need a context object).
'nunique' is an option for .agg() since pandas 0.20.0, so:
df.groupby('date').agg({'duration': 'sum', 'user_id': 'nunique'})
I have worked alot with msaccess vba. I think you are looking for MID function
example
dim myReturn as string
myreturn = mid("bonjour tout le monde",9,4)
will give you back the value "tout"
From the theoretical point of view, Languages can only support self-referential structures not self-inclusive structures.
I'll get back to you on instanceof performance. But a way to avoid problem (or lack thereof) altogether would be to create a parent interface to all the subclasses on which you need to do instanceof. The interface will be a super set of all the methods in sub-classes for which you need to do instanceof check. Where a method does not apply to a specific sub-class, simply provide a dummy implementation of this method. If I didn't misunderstand the issue, this is how I've gotten around the problem in the past.
issue is with the /var/lib/jenkins/.ssh/known_hosts. It exists in the first case, but not in the second one. This means you are running either on different system or the second case is somehow jailed in chroot or by other means separated from the rest of the filesystem (this is a good idea for running random code from jenkins).
Next steps are finding out how are the chroots for this user created and modify the known hosts inside this chroot. Or just go other ways of ignoring known hosts, such as ssh-keyscan, StrictHostKeyChecking=no or so.
You can do it by making the background into a pattern:
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image href="wall.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
Adjust the width and height according to your image, then reference it from the path like this:
<path d="M5,50
l0,100 l100,0 l0,-100 l-100,0
M215,100
a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
M265,50
l50,100 l-100,0 l50,-100
z"
fill="url(#img1)" />
If Short.TryParse(editTransactionRow.pay_id, New Short) Then editTransactionRow.pay_id.ToString()
Go to MongoDB website, Login > Connect > Connect Application > Copy > Paste in 'database_url' > Collections > Copy/Paste in 'collection' .
var mongoose = require("mongoose");
mongoose.connect(' database_url ');
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function () {
conn.db.collection(" collection ", function(err, collection){
collection.find({}).toArray(function(err, data){
console.log(data); // data printed in console
})
});
});
Happy to Help. by RTTSS.
try
{
// Some code
}
catch (Web2PDFException ex)
{
// It's your special exception
}
catch (Exception ex)
{
// Any other exception here
}
what about just store the output to the static table ? Like
-- SubProcedure: subProcedureName
---------------------------------
-- Save the value
DELETE lastValue_subProcedureName
INSERT INTO lastValue_subProcedureName (Value)
SELECT @Value
-- Return the value
SELECT @Value
-- Procedure
--------------------------------------------
-- get last value of subProcedureName
SELECT Value FROM lastValue_subProcedureName
its not ideal, but its so simple and you don't need to rewrite everything.
UPDATE: the previous solution does not work well with parallel queries (async and multiuser accessing) therefore now Iam using temp tables
-- A local temporary table created in a stored procedure is dropped automatically when the stored procedure is finished.
-- The table can be referenced by any nested stored procedures executed by the stored procedure that created the table.
-- The table cannot be referenced by the process that called the stored procedure that created the table.
IF OBJECT_ID('tempdb..#lastValue_spGetData') IS NULL
CREATE TABLE #lastValue_spGetData (Value INT)
-- trigger stored procedure with special silent parameter
EXEC dbo.spGetData 1 --silent mode parameter
nested spGetData
stored procedure content
-- Save the output if temporary table exists.
IF OBJECT_ID('tempdb..#lastValue_spGetData') IS NOT NULL
BEGIN
DELETE #lastValue_spGetData
INSERT INTO #lastValue_spGetData(Value)
SELECT Col1 FROM dbo.Table1
END
-- stored procedure return
IF @silentMode = 0
SELECT Col1 FROM dbo.Table1
In addition to Idriss answer:
In CSS we write code as depicted bellow, in full length.
body{
width: 800px;
color: #ffffff;
}
body content{
width:750px;
background:#ffffff;
}
In SCSS we can shorten this code using a @mixin
so we don’t have to write color
and width
properties again and again. We can define this through a function, similarly to PHP or other languages.
$color: #ffffff;
$width: 800px;
@mixin body{
width: $width;
color: $color;
content{
width: $width;
background:$color;
}
}
In SASS however, the whole structure is visually quicker and cleaner than SCSS.
It seems that it doesn't support inline CSS currently.
$color: #ffffff
$width: 800px
$stack: Helvetica, sans-serif
body
width: $width
color: $color
font: 100% $stack
content
width: $width
background:$color
You can also change the date format for the session. This is useful, for example, in Perl DBI, where the to_date() function is not available:
ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'
You can permanently set the default nls_date_format as well:
ALTER SYSTEM SET NLS_DATE_FORMAT='YYYY-MM-DD'
In Perl DBI you can run these commands with the do() method:
$db->do("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD');
http://www.dba-oracle.com/t_dbi_interface1.htm https://community.oracle.com/thread/682596?start=15&tstart=0
It's not exactly clear how you want to search the array. Here are some alternatives:
Find all items containing the exact string "Ra" (returns items 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.Contains("Ra"))
Find all items starting with the exact string "Ra" (returns items 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.StartsWith("Ra"))
Find all items containing any case version of "ra" (returns items 0, 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().Contains("ra"))
Find all items starting with any case version of "ra" (retuns items 0, 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))
-
If you are not using VB 9+ then you don't have anonymous functions, so you have to create a named function.
Example:
Function ContainsRa(s As String) As Boolean
Return s.Contains("Ra")
End Function
Usage:
Dim result As String() = Array.FindAll(arr, ContainsRa)
Having a function that only can compare to a specific string isn't always very useful, so to be able to specify a string to compare to you would have to put it in a class to have somewhere to store the string:
Public Class ArrayComparer
Private _compareTo As String
Public Sub New(compareTo As String)
_compareTo = compareTo
End Sub
Function Contains(s As String) As Boolean
Return s.Contains(_compareTo)
End Function
Function StartsWith(s As String) As Boolean
Return s.StartsWith(_compareTo)
End Function
End Class
Usage:
Dim result As String() = Array.FindAll(arr, New ArrayComparer("Ra").Contains)
The correct scheme should be:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/Sport"
xmlns:tns="http://www.example.org/Sport"
elementFormDefault="qualified"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
jaxb:version="2.0">
<complexType name="sportType">
<simpleContent>
<extension base="string">
<attribute name="type" type="string" />
<attribute name="gender" type="string" />
</extension>
</simpleContent>
</complexType>
<element name="sports">
<complexType>
<sequence>
<element name="sport" minOccurs="0" maxOccurs="unbounded"
type="tns:sportType" />
</sequence>
</complexType>
</element>
Code generated for SportType will be:
package org.example.sport;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sportType")
public class SportType {
@XmlValue
protected String value;
@XmlAttribute
protected String type;
@XmlAttribute
protected String gender;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String value) {
this.type = value;
}
public String getGender() {
return gender;
}
public void setGender(String value) {
this.gender = value;
}
}
Forget it; this might work with Outlook or maybe even GMail but you won't be able to get this working properly supporting most other E-mail clients out there (and there's a shitton of 'em).
You're better of using a simple PHP script (check out PHPMailer) or use a hosted solution (Google "email form hosted", "free email form hosting" or something similar)
By the way, you are looking for the term "Percent-encoding" (also called url-encoding and Javascript uses encodeUri/encodeUriComponent (make sure you understand the differences!)). You will need to encode a whole lot more than just newlines.
If your Manifest.xml
has the default android:theme="@style/AppTheme"
Go to res/values/styles.xml and change
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
to
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
And the ActionBar
is disappeared!
There are two different notations to access object properties
Dot notation is fast and easy but you must use the actual property name explicitly. No substitution, variables, etc.
Bracket notation is open ended. It uses a string but you can produce the string using any legal js code. You may specify the string as literal (though in this case dot notation would read easier) or use a variable or calculate in some way.
So, these all set the myObj property named prop1 to the value Hello:
// quick easy-on-the-eye dot notation
myObj.prop1 = "Hello";
// brackets+literal
myObj["prop1"] = "Hello";
// using a variable
var x = "prop1";
myObj[x] = "Hello";
// calculate the accessor string in some weird way
var numList = [0,1,2];
myObj[ "prop" + numList[1] ] = "Hello";
Pitfalls:
myObj.[xxxx] = "Hello"; // wrong: mixed notations, syntax fail
myObj[prop1] = "Hello"; // wrong: this expects a variable called prop1
tl;dnr: If you want to compute or reference the key you must use bracket notation. If you are using the key explicitly, then use dot notation for simple clear code.
Note: there are some other good and correct answers but I personally found them a bit brief coming from a low familiarity with JS on-the-fly quirkiness. This might be useful to some people.
If the autofiltering is part of a subroutine operation, you could use
BioSum.Unprotect "letmein"
'<Your function here>
BioSum.Cells(1, 1).Activate
BioSum.Protect "letmein"
to momentarily unprotect the sheet, filter the cells, and reprotect afterwards.
You use an addtional attribute; fill-opacity
: This attribute takes a decimal number between 0.0 and 1.0, inclusive; where 0.0 is completely transparent.
For example:
<rect ... fill="#044B94" fill-opacity="0.4"/>
Additionally you have the following:
stroke-opacity
attribute for the strokeopacity
for the entire objectYou Can simply Use One Jsp Page To accomplish the task.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String username=request.getParameter("user_name");
String password=request.getParameter("password");
String role=request.getParameter("role");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
Statement st=con.createStatement();
String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
session.setAttribute( "user_name",rs.getString(2));
session.setMaxInactiveInterval(3000);
response.sendRedirect("homepage.jsp");
}
%>
<%}
catch(Exception e)
{
out.println(e);
}
%>
</body>
I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.
Yes its possible! and you can use as many colors and images as you desire, here is the right way:
body{_x000D_
/* Its, very important to set the background repeat to: no-repeat */_x000D_
background-repeat:no-repeat; _x000D_
_x000D_
background-image: _x000D_
/* 1) An image */ url(http://lorempixel.com/640/100/nature/John3-16/), _x000D_
/* 2) Gradient */ linear-gradient(to right, RGB(0, 0, 0), RGB(255, 255, 255)), _x000D_
/* 3) Color(using gradient) */ linear-gradient(to right, RGB(110, 175, 233), RGB(110, 175, 233));_x000D_
_x000D_
background-position:_x000D_
/* 1) Image position */ 0 0, _x000D_
/* 2) Gradient position */ 0 100px,_x000D_
/* 3) Color position */ 0 130px;_x000D_
_x000D_
background-size: _x000D_
/* 1) Image size */ 640px 100px,_x000D_
/* 2) Gradient size */ 100% 30px, _x000D_
/* 3) Color size */ 100% 30px;_x000D_
}
_x000D_
You want to convert html (a byte-like object) into a string using .decode
, e.g. html = response.read().decode('utf-8')
.
I had a similar problem. Here is what I did. Since the element I was trying to center vertically had height = 60px, I managed to center it vertically using:
top: calc(50% - 30px);
Try the following :)
textBox1.Multiline = true;
textBox1.Height = 100;
textBox1.Width = 173;
I have installed Node.js on an iMac and
node somefile.js
in bash will work.
per @Kevin-Reid's answer, here's an alternative to the "I ended up doing the following" example that avoids needing to name and then lookup the form object again by constructing the form specifically (using jQuery)..
var url = 'http://example.com/vote/' + Username;
var form = $('<form action="' + url + '" method="post">' +
'<input type="text" name="api_url" value="' + Return_URL + '" />' +
'</form>');
$('body').append(form);
form.submit();
private String removeScript(String content) {
Pattern p = Pattern.compile("<script[^>]*>(.*?)</script>",
Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
return p.matcher(content).replaceAll("");
}
A simple inline JavaScript confirm would suffice:
<form onsubmit="return confirm('Do you really want to submit the form?');">
No need for an external function unless you are doing validation, which you can do something like this:
<script>
function validate(form) {
// validation code here ...
if(!valid) {
alert('Please correct the errors in the form!');
return false;
}
else {
return confirm('Do you really want to submit the form?');
}
}
</script>
<form onsubmit="return validate(this);">
If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:
Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:
In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.
Source: http://blogs.msdn.com/b/ianhu/archive/2014/12/16/gpu-usage-for-directx-in-visual-studio.aspx
var ref = $('#example').DataTable();
ref.ajax.reload();
If you want to add a reload/refresh button to DataTables 1.10 then use drawCallback.
See example below (I am using DataTables with bootstrap css)
var ref= $('#hldy_tbl').DataTable({
"responsive": true,
"processing":true,
"serverSide":true,
"ajax":{
"url":"get_hotels.php",
"type":"POST"
},
"drawCallback": function( settings ) {
$('<li><a onclick="refresh_tab()" class="fa fa-refresh"></a></li>').prependTo('div.dataTables_paginate ul.pagination');
}
});
function refresh_tab(){
ref.ajax.reload();
}
Well, did you DO what the error says? You go to some length telling about installation, but what about the obvious?
You can use a list comprehension:
[x for x in j if x >= 5]
I think this is a simple way for beginners:
using System;
using System.Numerics;
public class PrimeChecker
{
public static void Main()
{
// Input
Console.WriteLine("Enter number to check is it prime: ");
BigInteger n = BigInteger.Parse(Console.ReadLine());
bool prime = false;
// Logic
if ( n==0 || n==1)
{
Console.WriteLine(prime);
}
else if ( n==2 )
{
prime = true;
Console.WriteLine(prime);
}
else if (n>2)
{
IsPrime(n, prime);
}
}
// Method
public static void IsPrime(BigInteger n, bool prime)
{
bool local = false;
for (int i=2; i<=(BigInteger)Math.Sqrt((double)n); i++)
{
if (n % i == 0)
{
local = true;
break;
}
}
if (local)
{
Console.WriteLine(prime);
}
else
{
prime = true;
Console.WriteLine(prime);
}
}
}
The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
Simply goto MySql Console.
If using Wamp:
That's it. This set your root password to secret
In order to set user privilege to default one:
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('');
Works like a charm!
You don't need regex to do this. Here's an example :
var str = "'SELECT___100E___7',24";
var afterComma = str.substr(str.indexOf(",") + 1); // Contains 24 //
In the current component's module import RouterModule.
Like:-
import {RouterModule} from '@angular/router';
@NgModule({
declarations:[YourComponents],
imports:[RouterModule]
...
It helped me.
In my application,above javascript function didnt work,because i had many procrosses inside one page.so following code worked for me hope it helps you guys.
function redirection()
{
<?php $send=$_SERVER['HTTP_REFERER'];?>
var redirect_to="<?php echo $send;?>";
window.location = redirect_to;
}
In my case i had to move the html code of the element i wanted at the front at the end of the html file, because if one element has z-index and the other doesn't have z index it doesn't work.
First take a label. set its visibility to false, then on the DataGridView_CellClick event write this
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
label.Text=dataGridView1.Rows[e.RowIndex].Cells["Your Coloumn name"].Value.ToString();
// then perform your select statement according to that label.
}
//try it it might work for you
This has found an accepted answered, but I recently came across the UIImage+animatedGIF UIImage extension. It provides the following category:
+[UIImage animatedImageWithAnimatedGIFURL:(NSURL *)url]
allowing you to simply:
#import "UIImage+animatedGIF.h"
UIImage* mygif = [UIImage animatedImageWithAnimatedGIFURL:[NSURL URLWithString:@"http://en.wikipedia.org/wiki/File:Rotating_earth_(large).gif"]];
Works like magic.
If you just want to know if there are symbols present you can use
objdump -h /path/to/object
or to list the debug info
objdump -g /path/to/object
If anyone is using Maven, you'll need to add the dependency in the POM.XML file. The latest version as of this post is below:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
Open a command prompt. Enter the command spyder
. Does anything appear? If an exception is preventing it from opening, you would be able to see the reason here. If the command is not found, update your environment variables to point to the Python3.6/Scripts folder, and run spyder
again (in a new cmd prompt).
In script is usefull something like this:
if [ ! -d /etc/nginx ]; then ln -s /usr/local/nginx/conf/ /etc/nginx > /dev/null 2>&1; fi
it prevents before re-create "bad" looped symlink after re-run script
res.writeHead(404, {'Content-Type': 'text/plain'}); // <- redirect
res.write("Looked everywhere, but couldn't find that page at all!\n"); // <- content!
res.end(); // that's all!
res.writeHead(302, {'Location': 'https://example.com' + req.url});
res.end();
Just consider where you use this (e.g. only for http request), so you don't get endless redirects ;-)
You need a program that learns and improves classification accuracy organically from experience.
I'll suggest deep learning, with deep learning this becomes a trivial problem.
You can retrain the inception v3 model on Tensorflow:
How to Retrain Inception's Final Layer for New Categories.
In this case, you will be training a convolutional neural network to classify an object as either a coca-cola can or not.
function getParent(event)
{
return event.target.parentNode;
}
Examples: 1.
document.body.addEventListener("click", getParent, false);
returns the parent element of the current element that you have clicked.
- If you want to use inside any function then pass your event and call the function like this :
function yourFunction(event){ var parentElement = getParent(event); }
Check this handy pipe for Angular2: Usage:
in the SafePipe
code, substitute DomSanitizationService
with DomSanitizer
provide the SafePipe
if your NgModule
<div [style.background-image]="'url(' + your_property + ')' | safe: 'style'"></div>
Finally i found a way to clone specific commit using git cherry-pick. Assuming you don't have any repository in local and you are pulling specific commit from remote,
1) create empty repository in local and git init
2) git remote add origin "url-of-repository"
3) git fetch origin [this will not move your files to your local workspace unless you merge]
4) git cherry-pick "Enter-long-commit-hash-that-you-need"
Done.This way, you will only have the files from that specific commit in your local.
You can get this using -> git log --pretty=oneline
If you want a timestamp instead of just a date with sysdate, you can specify a timezone using systimestamp:
select systimestamp at time zone 'UTC' from dual
outputs: 29-AUG-17 06.51.14.781998000 PM UTC
you can use cleave.js
// phone (123) 123-4567
var cleavePhone = new Cleave('.input-phone', {
//prefix: '(123)',
delimiters: ['(',') ','-'],
blocks: [0, 3, 3, 4]
});
I actually use notifyDataSetChanged()
on ViewPager
and CirclePageIndicator
and after that I call destroyDrawingCache()
on ViewPager
and it works.. None of the other solutions worked for me.
What I ended up doing is create a new KeyContainer name based off of the current DateTime (DateTime.Now.Ticks.ToString()) whenever I need to create a new key and save the container name and public key to the database. Also, whenever I create a new key I would do the following:
public static string ConvertToNewKey(string oldPrivateKey)
{
// get the current container name from the database...
rsa.PersistKeyInCsp = false;
rsa.Clear();
rsa = null;
string privateKey = AssignNewKey(true); // create the new public key and container name and write them to the database...
// re-encrypt existing data to use the new keys and write to database...
return privateKey;
}
public static string AssignNewKey(bool ReturnPrivateKey){
string containerName = DateTime.Now.Ticks.ToString();
// create the new key...
// saves container name and public key to database...
// and returns Private Key XML.
}
before creating the new key.
Use compact
function view($view)
{
$ms = Person::where('name', '=', 'Foo Bar')->first();
$persons = Person::order_by('list_order', 'ASC')->get();
return View::make('users', compact('ms','persons'));
}