In my case it was not working because of the return.
Instead of using:
return RedirectToAction("Rescue", "CarteiraEtapaInvestimento", new { id = investimento.Id, idCarteiraEtapaResgate = etapaDoResgate.Id });
I used:
return View("ViewRescueCarteiraEtapaInvestimento", new CarteiraEtapaInvestimentoRescueViewModel { Investimento = investimento, ValorResgate = investimentoViewModel.ValorResgate });
It´s a Model, so it is obvius that ModelState.AddModelError("keyName","Message");
must work with a model.
This answer show why. Adding validation with DataAnnotations
You can add the model error on any property of your model, I suggest if there is nothing related to create a new property.
As an exemple we check if the email is already in use in DB and add the error to the Email property in the action so when I return the view, they know that there's an error and how to show it up by using
<%: Html.ValidationSummary(true)%>
<%: Html.ValidationMessageFor(model => model.Email) %>
and
ModelState.AddModelError("Email", Resources.EmailInUse);
You are trying to add an integer into an ArrayList
that takes an array of integers Integer[]
. It should be
ArrayList<Integer> list = new ArrayList<>();
or better
List<Integer> list = new ArrayList<>();
Use the Oracle documentation and search for keyword "trigger" in your browser.
This approach should work with other metadata type questions.
A good practice is listening for resize events to prevent resize on render or even a user window resize that can bug your application.
const MyComponent = ()=> {
const myRef = useRef(null)
const [myComponenetWidth, setMyComponentWidth] = useState('')
const handleResize = ()=>{
setMyComponentWidth(myRef.current.offsetWidth)
}
useEffect(() =>{
if(myRef.current)
myRef.current.addEventListener('resize', handleResize)
return ()=> {
myRef.current.removeEventListener('resize', handleResize)
}
}, [myRef])
return (
<div ref={MyRef}>Hello</div>
)
}
The problem with String concatenation is that it leads to copying of the String object with all the associated cost. StringBuilder is not threadsafe and is therefore faster than StringBuffer, which used to be the preferred choice before Java 5. As a rule of thumb, you should not do String concatenation in a loop, which will be called often. I guess doing a few concatenations here and there will not hurt you as long as you are not talking about hundreds and this of course depends on your performance requirements. If you are doing real time stuff, you should be very careful.
Here is a tutorial about how to do XSL Transformations in C# on MSDN:
http://support.microsoft.com/kb/307322/en-us/
and here how to write files:
http://support.microsoft.com/kb/816149/en-us
just as a side note: if you want to do validation too here is another tutorial (for DTD, XDR, and XSD (=Schema)):
http://support.microsoft.com/kb/307379/en-us/
i added this just to provide some more information.
If your dateString is RFC282 and ISO8601 compliant:
pass your string into the Date Constructor:
const dateString = "2020-10-30T12:52:27+05:30"; // ISO8601 compliant dateString
const D = new Date(dateString); // {object Date}
from here you can extract the desired values by using Date Getters:
D.getMonth() + 1 // 10 (PS: +1 since Month is 0-based)
D.getDate() // 30
D.getFullYear() // 2020
If you use a non standard date string:
destructure the string into known parts, and than pass the variables to the Date Constructor:
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
const dateString = "30/10/2020 12:52:27";
const [d, M, y, h, m, s] = dateString.match(/\d+/g);
// PS: M-1 since Month is 0-based
const D = new Date(y, M-1, d, h, m, s); // {object Date}
D.getMonth() + 1 // 10 (PS: +1 since Month is 0-based)
D.getDate() // 30
D.getFullYear() // 2020
fade's answer worked for me. I moved from 8.0.30 to 8.5.5 and the difference was the valve in <8.0.30>/manager/META-INF/context.xml was already commented out from the tar file but was uncommented in 8.5.5 tar.
I failed to read this important message in the 403 response:
By default the Manager is only accessible from a browser running on the same machine as Tomcat. If you wish to modify this restriction, you'll need to edit the Manager's context.xml file.
And failed to read this too:
Since r1734267 a RemoteAddrValve.is configured by default in Manager and HostManager web applications. This feature is present in 9.0.0.M4 and 8.5.0 onwards.
Your and
should be a &&
in the where
clause.
where epl.DepartAirportAfter > sd.UTCDepartureTime
and epl.ArriveAirportBy > sd.UTCArrivalTime
should be
where epl.DepartAirportAfter > sd.UTCDepartureTime
&& epl.ArriveAirportBy > sd.UTCArrivalTime
As far as I can see everything is right with your code. Your error is:
SMTP Error: Could not authenticate.
Which means that the credentials you've sending are rejected by the SMTP server. Make sure the host, port, username and password are good.
If you want to use STARTTLS, try adding:
$mail->SMTPSecure = 'tls';
If you want to use SMTPS (SSL), try adding:
$mail->SMTPSecure = 'ssl';
Keep in mind that:
Maybe this example can help (GMail secure SMTP).
You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.
You just need to re-open the image with IrfanView after changing the view color to white.
To change the viewing color in Irfanview go to:
Options > Properties/Settings > Viewing > Main window color
SELECT *
FROM emp_salaryrevise_view
WHERE curr_year Between '2008' AND '2009'
AND MNTH Between '12' AND '1'
This example shows you how to fill column B based on the the volume of data in Column A. Adjust "A1" accordingly to your needs. It will fill in column B based on the formula in B1.
Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown
Since jQuery.get is just a shorthand for jQuery.ajax, another way would be to use the latter one's context
option, as stated in the documentation:
The
this
reference within all callbacks is the object in the context option passed to$.ajax
in the settings; if context is not specified, this is a reference to the Ajax settings themselves.
So you would use
$.ajax('http://www.example.org', {
dataType: 'xml',
data: {'a':1,'b':2,'c':3},
context: {
url: 'http://www.example.org'
}
}).done(function(xml) {alert(this.url});
If your table has relationship with other tables using its primary or foriegen key, may be it is impossible to alter your table. so you need to drop and create the table again.
To solve these problems you need to Generate Scripts by right click on the database and in advanced option set type of data to script to scheme and data. after that, using this script with the changing your column to identify and regenerate the table using run its query.
your query will be like here:
USE [Db_YourDbName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Drop TABLE [dbo].[Tbl_TourTable]
CREATE TABLE [dbo].[Tbl_TourTable](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[Family] [nvarchar](150) NULL)
GO
SET IDENTITY_INSERT [dbo].[Tbl_TourTable] ON
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
SET IDENTITY_INSERT [dbo].[Tbl_TourTable] off
Use finish
like this:
Intent i = new Intent(Main_Menu.this, NextActivity.class);
finish(); //Kill the activity from which you will go to next activity
startActivity(i);
FLAG_ACTIVITY_NO_HISTORY
you can use in case for the activity you want to finish. For exampe you are going from A-->B--C. You want to finish activity B when you go from B-->C so when you go from A-->B you can use this flag. When you go to some other activity this activity will be automatically finished.
To learn more on using Intent.FLAG_ACTIVITY_NO_HISTORY
read: http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NO_HISTORY
I'm developing with android studio 2+.
to create class diagrams I did the following: - install "ObjectAid UML Explorer" as plugin for eclipse(in my case luna with android sdk but works with younger versions as well) ... go to eclipse marketplace and search for "ObjectAid UML Explorer". it's further down in the search results. after installation and restart of eclipse ...
open an empty android or what-ever-java-project in eclipse. then right click on the empty eclipse project in the project explorer -> select 'build path' then I link my ANDROID STUDIO SRC PATH into my eclipse android project. doesn't matter if there are errors. again right click on the eclipse-android project and select: New in the filter type 'class' then you should see among others an option 'class diagram' ... select it and confgure it ... png stuff, visibility, etc. drag/drop your ANDROID STUDIO project classes into the open diagram -> voila :)
hth
I open eclipse(luna, but that doesn't matter).
I got the "ObjectAid UML Explorer"
that installed I open an empty android project oin eclipse, right
In oracle, generally speaking, there are number of facts that I will mention in following section:
Therefore, your question, "to see all tablespaces and datafiles belong to SCOTT" is s bit wrong.
However, there are some DBA views encompass information about all database objects, regardless of the owner. Only users with DBA privileges can access these views: DBA_DATA_FILES, DBA_TABLESPACES, DBA_FREE_SPACE, DBA_SEGMENTS.
So, connect to your DB as sysdba and run query through these helpful views. For example this query can help you to find all tablespaces and their data files that objects of your user are located:
SELECT DISTINCT sgm.TABLESPACE_NAME , dtf.FILE_NAME
FROM DBA_SEGMENTS sgm
JOIN DBA_DATA_FILES dtf ON (sgm.TABLESPACE_NAME = dtf.TABLESPACE_NAME)
WHERE sgm.OWNER = 'SCOTT'
In the spring boot reference,it said:
When a class doesn’t include a package declaration it is considered to be in the “default package”. The use of the “default package” is generally discouraged, and should be avoided. It can cause particular problems for Spring Boot applications that use @ComponentScan, @EntityScan or @SpringBootApplication annotations, since every class from every jar, will be read.
com
+- example
+- myproject
+- Application.java
|
+- domain
| +- Customer.java
| +- CustomerRepository.java
|
+- service
| +- CustomerService.java
|
+- web
+- CustomerController.java
In your cases. You must add scanBasePackages
in the @SpringBootApplication
annotation.just like@SpringBootApplication(scanBasePackages={"domain","contorller"..})
You need to store all of the extra rows in the files in your dictionary, not just one of them:
dict1 = {row[0]: row[1:] for row in r}
...
dict2 = {row[0]: row[1:] for row in r}
Then, since the values in the dictionaries are lists, you need to just concatenate the lists together:
w.writerows([[key] + dict1.get(key, []) + dict2.get(key, []) for key in keys])
this is not a regex solution.
alist={"I love ":""He loves"","Je t'aime ":"Il aime","Ich liebe ":"Er liebt"}
for k in alist.keys():
if k in statement:
print alist[k],statement.split(k)[1:]
Observation
Try this :
var feed = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};_x000D_
_x000D_
var data = [];_x000D_
data.push(feed);_x000D_
_x000D_
console.log(data);
_x000D_
Instead of :
var my_json = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};_x000D_
_x000D_
var data = [];_x000D_
for(var i in my_json) {_x000D_
data.push(my_json[i]);_x000D_
}_x000D_
_x000D_
console.log(data);
_x000D_
If you want to update your project using SVN then first of all:
Go to the path on which your project is stored through command prompt.
Use the command SVN update
That's it.
border:2px soild #eee;
margin: 15px 15px;
-webkit-box-shadow: 2px 3px 8px #eee;
-moz-box-shadow: 2px 3px 8px #eee;
box-shadow: 2px 3px 8px #eee;
box-shadow requires you to set the horizontal & vertical offsets, you can then optionally set the blur and colour, you can also choose to have the shadow inset instead of the default outset. Colour can be defined as hex or rgba.
box-shadow : inset/outset h-offset v-offset blur spread color;
Explanation of the values...
inset/outset -- whether the shadow is inside or outside the box. If not specified it will default to outset.
h-offset -- the horizontal offset of the shadow (required value)
v-offset -- the vertical offset of the shadow (required value)
blur -- as it says, the blur of the shadow
spread -- moves the shadow away from the box equally on all sides. A positive value causes the shadow to expand, negative causes it to contract. Though this value isn't often used, it is useful with multiple shadows.
color -- as it says, the color of the shadow
box-shadow:2px 3px 8px #eee; a gray shadow with a horizontal outset of 2px, vertical of 3px and a blur of 8px
You should set a TimeZone in your DateFormat, otherwise it will use the default one (depending on the settings of the computer).
A good way to do it without getting the view involved may be:
$.ajax({
type: "POST",
url: '/Controller/Search',
data: { queryString: searchVal },
success: function (data) {
alert("here" + data.d.toString());
}
});
This will try to POST to the URL:
"http://domain/Controller/Search (which is the correct URL for the action you want to use)"
You also can get some benefit using knitr and puting your script in Rmd chuncks.
I usually divide the code in different chunks and select which one will save a checkpoint to cache or to a RDS file, and
Over there you can set a chunk to be saved to "cache", or you can decide to run or not a particular chunk. In this way, in a first run you can process only "part 1", another execution you can select only "part 2", etc.
Example:
part1
```{r corpus, warning=FALSE, cache=TRUE, message=FALSE, eval=TRUE}
corpusTw <- corpus(twitter) # build the corpus
```
part2
```{r trigrams, warning=FALSE, cache=TRUE, message=FALSE, eval=FALSE}
dfmTw <- dfm(corpusTw, verbose=TRUE, removeTwitter=TRUE, ngrams=3)
```
As a side effect, this also could save you some headaches in terms of reproducibility :)
You can do something like this:
// show loading image
$('#loader_img').show();
// main image loaded ?
$('#main_img').on('load', function(){
// hide/remove the loading image
$('#loader_img').hide();
});
You assign load
event to the image which fires when image has finished loading. Before that, you can show your loader image.
<script src="/assets/backend/js/html2canvas.min.js"></script>
<script>
$("#download").on('click', function(){
html2canvas($("#printform"), {
onrendered: function (canvas) {
var url = canvas.toDataURL();
var triggerDownload = $("<a>").attr("href", url).attr("download", getNowFormatDate()+"????????.jpeg").appendTo("body");
triggerDownload[0].click();
triggerDownload.remove();
}
});
})
</script>
this is what i used:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];
NSDate *now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];
NSLog(@"\n"
"theDate: |%@| \n"
"theTime: |%@| \n"
, theDate, theTime);
[dateFormat release];
[timeFormat release];
[now release];
Count and show keys in a dictionary (run in console):
o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")
Sample output:
"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"
Simple count function:
function size_dict(d){c=0; for (i in d) ++c; return c}
just simply (PowerShell V5)
Get-ChildItem "C:\temp" -Recurse -File | Where CreationTime -lt (Get-Date).AddDays(-15) | Remove-Item -Force
Something to be aware of, the $_SESSION
variables are still set in the same page after calling session_destroy()
where as this is not the case when using unset($_SESSION)
or $_SESSION = array()
. Also, unset($_SESSION)
blows away the $_SESSION
superglobal so only do this when you're destroying a session.
With all that said, it's best to do like the PHP docs has it in the first example for session_destroy()
.
Make sure WindowManager.LayoutParams.TYPE_SYSTEM_ERROR
is added for OS version < Oreo as it's been deprecated.
The (currently) accepted answer by Jerub is correct for python2, but incorrect and may produce garbled results (as Apalala points out in a comment to that solution), for python3. That's because the unicode_escape codec requires its source to be coded in latin-1, not utf-8, as per the official python docs. Hence, in python3 use:
>>> myString="špåm\\nëðþ\\x73"
>>> print(myString)
špåm\nëðþ\x73
>>> decoded_string = myString.encode('latin-1','backslashreplace').decode('unicode_escape')
>>> print(decoded_string)
špåm
ëðþs
This method also avoids the extra unnecessary roundtrip between strings and bytes in metatoaster's comments to Jerub's solution (but hats off to metatoaster for recognizing the bug in that solution).
Good practice to work with SQL Server.
Create below stored procedure and set short key,
CREATE PROCEDURE [dbo].[Searchinall]
(@strFind AS VARCHAR(MAX))
AS
BEGIN
SET NOCOUNT ON;
--TO FIND STRING IN ALL PROCEDURES
BEGIN
SELECT OBJECT_NAME(OBJECT_ID) SP_Name
,OBJECT_DEFINITION(OBJECT_ID) SP_Definition
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%'+@strFind+'%'
END
--TO FIND STRING IN ALL VIEWS
BEGIN
SELECT OBJECT_NAME(OBJECT_ID) View_Name
,OBJECT_DEFINITION(OBJECT_ID) View_Definition
FROM sys.views
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%'+@strFind+'%'
END
--TO FIND STRING IN ALL FUNCTION
BEGIN
SELECT ROUTINE_NAME Function_Name
,ROUTINE_DEFINITION Function_definition
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%'+@strFind+'%'
AND ROUTINE_TYPE = 'FUNCTION'
ORDER BY
ROUTINE_NAME
END
--TO FIND STRING IN ALL TABLES OF DATABASE.
BEGIN
SELECT t.name AS Table_Name
,c.name AS COLUMN_NAME
FROM sys.tables AS t
INNER JOIN sys.columns c
ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%'+@strFind+'%'
ORDER BY
Table_Name
END
END
Now - Set short key as below,
So next time whenever you want to find a particular text in any of the four objects like Store procedure
, Views
, Functions
and Tables
. You just need to write that keyword and press shortcut key.
For example: I want to search 'PaymentTable' then write 'PaymentTable' and make sure you select or highlight the written keyword in query editor and press shortcut key ctrl+4
- it will provide you full result.
Command + Space
Search for Xcode
Open it and accept license
Then run again from terminal xcode-select --install
Depending on the type of input types you're using on your form, you should be able to grab them using standard jQuery expressions.
Example:
// change forms[0] to the form you're trying to collect elements from... or remove it, if you need all of them
var input_elements = $("input, textarea", document.forms[0]);
Check out the documentation for jQuery expressions on their site for more info: http://docs.jquery.com/Core/jQuery#expressioncontext
Changing to Varchar(1200) from Varchar(200) should cause you no issue as it is only a metadata change and as SQL server 2008 truncates excesive blank spaces you should see no performance differences either so in short there should be no issues with making the change.
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
this deletes test.blue
I believe this can help you:
$(document).ready(function(){
var temp = {someKey:"temp value", otherKey:"other value", fooKey:"some value"};
for (var key in temp) {
alert('<option value=' + key + '>' + temp[key] + '</option>');
}
});
With argc
(argument count) and argv
(argument vector) you can get the number and the values of passed arguments when your application has been launched.
This way you can use parameters (such as -version
) when your application is started to act a different way.
But you can also use int main(void)
as a prototype in C.
There is a third (less known and nonstandard) prototype with a third argument which is envp
. It contains environment variables.
Resources:
Mehrdad makes some good points, but the main thing I noticed is that you never run the query...
SqlParameter retval = sqlcomm.Parameters.Add("@b", SqlDbType.VarChar);
retval.Direction = ParameterDirection.ReturnValue;
sqlcomm.ExecuteNonQuery(); // MISSING
string retunvalue = (string)sqlcomm.Parameters["@b"].Value;
Consider the following code:
class X():
def __init__(self):
print("X")
class Y(X):
def __init__(self):
# X.__init__(self)
super(Y, self).__init__()
print("Y")
class P(X):
def __init__(self):
super(P, self).__init__()
print("P")
class Q(Y, P):
def __init__(self):
super(Q, self).__init__()
print("Q")
Q()
If change constructor of Y
to X.__init__
, you will get:
X
Y
Q
But using super(Y, self).__init__()
, you will get:
X
P
Y
Q
And P
or Q
may even be involved from another file which you don't know when you writing X
and Y
. So, basically, you won't know what super(Child, self)
will reference to when you are writing class Y(X)
, even the signature of Y is as simple as Y(X)
. That's why super could be a better choice.
MORE ANSWERS! Here is the solution i used
\"([^\"]*?icon[^\"]*?)\"
TLDR;
replace the word icon with what your looking for in said quotes and voila!
The way this works is it looks for the keyword and doesn't care what else in between the quotes.
EG:
id="fb-icon"
id="icon-close"
id="large-icon-close"
the regex looks for a quote mark "
then it looks for any possible group of letters thats not "
until it finds icon
and any possible group of letters that is not "
it then looks for a closing "
Complete example:
<select name="hall" id="hall"> _x000D_
<option> _x000D_
1 _x000D_
</option> _x000D_
<option> _x000D_
2 _x000D_
</option> _x000D_
<option selected> _x000D_
3 _x000D_
</option> _x000D_
<option> _x000D_
4 _x000D_
</option> _x000D_
<option> _x000D_
5 _x000D_
</option> _x000D_
</select>
_x000D_
I had the same error due to a typo in the service name, i was trying to delete the service display name instead of the service name. Once I used the right service name it worked fine
Just use JavaScript. Then compatible with most and older browsers. Use the escape sequence \n for newline.
document.getElementById("ElementID").title = 'First Line text \n Second line text'
I use AutoMapper for this. It works like this:
Mapper.CreateMap(typeof(Person), typeof(Person));
Mapper.Map(a, b);
Now person a has all the properties of person b.
As an aside, AutoMapper works for differing objects as well. For more information, check it out at http://automapper.org
Update: I use this syntax now (simplistically - really the CreateMaps are in AutoMapper profiles):
Mapper.CreateMap<Person, Person>;
Mapper.Map(a, b);
Note that you don't have to do a CreateMap to map one object of the same type to another, but if you don't, AutoMapper will create a shallow copy, meaning to the lay man that if you change one object, the other changes also.
Had the same error while using SourceTree connected to BitBucket repository.
When navigating to repository url on bitbucket.org the warning message appeared:
This repository is in read-only mode. You caught us doing some quick maintenance.
After around 2 hours repository was accessible again.
You can check status and uptime of bitbucket here: http://status.bitbucket.org/
You can do do it. The input type submit should be inside of a form. Then all you have to do is write the link you want to redirect to inside the action attribute that is inside the form tag.
I got this error because I didn't specify the correct programmer in the avrdude command line. You have to specify "-c arduino" if you are using an Arduino board.
This example command reads the status of the hfuse:
avrdude -c arduino -P /dev/ttyACM0 -p atmega328p -U hfuse:r:-:h
In day to day, practical programming terms, the biggest difference is in the fact that with SOAP you are working with static and strongly defined data exchange formats where as with REST and JSON data exchange formatting is very loose by comparison. For example with SOAP you can validate that exchanged data matches an XSD schema. The XSD therefore serves as a 'contract' on how the client and the server are to understand how the data being exchanged must be structured.
JSON data is typically not passed around according to a strongly defined format (unless you're using a framework that supports it .. e.g. http://msdn.microsoft.com/en-us/library/jj870778.aspx or implementing json-schema).
In-fact, some (many/most) would argue that the "dynamic" secret sauce of JSON goes against the philosophy/culture of constraining it by data contracts (Should JSON RESTful web services use data contract)
People used to working in dynamic loosely typed languages tend to feel more comfortable with the looseness of JSON while developers from strongly typed languages prefer XML.
I found this approach which parse JSON into a dynamic object, it extends a DynamicObject
and JavascriptConverter
to turn the string into an object.
DynamicJsonObject
public class DynamicJsonObject : DynamicObject
{
private IDictionary<string, object> Dictionary { get; set; }
public DynamicJsonObject(IDictionary<string, object> dictionary)
{
this.Dictionary = dictionary;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = this.Dictionary[binder.Name];
if (result is IDictionary<string, object>)
{
result = new DynamicJsonObject(result as IDictionary<string, object>);
}
else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>)
{
result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>)));
}
else if (result is ArrayList)
{
result = new List<object>((result as ArrayList).ToArray());
}
return this.Dictionary.ContainsKey(binder.Name);
}
}
Converter
public class DynamicJsonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
if (type == typeof(object))
{
return new DynamicJsonObject(dictionary);
}
return null;
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); }
}
}
Usage (sample json):
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });
dynamic glossaryEntry = jss.Deserialize(json, typeof(object)) as dynamic;
Console.WriteLine("glossaryEntry.glossary.title: " + glossaryEntry.glossary.title);
Console.WriteLine("glossaryEntry.glossary.GlossDiv.title: " + glossaryEntry.glossary.GlossDiv.title);
Console.WriteLine("glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.ID: " + glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.ID);
Console.WriteLine("glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.para: " + glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.para);
foreach (var also in glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso)
{
Console.WriteLine("glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso: " + also);
}
This method has to return true, otherwise it will throw an error. E.g. you can throw an error if a key does not exist.
Returning true
and emptying result
will return an empty value rather than throwing an error.
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (!this.Dictionary.ContainsKey(binder.Name))
{
result = "";
}
else
{
result = this.Dictionary[binder.Name];
}
if (result is IDictionary<string, object>)
{
result = new DynamicJsonObject(result as IDictionary<string, object>);
}
else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>)
{
result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>)));
}
else if (result is ArrayList)
{
result = new List<object>((result as ArrayList).ToArray());
}
return true; // this.Dictionary.ContainsKey(binder.Name);
}
I think you need to wrap the inputs inside a col-lg-4
, and then inside the form-group
and it all gets contained in a form-horizontal
..
<form class="form form-horizontal">
<div class="form-group">
<div class="col-md-3">
<label>Email</label>
<input type="email" class="form-control" id="email" placeholder="email">
</div>
</div>
...
</form>
EDIT: From the Bootstrap 3 docs..
Inputs, selects, and textareas are 100% wide by default in Bootstrap. To use the inline form, you'll have to set a width on the form controls used within.
So another option is to set a specific width using CSS:
.form-control {
width:100px;
}
Or, apply the col-sm-*
to the `form-group'.
Will not necessarily work
Backup / Restore - will not work when the target is an earlier MS SQL version.
Copy Database - will not work when the target is SQL Server Express: "The destination server cannot be a SQL Server 2005 or later Express instance."
Data import - Will not copy the schema.
Will work
Script generation - Tasks -> Generate Scripts. Make sure you set the desired target SQL Server version on the Set Scripting Options -> Advanced page. You can also choose there whether to copy schema, data, or both. Note that in the generated script, you may need to change the DATA folder for the mdf/ldf files if moving from non-express to express or vice versa.
Microsoft SQL Server Database Publishing Services - comes with SQL Server 2005 and above, I think. Download the latest version from here. Prerequisites: sqlncli.msi
/sqlncli_x64.msi
/sqlncli_ia64.msi
, SQLServer2005_XMO.msi
/SQLServer2005_XMO_x64.msi
/SQLServer2005_XMO_ia64.msi
(download here).
I think you want to return a REFCURSOR:
create function test_cursor
return sys_refcursor
is
c_result sys_refcursor;
begin
open c_result for
select * from dual;
return c_result;
end;
Update: If you need to call this from SQL, use a table function like @Tony Andrews suggested.
You need to use
<?php bloginfo('template_directory'); ?>
It returns the directory of the current WordPress theme.
Now for example, if your theme has some image named example.jpg
inside some folder name subfolder
folder in the images
folder.
themes
|-> your theme
|-> images
|->subfolder
|-> examples.jpg
You access it like this
<img class="article-image" src="<?php bloginfo('template_directory'); ?> /images/subfolder/example.jpg" border="0" alt="">
If you're trying to just count how many of your cells in a range are not blank try this:
=COUNTA(range)
Example: (assume that it starts from A1 downwards):
---------
Something
---------
Something
---------
---------
Something
---------
---------
Something
---------
=COUNTA(A1:A6)
returns 4
since there are two blank cells in there.
#!/bin/bash
CURL='/usr/bin/curl'
RVMHTTP="https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer"
CURLARGS="-f -s -S -k"
# you can store the result in a variable
raw="$($CURL $CURLARGS $RVMHTTP)"
# or you can redirect it into a file:
$CURL $CURLARGS $RVMHTTP > /tmp/rvm-installer
or:
Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";
// use the built in Json deserializer to convert the string to a list of Person objects
var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);
foreach (var person in people)
{
Console.WriteLine(person.Name + " is " + person.Age + " years old.");
}
}
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
}
}
new AsyncRoute({path: '/demo/:demoKey1/:demoKey2', loader: () => {
return System.import('app/modules/demo/demo').then(m =>m.demoComponent);
}, name: 'demoPage'}),
export class demoComponent {
onClick(){
this._router.navigate( ['/demoPage', {demoKey1: "123", demoKey2: "234"}]);
}
}
Most layout managers work best with a component's preferredSize, and most GUI's are best off allowing the components they contain to set their own preferredSizes based on their content or properties. To use these layout managers to their best advantage, do call pack()
on your top level containers such as your JFrames before making them visible as this will tell these managers to do their actions -- to layout their components.
Often when I've needed to play a more direct role in setting the size of one of my components, I'll override getPreferredSize and have it return a Dimension that is larger than the super.preferredSize (or if not then it returns the super's value).
For example, here's a small drag-a-rectangle app that I created for another question on this site:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MoveRect extends JPanel {
private static final int RECT_W = 90;
private static final int RECT_H = 70;
private static final int PREF_W = 600;
private static final int PREF_H = 300;
private static final Color DRAW_RECT_COLOR = Color.black;
private static final Color DRAG_RECT_COLOR = new Color(180, 200, 255);
private Rectangle rect = new Rectangle(25, 25, RECT_W, RECT_H);
private boolean dragging = false;
private int deltaX = 0;
private int deltaY = 0;
public MoveRect() {
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseListener(myMouseAdapter);
addMouseMotionListener(myMouseAdapter);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (rect != null) {
Color c = dragging ? DRAG_RECT_COLOR : DRAW_RECT_COLOR;
g.setColor(c);
Graphics2D g2 = (Graphics2D) g;
g2.draw(rect);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private class MyMouseAdapter extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
Point mousePoint = e.getPoint();
if (rect.contains(mousePoint)) {
dragging = true;
deltaX = rect.x - mousePoint.x;
deltaY = rect.y - mousePoint.y;
}
}
@Override
public void mouseReleased(MouseEvent e) {
dragging = false;
repaint();
}
@Override
public void mouseDragged(MouseEvent e) {
Point p2 = e.getPoint();
if (dragging) {
int x = p2.x + deltaX;
int y = p2.y + deltaY;
rect = new Rectangle(x, y, RECT_W, RECT_H);
MoveRect.this.repaint();
}
}
}
private static void createAndShowGui() {
MoveRect mainPanel = new MoveRect();
JFrame frame = new JFrame("MoveRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Note that my main class is a JPanel, and that I override JPanel's getPreferredSize:
public class MoveRect extends JPanel {
//.... deleted constants
private static final int PREF_W = 600;
private static final int PREF_H = 300;
//.... deleted fields and constants
//... deleted methods and constructors
@Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
Also note that when I display my GUI, I place it into a JFrame, call pack();
on the JFrame, set its position, and then call setVisible(true);
on my JFrame:
private static void createAndShowGui() {
MoveRect mainPanel = new MoveRect();
JFrame frame = new JFrame("MoveRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
If you know there are three li's in the list you're looking at, for example, you could do this:
li + li + li { /* Selects third to last li */
}
In IE6 you can use expressions:
li {
color: expression(this.previousSibling ? 'red' : 'green'); /* 'green' if last child */
}
I would recommend using a specialized class or Javascript (not IE6 expressions), though, until the :last-child
selector gets better support.
It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:
openssl sha1 [put the full path to the file here without brackets]
For example:
openssl sha1 /Users/me/Desktop/myFile.dmg
If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.
clock()
-> floating point number
Return the CPU time or real time since the start of the process or since
the first call to clock()
. This has as much precision as the system
records.
time()
-> floating point number
Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them.
Usually time()
is more precise, because operating systems do not store the process running time with the precision they store the system time (ie, actual time)
I tried the above and adding the registry keys to the LOCALMACHINE was not getting the job done. So in case you are still stuck , try this.
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\SOFTWARE\Python]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\Help]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\Help\Main Python Documentation] @="C:\Python27\Doc\python272.chm"
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\InstallPath] @="C:\Python27\"
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\InstallPath\InstallGroup] @="Python 2.7"
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\Modules]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\PythonPath] @="C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk"
Copy paste the above in notepad and save it as Python27.reg . Now run/merge the file as mentioned in the answers above. (Make sure the paths of Python installation are corrected as per your installation.
It simply does ,what the above answers suggest for a local machine ,to the current user.
This may not be an option for you, but if you can use the Parallel Extension for .NET then you could use Task
s instead of raw threads and then use Task.WaitAll()
to wait for them to complete.
To set image cource in imageview you can use any of the following ways. First confirm your image is present in which format.
If you have image in the form of bitmap then use
imageview.setImageBitmap(bm);
If you have image in the form of drawable then use
imageview.setImageDrawable(drawable);
If you have image in your resource example if image is present in drawable folder then use
imageview.setImageResource(R.drawable.image);
If you have path of image then use
imageview.setImageURI(Uri.parse("pathofimage"));
-Xms initial heap size for the startup, however, during the working process the heap size can be less than -Xms due to users' inactivity or GC iterations. This is not a minimal required heap size.
-Xmx maximal heap size
Declare a global var:
var td
Then select your guiena pig <td>
getting it by its id
, if you want to change all of them then
window.onload = function () {
td = document.getElementsByTagName("td");
}
Make a function to be triggered and a loop to change all of your desired td
's
function trigger() {
for(var x = 0; x < td.length; x++) {
td[x].className = "yournewclass";
}
}
Go to your CSS Sheet:
.yournewclass:hover { background-color: #00ff00; }
And that is it, with this you are able to to make all your <td>
tags get a background-color: #00ff00;
when hovered by changing its css propriety directly (switching between css classes).
You probably need to add the namespace:
<Window x:Class="UserControlTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:UserControlTest"
Title="User Control Test" Height="300" Width="300">
<local:UserControl1 />
</Window>
VS 2010 Express is no longer linked to any VS Express pages (that I found). I did find this link to the ISO which I used and it fixed the errors mentioned here.
http://download.microsoft.com/download/1/E/5/1E5F1C0A-0D5B-426A-A603-1798B951DDAE/VS2010Express1.iso
Note: Also make sure you have x86 everything (Python + Postgresql) or you'll get other errors. I did not try x64 everything.
Just as a notice. I made a test function for my spreadsheet. I use the variable google throws in the onEdit(e) function (I called it e). Then I made a test function like this:
function test(){
var testRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GetItemInfoSheetName).getRange(2,7)
var testObject = {
range:testRange,
value:"someValue"
}
onEdit(testObject)
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GetItemInfoSheetName).getRange(2,6).setValue(Logger.getLog())
}
Calling this test function makes all the code run as you had an event in the spreadsheet. I just put in the possision of the cell i edited whitch gave me an unexpected result, setting value as the value i put into the cell. OBS! for more variables googles gives to the function go here: https://developers.google.com/apps-script/guides/triggers/events#google_sheets_events
spring boot allows us to write different profiles to write for different environments, for example we can have separate properties files for production, qa and local environments
application-local.properties file with configurations according to my local machine is
spring.profiles.active=local
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=users
spring.data.mongodb.username=humble_freak
spring.data.mongodb.password=freakone
spring.rabbitmq.host=localhost
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.port=5672
rabbitmq.publish=true
Similarly, we can write application-prod.properties and application-qa.properties as many properties files as we want
then write some scripts to start the application for different environments, for e.g.
mvn spring-boot:run -Drun.profiles=local
mvn spring-boot:run -Drun.profiles=qa
mvn spring-boot:run -Drun.profiles=prod
This saves the data in a list of lists.
text = open("filetest.txt", "r")
data = [ ]
for line in text:
data.append( line.strip().split() )
print "number of lines ", len(data)
print "number of columns ", len(data[0])
print "element in first row column two ", data[0][1]
With VS 2017, debugging ASP.NET project with Chrome doesn't sign you in with your Google account.
To fix that go to Tools -> Options -> Debugging -> General and turn off the setting Enable JavaScript Debugging for ASP.NET (Chrome and IE).
Adding Allow from All
didn't worked for me. Then I tried this and it worked.
OS: Windows 8.1
Wamp : 2.5
I added this in the file C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "c:/wamp/www/"
ServerName localhost
ServerAlias localhost
ErrorLog "logs/localhost-error.log"
CustomLog "logs/localhost-access.log" common
</VirtualHost>
int var1 = int.Parse(ds.Tables[0].Rows[0][3].ToString());
int var2 = int.Parse(ds.Tables[0].Rows[0][4].ToString());
It's rather difficult to give a practical answer because the difference is about the language definition itself. It's possible to build an interpreter for every compiled language, but it's not possible to build an compiler for every interpreted language. It's very much about the formal definition of a language. So that theoretical informatics stuff noboby likes at university.
Try this:
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Although Justin grant's solution appears solid I found that when you have a number of duplicate values within a given partition key the row numbers for the ASC duplicate values end up out of sequence so they do not properly align.
Here is a fragment from my result:
KEY VALUE ROWA ROWD
13 2 22 182
13 1 6 183
13 1 7 184
13 1 8 185
13 1 9 186
13 1 10 187
13 1 11 188
13 1 12 189
13 0 1 190
13 0 2 191
13 0 3 192
13 0 4 193
13 0 5 194
I used Justin's code as the basis for this solution. Although not as efficient given the use of multiple derived tables it does resolve the row ordering problem I encountered. Any improvements would be welcome as I am not that experienced in T-SQL.
SELECT PKEY, cast(AVG(VALUE)as decimal(5,2)) as MEDIANVALUE
FROM
(
SELECT PKEY,VALUE,ROWA,ROWD,
'FLAG' = (CASE WHEN ROWA IN (ROWD,ROWD-1,ROWD+1) THEN 1 ELSE 0 END)
FROM
(
SELECT
PKEY,
cast(VALUE as decimal(5,2)) as VALUE,
ROWA,
ROW_NUMBER() OVER (PARTITION BY PKEY ORDER BY ROWA DESC) as ROWD
FROM
(
SELECT
PKEY,
VALUE,
ROW_NUMBER() OVER (PARTITION BY PKEY ORDER BY VALUE ASC,PKEY ASC ) as ROWA
FROM [MTEST]
)T1
)T2
)T3
WHERE FLAG = '1'
GROUP BY PKEY
ORDER BY PKEY
I would recommend looking into conditional comments and making a separate sheet for the IEs you are having problems with.
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="ie7.css" />
<![endif]-->
What is wrong with using string.Length?
// len will be 5
int len = "Hello".Length;
It depends which version of C# you're using, from version 3.0 onwards you can use...
List<string> nameslist = new List<string> { "one", "two", "three" };
Only stopped containers can be listed using:
docker ps --filter "status=exited"
or
docker ps -f "status=exited"
Provide a format string:
date +"%H:%M"
Running man date
will give all the format options
%a locale's abbreviated weekday name (e.g., Sun)
%A locale's full weekday name (e.g., Sunday)
%b locale's abbreviated month name (e.g., Jan)
%B locale's full month name (e.g., January)
%c locale's date and time (e.g., Thu Mar 3 23:05:25 2005)
%C century; like %Y, except omit last two digits (e.g., 20)
%d day of month (e.g., 01)
%D date; same as %m/%d/%y
%e day of month, space padded; same as %_d
%F full date; same as %Y-%m-%d
%g last two digits of year of ISO week number (see %G)
%G year of ISO week number (see %V); normally useful only with %V
%h same as %b
%H hour (00..23)
%I hour (01..12)
%j day of year (001..366)
%k hour, space padded ( 0..23); same as %_H
%l hour, space padded ( 1..12); same as %_I
%m month (01..12)
%M minute (00..59)
%n a newline
%N nanoseconds (000000000..999999999)
%p locale's equivalent of either AM or PM; blank if not known
%P like %p, but lower case
%r locale's 12-hour clock time (e.g., 11:11:04 PM)
%R 24-hour hour and minute; same as %H:%M
%s seconds since 1970-01-01 00:00:00 UTC
%S second (00..60)
%t a tab
%T time; same as %H:%M:%S
%u day of week (1..7); 1 is Monday
%U week number of year, with Sunday as first day of week (00..53)
%V ISO week number, with Monday as first day of week (01..53)
%w day of week (0..6); 0 is Sunday
%W week number of year, with Monday as first day of week (00..53)
%x locale's date representation (e.g., 12/31/99)
%X locale's time representation (e.g., 23:13:48)
%y last two digits of year (00..99)
%Y year
%z +hhmm numeric time zone (e.g., -0400)
%:z +hh:mm numeric time zone (e.g., -04:00)
%::z +hh:mm:ss numeric time zone (e.g., -04:00:00)
%:::z numeric time zone with : to necessary precision (e.g., -04, +05:30)
%Z alphabetic time zone abbreviation (e.g., EDT)
Depending on the version of HTML you're catering to:
HTML 5 states that the <a>
element "may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links)".
HTML 4.01 specifies that <a>
elements may only contain inline elements. A <div>
is a block element, so it may not appear inside an <a>
.
Of course you are at liberty to style an inline element such that it appears to be a block, or indeed style a block so that it is rendered inline. The use of the terms inline
and block
in HTML refers to the relationship of the elements to the semantic structure of the document, whereas the same terms in CSS are related more to the visual styling of the elements. If you make inline elements display in a blocky manner, that's fine.
However you should ensure that the structure of the document still makes sense when CSS is not present, for example when accessed via an assistive technology such as a screen reader - or indeed when examined by the mighty Googlebot.
Actually you have three steps because the local branch has a duplicate on the server so we have one step for local on two steps on the server:
git branch -m <old-branch-name> <new-branch-name>
git push <remote-name[origin by default]> :<old-branch-name>
git push -u <new-branch-name>
In phpMyAdmin 4.0, you go to Status > Monitor. In there you can enable the slow query log and general log, see a live monitor, select a portion of the graph, see the related queries and analyse them.
First string date is converted to js date format and converted into string format again, then it is compared with original string.
function dateValidation(){
var dateString = "34/05/2019"
var dateParts = dateString.split("/");
var date= new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);
var isValid = isValid( dateString, date );
console.log("Is valid date: " + isValid);
}
function isValidDate(dateString, date) {
var newDateString = ( date.getDate()<10 ? ('0'+date.getDate()) : date.getDate() )+ '/'+ ((date.getMonth() + 1)<10? ('0'+(date.getMonth() + 1)) : (date.getMonth() + 1) ) + '/' + date.getFullYear();
return ( dateString == newDateString);
}
Following the answer from this issue, you must call Menu.setApplicationMenu(null)
before the window is created
I faced the very same error when I was trying to connect to my SQL Server 2014 instance using sa
user using SQL Server Management Studio (SSMS). I was facing this error even when security settings for sa
user was all good and SQL authentication mode was enabled on the SQL Server instance.
Finally, the issue turned out to be that Named Pipes
protocol was disabled. Here is how you can enable it:
Open SQL Server Configuration Manager application from start menu. Now, enable Named Pipes
protocol for both Client Protocols
and Protocols for <SQL Server Instance Name>
nodes as shown in the snapshot below:
Note: Make sure you restart the SQL Server instance after making changes.
P.S. I'm not very sure but there is a possibility that the Named Pipes
enabling was required under only one of the two nodes that I've advised. So you can try it one after the other to reach to a more precise solution.
New in C# 8.0 you can use the so-called "hat" (^) operator! This is useful for when you want to do something in one line!
var mystr = "Hello World!";
var lastword = mystr.Split(" ")[^1];
Console.WriteLine(lastword);
// World!
instead of the old way:
var mystr = "Hello World";
var split = mystr.Split(" ");
var lastword = split[split.Length - 1];
Console.WriteLine(lastword);
// World!
It doesn't save much space, but it looks much clearer (maybe I only think this because I came from python?). This is also much better than calling a method like .Last()
or .Reverse()
Read more at MSDN
Edit: You can add this functionality to your class like so:
public class MyClass
{
public object this[Index indx]
{
get
{
// Do indexing here, this is just an example of the .IsFromEnd property
if (indx.IsFromEnd)
{
Console.WriteLine("Negative Index!")
}
else
{
Console.WriteLine("Positive Index!")
}
}
}
}
The Index.IsFromEnd
will tell you if someone is using the 'hat' (^) operator
You can get a non-js-based redirection from an ajax call by putting in one of those meta refresh tags. This here seems to be working:
return Content("<meta http-equiv=\"refresh\" content=\"0;URL='" + @Url.Action("Index", "Home") + "'\" />");
Note: I discovered that meta refreshes are auto-disabled by Firefox, rendering this not very useful.
You can create a sub-interface for that special case:
interface Command extends Action<Void, Void> {
default Void execute(Void v) {
execute();
return null;
}
void execute();
}
It uses a default method to override the inherited parameterized method Void execute(Void)
, delegating the call to the simpler method void execute()
.
The result is that it's much simpler to use:
Command c = () -> System.out.println("Do nothing!");
this is the easiest way:
Make list
Select list
right click: Define Name (e.g. ItemStatus)
select a cell where the list should appear (copy paste can be done later, so not location critical)
Data > Data Validation
Allow: Select List
Source: =ItemStatus (don't forget the = sign)
click Ok
dropdown appears in the cell you selected
Home > Conditional Formatting
Manage Rules
New Rule
etc.
Using print
and JSON.stringify
you can simply produce a valid JSON
result.
Use --quiet
flag to filter shell noise from the output.
Use --norc
flag to avoid .mongorc.js
evaluation. (I had to do it because of a pretty-formatter that I use, which produces invalid JSON output)
Use DBQuery.shellBatchSize = ?
replacing ?
with the limit of the actual result to avoid paging.
And finally, use tee
to pipe the terminal output to a file:
// Shell:
mongo --quiet --norc ./query.js | tee ~/my_output.json
// query.js:
DBQuery.shellBatchSize = 2000;
function toPrint(data) {
print(JSON.stringify(data, null, 2));
}
toPrint(
db.getCollection('myCollection').find().toArray()
);
Hope this helps!
Steps:
Call JObject's ToString(Formatting.None)
method.
Alternatively if you pass the object to the JsonConvert.SerializeObject method it will return the JSON without formatting.
Documentation: Write JSON text with JToken.ToString
Angular 8+
You should add { static: false }
as a second option for @ViewChild
. This causes the query results to be resolved after change detection runs, allowing your @ViewChild
to be updated after the value changes.
Example:
export class AppComponent {
@ViewChild('contentPlaceholder', { static: false }) contentPlaceholder: ElementRef;
display = false;
constructor(private changeDetectorRef: ChangeDetectorRef) {
}
show() {
this.display = true;
this.changeDetectorRef.detectChanges(); // not required
console.log(this.contentPlaceholder);
}
}
Stackblitz example: https://stackblitz.com/edit/angular-d8ezsn
You could use the HTML5 Tag <mark>
:
<p>Enter the competition by
<mark class="red">January 30, 2011</mark> and you could win up to $$$$ — including amazing
<mark class="blue">summer</mark> trips!</p>
And use this in the CSS:
p {
font-size:14px;
color:#538b01;
font-weight:bold;
font-style:italic;
}
mark.red {
color:#ff0000;
background: none;
}
mark.blue {
color:#0000A0;
background: none;
}
The tag <mark>
has a default background color...at least in Chrome.
There is no float
type. Looks like you want float64
. You could also use float32
if you only need a single-precision floating point value.
package main
import "fmt"
func main() {
i := 5
f := float64(i)
fmt.Printf("f is %f\n", f)
}
Yes to your second and third questions -- that's what you need to do as you cannot have multiple 'lvalues' on the left of an assignment.
running your code hundred times may affect the camera to function wrongly.Your activity may be performing correctly but system could not buy it.so camera forces stop. One main tip all missed is rebooting your phone and not only eclipse..It worked for me..
In C++ you can declare a string like this:
#include <string>
using namespace std;
int main()
{
string str1("argue2000"); //define a string and Initialize str1 with "argue2000"
string str2 = "argue2000"; // define a string and assign str2 with "argue2000"
string str3; //just declare a string, it has no value
return 1;
}
This is the best video about Object-Oriented JavaScript on the internet:
The Definitive Guide to Object-Oriented JavaScript
Watch from beginning to end!!
Basically, Javascript is a Prototype-based language which is quite different than the classes in Java, C++, C#, and other popular friends. The video explains the core concepts far better than any answer here.
With ES6 (released 2015) we got a "class" keyword which allows us to use Javascript "classes" like we would with Java, C++, C#, Swift, etc.
Screenshot from the video showing how to write and instantiate a Javascript class/subclass:
Lets see an example with Select control
binded to: $scope.cboPais,
source: $scope.geoPaises
HTML
<select
ng-model="cboPais"
ng-options="item.strPais for item in geoPaises"
></select>
JavaScript
$http.get(strUrl2).success(function (response) {
if (response.length > 0) {
$scope.geoPaises = response; //Data source
nIndex = indexOfUnsortedArray(response, 'iPais', default_values.iPais); //array index of default value, using a custom function to search
if (nIndex >= 0) {
$scope.cboPais = response[nIndex]; //if index of array was found
} else {
$scope.cboPais = response[0]; //select the first element of array
}
$scope.geo_getDepartamentos();
}
}
COLLATE UTF8_GENERAL_CI
will work as ignore-case.
USE:
SELECT * from games WHERE title COLLATE UTF8_GENERAL_CI LIKE 'age of empires III%';
or
SELECT * from games WHERE LOWER(title) LIKE 'age of empires III%';
You can't really force the optimizer to do anything, but you can guide it.
UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93
gettimeofday will return time accurate to microseconds within the resolution of the system clock. You might also want to check out the High Res Timers project on SourceForge.
You could use linq.js
.
This allows to use aggregations and selectings from a data set of objects, as other structures data.
var data = [{ x: 2, y: 0 }, { x: 3, y: 1 }, { x: 4, y: 1 }];_x000D_
_x000D_
// SUM(X) WHERE Y > 0 -> 7_x000D_
console.log(Enumerable.From(data).Where("$.y > 0").Sum("$.x"));_x000D_
_x000D_
// LIST(X) WHERE Y > 0 -> [3, 4]_x000D_
console.log(Enumerable.From(data).Where("$.y > 0").Select("$.x").ToArray());
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>
_x000D_
python -m pip install -r requirements.txt
Referece: How to install packages using pip according to the requirements.txt file from a local directory?
You can use the DATE()
function to extract the date portion of the timestamp:
SELECT * FROM table
WHERE DATE(timestamp) = '2012-05-25'
Though, if you have an index on the timestamp column, this would be faster because it could utilize an index on the timestamp column if you have one:
SELECT * FROM table
WHERE timestamp BETWEEN '2012-05-25 00:00:00' AND '2012-05-25 23:59:59'
You can use the built in OnSelecting parameter of asp:SqlDataSource
Example: [.aspx file]
<asp:SqlDataSource ID="SqldsExample" runat="server"
SelectCommand="SELECT [SomeColumn], [AnotherColumn]
FROM [SomeTable]
WHERE [Dynamic_Variable_Column] = @DynamicVariable"
OnSelecting="SqldsExample_Selecting">
<SelectParameters>
<asp:Parameter Name="DynamicVariable" Type="String"/>
</SelectParameters>
Then in your code behind implement your OnSelecting method: [.aspx.cs]
protected void SqldsExample_Selecting(object sender, SqlDataSourceCommandEventArgs e)
{
e.Command.Parameters["@DynamicVariable"].Value = (whatever value you want);
}
You can also use this for the other types of DB operations just implement your own methods:
OnInserting="SqldsExample_Inserting"
OnUpdating="SqldsExample_Updating"
OnDeleting="SqldsExample_Deleting"
Don't know what exactly causes the issue.
A had several schemes, all could be build and install all of them and once, one didn't want (after what actions - don't know). In all unknown situations I execute:
npm run mac-reinstall
where in package.json
in scripts
section:
"mac-reinstall": "rm -rf -v package-lock.json ios/build ios/Podfile.lock android/.gradle android/build android/app/build node_modules && npm i && cd ios/ && rm -rf Pods/ && pod install && cd ../"
You can try to leave only Android's part from the script.
hg rollback
is what you want.
In TortoiseHg, the hg rollback
is accomplished in the commit dialog. Open the commit dialog and select "Undo".
It'll vary depending on resources, but you could run the script bellow and see for yourself ;)
<?php
$tests = 100000;
for ($i = 0; $i < $tests; $i++)
{
$string = md5(rand());
$position = rand(0, 31);
$start1 = microtime(true);
$char1 = $string[$position];
$end1 = microtime(true);
$time1[$i] = $end1 - $start1;
$start2 = microtime(true);
$char2 = substr($string, $position, 1);
$end2 = microtime(true);
$time2[$i] = $end2 - $start2;
$start3 = microtime(true);
$char3 = $string{$position};
$end3 = microtime(true);
$time3[$i] = $end3 - $start3;
}
$avg1 = array_sum($time1) / $tests;
echo 'the average float microtime using "array[]" is '. $avg1 . PHP_EOL;
$avg2 = array_sum($time2) / $tests;
echo 'the average float microtime using "substr()" is '. $avg2 . PHP_EOL;
$avg3 = array_sum($time3) / $tests;
echo 'the average float microtime using "array{}" is '. $avg3 . PHP_EOL;
?>
Some reference numbers (on an old CoreDuo machine)
$ php 1.php
the average float microtime using "array[]" is 1.914701461792E-6
the average float microtime using "substr()" is 2.2536706924438E-6
the average float microtime using "array{}" is 1.821768283844E-6
$ php 1.php
the average float microtime using "array[]" is 1.7251944541931E-6
the average float microtime using "substr()" is 2.0931363105774E-6
the average float microtime using "array{}" is 1.7225742340088E-6
$ php 1.php
the average float microtime using "array[]" is 1.7293763160706E-6
the average float microtime using "substr()" is 2.1037721633911E-6
the average float microtime using "array{}" is 1.7249774932861E-6
It seems that using the []
or {}
operators is more or less the same.
"By default, when an application calls DriverManager.getConnection(url, ...)
and the database specified in the URL does not yet exist, a new (empty) database is created."—H2 Database.
Addendum: @Thomas Mueller shows how to Execute SQL on Connection, but I sometimes just create and populate in the code, as suggested below.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/** @see http://stackoverflow.com/questions/5225700 */
public class H2MemTest {
public static void main(String[] args) throws Exception {
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
Statement st = conn.createStatement();
st.execute("create table customer(id integer, name varchar(10))");
st.execute("insert into customer values (1, 'Thomas')");
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("select name from customer");
while (rset.next()) {
String name = rset.getString(1);
System.out.println(name);
}
}
}
One option would be to read the data from the registry. MSDN Article On The Topic: http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.localmachine(v=vs.71).aspx)
The processors, I believe can be located here, HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor
private void determineNumberOfProcessCores()
{
RegistryKey rk = Registry.LocalMachine;
String[] subKeys = rk.OpenSubKey("HARDWARE").OpenSubKey("DESCRIPTION").OpenSubKey("System").OpenSubKey("CentralProcessor").GetSubKeyNames();
textBox1.Text = "Total number of cores:" + subKeys.Length.ToString();
}
I am reasonably sure the registry entry will be there on most systems.
Though I would throw my $0.02 in.
the time(NULL) function will return the number of seconds elapsed since 01/01/1970 at 00:00. And because, that function is called at different time in your program, it will always be different Time in C++
Assuming df1
has all the values of x
of interest, you could use a dplyr::left_join()
to merge and then either a base::replace()
or tidyr::replace_na()
to replace the NA
s as 0
s:
library(tidyverse)
# dplyr only:
df_new <-
left_join(df1, df2, by = 'x') %>%
mutate(y = replace(y, is.na(y), 0))
# dplyr and tidyr:
df_new <-
left_join(df1, df2, by = 'x') %>%
mutate(y = replace_na(y, 0))
# In the sample data column `x` is a factor, which will give a warning with the join. This can be prevented by converting to a character before the join:
df_new <-
left_join(df1 %>% mutate(x = as.character(x)),
df2 %>% mutate(x = as.character(x)),
by = 'x') %>%
mutate(y = replace(y, is.na(y), 0))
Use a BitSet
. 4 billion integers (assuming up to 2^32 integers) packed into a BitSet at 8 per byte is 2^32 / 2^3 = 2^29 = approx 0.5 Gb.
To add a bit more detail - every time you read a number, set the corresponding bit in the BitSet. Then, do a pass over the BitSet to find the first number that's not present. In fact, you could do this just as effectively by repeatedly picking a random number and testing if it's present.
Actually BitSet.nextClearBit(0) will tell you the first non-set bit.
Looking at the BitSet API, it appears to only support 0..MAX_INT, so you may need 2 BitSets - one for +'ve numbers and one for -'ve numbers - but the memory requirements don't change.
PostgreSQL Create Database - Steps to create database in Postgres.
su - postgres
bash-4.1$ psql psql (12.1) Type "help" for help. postgres=#
CREATE DATABASE database_name;
Check for detailed information below: https://orahow.com/postgresql-create-database/
To add to the above points. Using ArrayList
in 64bit operating system takes 2x memory than using in the 32bit operating system. Meanwhile, generic list List<T>
will use much low memory than the ArrayList
.
for example if we use a ArrayList
of 19MB in 32-bit it would take 39MB in the 64-bit. But if you have a generic list List<int>
of 8MB in 32-bit it would take only 8.1MB in 64-bit, which is a whooping 481% difference when compared to ArrayList.
Source: ArrayList’s vs. generic List for primitive types and 64-bits
For Development purpose you can just export the required tables data into a single HTML and make a direct search on it.
Assuming that the indexes are consistent in the dataframes (not taking into account the actual col values):
df1[~df1.index.isin(df2.index)]
For Python:
ActionChains(driver).key_down(Keys.CONTROL).send_keys("a").key_up(Keys.CONTROL).perform();
You can either use the prepareStatement
method taking an additional int
parameter
PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
For some JDBC drivers (for example, Oracle) you have to explicitly list the column names or indices of the generated keys:
PreparedStatement ps = con.prepareStatement(sql, new String[]{"USER_ID"})
I think you've missed the point of access control.
A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.
Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee
) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.
In your specific case, it seems that paste.ee
doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).
Possibly a simpler solution would be to turn the array of values into an array of value,index-pairs, and take the max/min of that. This would give the largest/smallest index that has the max/min (i.e. pairs are compared by first comparing the first element, and then comparing the second element if the first ones are the same). Note that it's not necessary to actually create the array, because min/max allow generators as input.
values = [3,4,5]
(m,i) = max((v,i) for i,v in enumerate(values))
print (m,i) #(5, 2)
My PHP/MongoDB sort/order by RANDOM solution. Hope this helps anyone.
Note: I have numeric ID's within my MongoDB collection that refer to a MySQL database record.
First I create an array with 10 randomly generated numbers
$randomNumbers = [];
for($i = 0; $i < 10; $i++){
$randomNumbers[] = rand(0,1000);
}
In my aggregation I use the $addField pipeline operator combined with $arrayElemAt and $mod (modulus). The modulus operator will give me a number from 0 - 9 which I then use to pick a number from the array with random generated numbers.
$aggregate[] = [
'$addFields' => [
'random_sort' => [ '$arrayElemAt' => [ $randomNumbers, [ '$mod' => [ '$my_numeric_mysql_id', 10 ] ] ] ],
],
];
After that you can use the sort Pipeline.
$aggregate[] = [
'$sort' => [
'random_sort' => 1
]
];
There are various technological stacks present. Have a look:
LAMP:
Linux
Apache
MySQL
PHP
WAMP:
Windows
Apache
MySQL
PHP
MAMP:
Mac operating system
Apache web server
MySQL as database
PHP for scripting
XAMPP:
X is cross-platform
Apache
MySQL
PHP
Perl
MEAN:
MongoDB
Express.js
Angular
Node.js
MERN:
MongoDB
Express.js
React
Node.js
Try this:
$.each(result,function(index, value){
console.log('My array has at position ' + index + ', this value: ' + value);
});
You can also get a query string value as:
$uri = $_SERVER["REQUEST_URI"]; //it will print full url
$uriArray = explode('/', $uri); //convert string into array with explode
$id = $uriArray[1]; //Print first array value
This is no more .NET Core vs. Mono. It's unified.
Update as of November 2020 - .NET 5 released that unifies .NET Framework and .NET Core
.NET and Mono will be unified under .NET 6 that would be released in November 2021
net6.0-ios
and net6.0-android
.net6.0-ios14
.Check below articles:
val UserMobile = findViewById<edittext>(R.id.UserMobile)
val msgUserMobile: String = UserMobile.text.toString()
fun String.isMobileValid(): Boolean {
// 11 digit number start with 011 or 010 or 015 or 012
// then [0-9]{8} any numbers from 0 to 9 with length 8 numbers
if(Pattern.matches("(011|012|010|015)[0-9]{8}", msgUserMobile)) {
return true
}
return false
}
if(msgUserMobile.trim().length==11&& msgUserMobile.isMobileValid())
{//pass}
else
{//not valid}
I have an application which I wanted to:
I had to hook process.exit(code)
to an exit
event handler, or else the mail will not be sent since calling process.exit(code)
directly kills asynchronous events.
#!/usr/bin/nodejs
var mailer = require('nodemailer');
var transport = mailer.createTransport();
mail = {
to: 'Dave Bowman',
from: 'HAL 9000',
subject: 'Sorry Dave',
html: 'Im sorry, Dave. Im afraid I cant do <B>THAT</B>.'
}
transport.sendMail(mail);
//process.exit(1);
process.on('exit', function() { process.exit(1); });
You can use Dialog to create this easily
create a Dialog instance using the context
Dialog dialog = new Dialog(contex);
You can design your layout as you like.
You can add this layout to your dialog by
dialog.setContentView(R.layout.popupview);//popup view is the layout you created
then you can access its content (textviews, etc.) by using findViewById
method
TextView txt = (TextView)dialog.findViewById(R.id.textbox);
you can add any text here. the text can be stored in the String.xml file in res\values.
txt.setText(getString(R.string.message));
then finally show the pop up menu
dialog.show();
more information http://developer.android.com/guide/topics/ui/dialogs.html
http://developer.android.com/reference/android/app/Dialog.html
{ "date" : "1000000" }
in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }
It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback)
and if that works, you have a typing issue.
Solved!
$a['index'] = [];
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';
selection -selecting a particular item(the lowest) and swap it with the i(no of iteration)th element. (i.e,first,second,third.......) hence,making the sorted list on one side.
insertion- comparing first with second compare third with second & first compare fourth with third,second & first......
You can use parents
method with specified .class
selector and check if any of them matches it:
if ($elem.parents('.left').length != 0) {
//someone has this class
}
this.marker = new google.maps.Marker({
position: new google.maps.LatLng(12.924640523603115,77.61965398949724),
map: map
});
this.placeMarker(coordinates, this.map);
placeMarker(location, map) {
var marker = new google.maps.Marker({
position: location,
map: map
});
this.markersArray.push(marker);
}
Download source code from here (Open Pdf from url in Android Programmatically)
MainActivity.java
package com.deepshikha.openpdf;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
WebView webview;
ProgressBar progressbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView)findViewById(R.id.webview);
progressbar = (ProgressBar) findViewById(R.id.progressbar);
webview.getSettings().setJavaScriptEnabled(true);
String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do your stuff here
progressbar.setVisibility(View.GONE);
}
});
}
}
Thanks!
Storing files in your database will lead to a huge database size. You may not like that, for development, testing, backups, etc.
Instead, you'd use FileStream (SQL-Server) or BFILE (Oracle).
There is no default-implementation of BFILE/FileStream in Postgres, but you can add it: https://github.com/darold/external_file
And further information (in french) can be obtained here:
http://blog.dalibo.com/2015/01/26/Extension_BFILE_pour_PostgreSQL.html
To answer the acual question:
Apart from bytea
, for really large files, you can use LOBS:
// http://stackoverflow.com/questions/14509747/inserting-large-object-into-postgresql-returns-53200-out-of-memory-error
// https://github.com/npgsql/Npgsql/wiki/User-Manual
public int InsertLargeObject()
{
int noid;
byte[] BinaryData = new byte[123];
// Npgsql.NpgsqlCommand cmd ;
// long lng = cmd.LastInsertedOID;
using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(GetConnectionString()))
{
using (Npgsql.NpgsqlTransaction transaction = connection.BeginTransaction())
{
try
{
NpgsqlTypes.LargeObjectManager manager = new NpgsqlTypes.LargeObjectManager(connection);
noid = manager.Create(NpgsqlTypes.LargeObjectManager.READWRITE);
NpgsqlTypes.LargeObject lo = manager.Open(noid, NpgsqlTypes.LargeObjectManager.READWRITE);
// lo.Write(BinaryData);
int i = 0;
do
{
int length = 1000;
if (i + length > BinaryData.Length)
length = BinaryData.Length - i;
byte[] chunk = new byte[length];
System.Array.Copy(BinaryData, i, chunk, 0, length);
lo.Write(chunk, 0, length);
i += length;
} while (i < BinaryData.Length);
lo.Close();
transaction.Commit();
} // End Try
catch
{
transaction.Rollback();
throw;
} // End Catch
return noid;
} // End Using transaction
} // End using connection
} // End Function InsertLargeObject
public System.Drawing.Image GetLargeDrawing(int idOfOID)
{
System.Drawing.Image img;
using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(GetConnectionString()))
{
lock (connection)
{
if (connection.State != System.Data.ConnectionState.Open)
connection.Open();
using (Npgsql.NpgsqlTransaction trans = connection.BeginTransaction())
{
NpgsqlTypes.LargeObjectManager lbm = new NpgsqlTypes.LargeObjectManager(connection);
NpgsqlTypes.LargeObject lo = lbm.Open(takeOID(idOfOID), NpgsqlTypes.LargeObjectManager.READWRITE); //take picture oid from metod takeOID
byte[] buffer = new byte[32768];
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
int read;
while ((read = lo.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
} // Whend
img = System.Drawing.Image.FromStream(ms);
} // End Using ms
lo.Close();
trans.Commit();
if (connection.State != System.Data.ConnectionState.Closed)
connection.Close();
} // End Using trans
} // End lock connection
} // End Using connection
return img;
} // End Function GetLargeDrawing
public void DeleteLargeObject(int noid)
{
using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(GetConnectionString()))
{
if (connection.State != System.Data.ConnectionState.Open)
connection.Open();
using (Npgsql.NpgsqlTransaction trans = connection.BeginTransaction())
{
NpgsqlTypes.LargeObjectManager lbm = new NpgsqlTypes.LargeObjectManager(connection);
lbm.Delete(noid);
trans.Commit();
if (connection.State != System.Data.ConnectionState.Closed)
connection.Close();
} // End Using trans
} // End Using connection
} // End Sub DeleteLargeObject
My Point , IN this arent way asking developer to create all environment related in single go, resulting in risk of exposing Production Configuration to end developer
as per 12-Factor, shouldnt be enviornment specific reside in Enviornment only .
How do we do for CI CD
SELECT
AGE('2012-03-05', '2010-04-01'),
DATE_PART('year', AGE('2012-03-05', '2010-04-01')) AS years,
DATE_PART('month', AGE('2012-03-05', '2010-04-01')) AS months,
DATE_PART('day', AGE('2012-03-05', '2010-04-01')) AS days;
This will give you full years, month, days ... between two dates:
age | years | months | days
-----------------------+-------+--------+------
1 year 11 mons 4 days | 1 | 11 | 4
More detailed datediff information.
If you want to get a UTF-16 encoded code unit as a char
, you can parse the integer and cast to it as others have suggested.
If you want to support all code points, use Character.toChars(int)
. This will handle cases where code points cannot fit in a single char
value.
Doc says:
Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array. If the specified code point is a BMP (Basic Multilingual Plane or Plane 0) value, the resulting char array has the same value as codePoint. If the specified code point is a supplementary code point, the resulting char array has the corresponding surrogate pair.
You can remove the existing options by using the empty
method, and then add your new options:
var option = $('<option></option>').attr("value", "option value").text("Text");
$("#selectId").empty().append(option);
If you have your new options in an object you can:
var newOptions = {"Option 1": "value1",
"Option 2": "value2",
"Option 3": "value3"
};
var $el = $("#selectId");
$el.empty(); // remove old options
$.each(newOptions, function(key,value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
Edit: For removing the all the options but the first, you can use the :gt
selector, to get all the option
elements with index greater than zero and remove
them:
$('#selectId option:gt(0)').remove(); // remove all options, but not the first
to pass many options you can pass a object to a @Input decorator with custom data in a single line.
In the template
<li *ngFor = 'let opt of currentQuestion.options'
[selectable] = 'opt'
[myOptions] ="{first: opt.val1, second: opt.val2}" // these are your multiple parameters
(selectedOption) = 'onOptionSelection($event)' >
{{opt.option}}
</li>
so in Directive class
@Directive({
selector: '[selectable]'
})
export class SelectableDirective{
private el: HTMLElement;
@Input('selectable') option:any;
@Input('myOptions') data;
//do something with data.first
...
// do something with data.second
}
Image can not be shown until it serves from any server. so you need to upload the image to your server to show its preview.
You could modify .adm
and add
.adm{
clear:both;
}
That should make it move to a new line
You're looking for the toggle_comment
command. (Edit > Comment > Toggle Comment)
By default, this command is mapped to:
This command also takes a block
argument, which allows you to use block comments instead of single lines (e.g. /* ... */
as opposed to // ...
in JavaScript). By default, the following key combinations are mapped to toggle block comments:
You could checkout Moment.js, Luxon, date-fns or Day.js for nice date manipulation.
Or just extract the first part of your ISO string, it already contains what you want.
Here is an example by splitting on the T
:
"2013-03-10T02:00:00Z".split("T")[0] // "2013-03-10"
USING PURE JAVASCRIPT: I know it's late but may be for the future people it can help:
In the HTML part:
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
In the Javascipt Controller:
function reply_click()
{
alert(event.srcElement.id);
}
This way we don't have to bind the 'id' of the Element at the time of calling the javascript function.
The following worked for me with clang. Allows what appears as symbolic macro value comparison. #error xxx is just to see what compiler really does. Replacing cat definition with #define cat(a,b) a ## b breaks things.
#define cat(a,...) cat_impl(a, __VA_ARGS__)
#define cat_impl(a,...) a ## __VA_ARGS__
#define xUSER_jack 0
#define xUSER_queen 1
#define USER_VAL cat(xUSER_,USER)
#define USER jack // jack or queen
#if USER_VAL==xUSER_jack
#error USER=jack
#define USER_VS "queen"
#elif USER_VAL==xUSER_queen
#error USER=queen
#define USER_VS "jack"
#endif
try this:
var a = screen.Data.getFullYear();
var m = screen.Data.getMonth();
var d = screen.Data.getDate();
m = m + 1;
screen.Data = new Date(a, m, d);
if (screen.Data.getDate() != d)
screen.Data = new Date(a, m + 1, 0);
https://dev.mysql.com/doc/refman/8.0/en/insert-optimization.html
The time required for inserting a row is determined by the following factors, where the numbers indicate approximate proportions:
- Connecting: (3)
- Sending query to server: (2)
- Parsing query: (2)
- Inserting row: (1 × size of row)
- Inserting indexes: (1 × number of indexes)
- Closing: (1)
From this it should be obvious, that sending one large statement will save you an overhead of 7 per insert statement, which in further reading the text also says:
If you are inserting many rows from the same client at the same time, use INSERT statements with multiple VALUES lists to insert several rows at a time. This is considerably faster (many times faster in some cases) than using separate single-row INSERT statements.
While working on an enterprise project in STS (heavily Eclipse based) I was crashing constantly and STS plateaued at around 1GB of RAM usage. I couldn't add new .war files to my local tomcat server and after deleting the tomcat folder to re-add it, found I couldn't re-add it either. Essentially almost anything that required a new popup besides the main menus was causing STS to freeze up.
I edited the STS.ini (your Eclipse.ini can be configured similarly) to:
--launcher.XXMaxPermSize 1024M -vmargs -Xms1536m -Xmx2048m -XX:MaxPermSize=1024m
Rebooted STS immediately and saw it plateau at about 1.5 gigs before finally not crashing
I suspect your string already actually only contains a single backslash, but you're looking at it in the debugger which is escaping it for you into a form which would be valid as a regular string literal in C#.
If print it out in the console, or in a message box, does it show with two backslashes or one?
If you actually want to replace a double backslash with a single one, it's easy to do so:
text = text.Replace(@"\\", @"\");
... but my guess is that the original doesn't contain a double backslash anyway. If this doesn't help, please give more details.
EDIT: In response to the edited question, your stringToBeReplaced
only has a single backslash in. Really. Wherever you're seeing two backslashes, that viewer is escaping it. The string itself doesn't have two backslashes. Examine stringToBeReplaced.Length
and count the characters.
Sure!
#file -- test.py --
myvar = 42
def test_func():
print("Hello!")
Now, this file ("test.py") is in python terminology a "module". We can import it (as long as it can be found in our PYTHONPATH
) Note that the current directory is always in PYTHONPATH
, so if use_test
is being run from the same directory where test.py
lives, you're all set:
#file -- use_test.py --
import test
test.test_func() #prints "Hello!"
print (test.myvar) #prints 42
from test import test_func #Only import the function directly into current namespace
test_func() #prints "Hello"
print (myvar) #Exception (NameError)
from test import *
test_func() #prints "Hello"
print(myvar) #prints 42
There's a lot more you can do than just that through the use of special __init__.py
files which allow you to treat multiple files as a single module), but this answers your question and I suppose we'll leave the rest for another time.
Without your seeing your data (you can use the output of dput(head(survey))
to show us) this is a shot in the dark:
survey <- data.frame(date=c("2012/07/26","2012/07/25"),tx_start=c("2012/01/01","2012/01/01"))
survey$date_diff <- as.Date(as.character(survey$date), format="%Y/%m/%d")-
as.Date(as.character(survey$tx_start), format="%Y/%m/%d")
survey
date tx_start date_diff
1 2012/07/26 2012/01/01 207 days
2 2012/07/25 2012/01/01 206 days
DATEADD
is the way to go with this
See the W3Schools tutorial: http://www.w3schools.com/sql/func_dateadd.asp
i am actually doing somewhat same thing but on my AWS S3 storage:-
Code for servlet which is receiving uploaded file:-
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.src.code.s3.S3FileUploader;
public class FileUploadHandler extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
try{
List<FileItem> multipartfiledata = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
//upload to S3
S3FileUploader s3 = new S3FileUploader();
String result = s3.fileUploader(multipartfiledata);
out.print(result);
} catch(Exception e){
System.out.println(e.getMessage());
}
}
}
Code which is uploading this data as AWS object:-
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import org.apache.commons.fileupload.FileItem;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.ClasspathPropertiesFileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
public class S3FileUploader {
private static String bucketName = "***NAME OF YOUR BUCKET***";
private static String keyName = "Object-"+UUID.randomUUID();
public String fileUploader(List<FileItem> fileData) throws IOException {
AmazonS3 s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
String result = "Upload unsuccessfull because ";
try {
S3Object s3Object = new S3Object();
ObjectMetadata omd = new ObjectMetadata();
omd.setContentType(fileData.get(0).getContentType());
omd.setContentLength(fileData.get(0).getSize());
omd.setHeader("filename", fileData.get(0).getName());
ByteArrayInputStream bis = new ByteArrayInputStream(fileData.get(0).get());
s3Object.setObjectContent(bis);
s3.putObject(new PutObjectRequest(bucketName, keyName, bis, omd));
s3Object.close();
result = "Uploaded Successfully.";
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, which means your request made it to Amazon S3, but was "
+ "rejected with an error response for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
result = result + ase.getMessage();
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which means the client encountered an internal error while "
+ "trying to communicate with S3, such as not being able to access the network.");
result = result + ace.getMessage();
}catch (Exception e) {
result = result + e.getMessage();
}
return result;
}
}
Note :- I am using aws properties file for credentials.
Hope this helps.
int64_t delayInSeconds = 0.6;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
do something to the button(s)
});
Here is an example that I built based on this page.
library(e1071); library(ggplot2)
mysvm <- svm(Species ~ ., iris)
Predicted <- predict(mysvm, iris)
mydf = cbind(iris, Predicted)
qplot(Petal.Length, Petal.Width, colour = Species, shape = Predicted,
data = iris)
This gives you the output. You can easily spot the misclassified species from this figure.
Using the contentWindow.focus() method, the timeout is probably necessary to wait for the iframe to be completely loaded.
For me, also using attribute onload="this.contentWindow.focus()"
works, with firefox, into the iframe tag
Write-Host "Found file - " + $File.FullName -ForegroundColor Magenta
Magenta can be one of the "System.ConsoleColor" enumerator values - Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White.
The + $File.FullName
is optional, and shows how to put a variable into the string.
There is two way for hide a element
Use the "hidden" html attribute But in angular you can bind it with one or more fields like this :
<input class="txt" type="password" [(ngModel)]="input_pw" [hidden]="isHidden">
2.Better way of doing this is to use " *ngIf " directive like this :
<input class="txt" type="password" [(ngModel)]="input_pw" *ngIf="!isHidden">
Now why this is a better way because it doesn't just hide the element, it will removes it from the html code so this will help your page to render.
When you say "full-screen", do you mean like full-screen for the computer, or for taking up the entire space in the browser?
You can't force the user into full-screen F11
; however, you can make your div full screen by using the following CSS
div {width: 100%; height: 100%;}
This will of course assume your div is child of the <body>
tag. Otherwise, you'd need to add the following in addition to the above code.
div {position: absolute; top: 0; left: 0;}
Here's an option if you need to escape multiple %'s in a string with some already escaped.
(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])
To sanitise the message before passing it to String.format, you can use the following
Pattern p = Pattern.compile("(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])");
Matcher m1 = p.matcher(log);
StringBuffer buf = new StringBuffer();
while (m1.find())
m1.appendReplacement(buf, log.substring(m1.start(), m1.start(2)) + "%%" + log.substring(m1.end(2), m1.end()));
// Return the sanitised message
String escapedString = m1.appendTail(buf).toString();
This works with any number of formatting characters, so it will replace % with %%, %%% with %%%%, %%%%% with %%%%%% etc.
It will leave any already escaped characters alone (e.g. %%, %%%% etc.)
You have the noclobber
option set. The error looks like it's from csh, so you would do:
cat /dev/null >! file
If I'm wrong and you are using bash, you should do:
cat /dev/null >| file
in bash, you can also shorten that to:
>| file
new_list = my_list[:]
new_list = my_list
Try to understand this. Let's say that my_list is in the heap memory at location X i.e. my_list is pointing to the X. Now by assigning new_list = my_list
you're Letting new_list pointing to the X. This is known as shallow Copy.
Now if you assign new_list = my_list[:]
You're simply copying each object of my_list to new_list. This is known as Deep copy.
The Other way you can do this are :
new_list = list(old_list)
import copy
new_list = copy.deepcopy(old_list)
This error happened to me in a Grails Application with the JTDS Driver 1.3.0 (SQL Server). The problem was an incorrect login in SQL Server. After solve this issue (in SQL Server) my app was correctly deployed in Tomcat. Tip: I saw the error in stacktrace.log
SHA-1 (and all other hashing algorithms) return binary data. That means that (in Java) they produce a byte[]
. That byte
array does not represent any specific characters, which means you can't simply turn it into a String
like you did.
If you need a String
, then you have to format that byte[]
in a way that can be represented as a String
(otherwise, just keep the byte[]
around).
Two common ways of representing arbitrary byte[]
as printable characters are BASE64 or simple hex-Strings (i.e. representing each byte
by two hexadecimal digits). It looks like you're trying to produce a hex-String.
There's also another pitfall: if you want to get the SHA-1 of a Java String
, then you need to convert that String
to a byte[]
first (as the input of SHA-1 is a byte[]
as well). If you simply use myString.getBytes()
as you showed, then it will use the platform default encoding and as such will be dependent on the environment you run it in (for example it could return different data based on the language/locale setting of your OS).
A better solution is to specify the encoding to use for the String
-to-byte[]
conversion like this: myString.getBytes("UTF-8")
. Choosing UTF-8 (or another encoding that can represent every Unicode character) is the safest choice here.
Cast the operands to floats:
float ans = (float)a / (float)b;
I've also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.
$periods=array('hour', 'day', 'month');
foreach ($periods as $period)
{
$this->{'value_'.$period}=1;
}
This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.
You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.
class timevalues
{
// Database table values:
public $value_hour; // maps to values.value_hour
public $value_day; // maps to values.value_day
public $value_month; // maps to values.value_month
public $values=array();
public function __construct()
{
$this->value_hour=0;
$this->value_day=0;
$this->value_month=0;
$this->values=array(
'hour'=>$this->value_hour,
'day'=>$this->value_day,
'month'=>$this->value_month,
);
}
}
In my case, I was copying and pasting code from my other classes, so I did not notice that the getter code was bad written:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "credito")
public Set getConceptoses() {
return this.letrases;
}
public void setConceptoses(Set conceptoses) {
this.conceptoses = conceptoses;
}
All references conceptoses but if you look at the get says letrases
You can create a new model to Deserialize your Json CustomerJson
:
public class CustomerJson
{
[JsonProperty("customer")]
public Customer Customer { get; set; }
}
public class Customer
{
[JsonProperty("first_name")]
public string Firstname { get; set; }
[JsonProperty("last_name")]
public string Lastname { get; set; }
...
}
And you can deserialize your json easily :
JsonConvert.DeserializeObject<List<CustomerJson>>(json);
Hope it helps !
Documentation: Serializing and Deserializing JSON
Remove rel="stylesheet" and add type="text/html". So it will look like this -
<link href="styles.css" type="text/html" />
= 0
means that a function is pure virtual and you cannot instantiate an object from this class. You need to derive from it and implement this method= delete
means that the compiler will not generate those constructors for you. AFAIK this is only allowed on copy constructor and assignment operator. But I am not too good at the upcoming standard.?? For JetBrains IntelliJ IDEA: Go to Help -> Edit Custom Properties...
. Create the file if it asks you to create it. To disable the error message paste the following to the file you created:
idea_rt
idea.no.launcher=true
This will take effect on the restart of the IntelliJ.
Try this...
styles.xml
<resources>
<style name="Theme.AppCompat.Light.NoActionBar" parent="@style/Theme.AppCompat.Light">
<item name="android:windowNoTitle">true</item>
</style>
</resources>
AndroidManifest.xml
<activity
android:name="com.example.Home"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Light.NoActionBar"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
sp_help tablename
in sql server
desc tablename
in oracle
The problem was that I was going a step too far in calling the parse method of XMLReader. The parse method accepts an InputSource, so there was no reason to even use a FileReader. Changing the last line of the code above to
xr.parse( new InputSource( filename ));
works just fine.
This is typical behavior for when the JavaScript for the Modal plugin gets loaded twice. Please check to make sure that the plugin isn't getting double loaded. Depending on the platform you are using, the modal code could be loaded from a number a sources. Some of the common ones are:
require('bootstrap')
A good place to start is to inspect the registered click
event listeners using the developer tools in your browser. Chrome, for instance, will list the JS source file where the code to register the listener can be found. Another option is to try searching the sources on the page for a phrase found in the Modal code, e.g., var Modal
.
Unfortunately, these won't always find things in all cases. Inspecting the network requests can be a little more robust at giving you a picture of everything loaded on a page.
Here's a demo of what happens when you load both the bootstrap.js and bootstrap-modal.js (just to confirm your experience):
If you scroll down to the bottom of the source on that page, you can remove or comment out the <script>
line for the bootstrap-modal.js and then verify that now the modal will function as expected.
There are probably tests you can do, for instance if you know that the JSON returned is always going to be surrounded by {
and }
then you could test for those characters, or some other hacky method. Or you could use the json.org JS library to try and parse it and test if it succeeds.
I would however suggest a different approach. Your PHP script currently returns JSON if the call is successful, but something else if it is not. Why not always return JSON?
E.g.
Successful call:
{ "status": "success", "data": [ <your data here> ] }
Erroneous call:
{ "status": "error", "error": "Database not found" }
This would make writing your client side JS much easier - all you have to do is check the "status" member and the act accordingly.
Some cookies, such as referrer urls, have =
in them. As a result, simply splitting on =
will cause irregular results, and the previous answers here will breakdown over time (or immediately depending on your depth of use).
This takes only the first instance of the equals sign. It returns an object with the cookie's key value pairs.
// Returns an object of key value pairs for this page's cookies
function getPageCookies(){
// cookie is a string containing a semicolon-separated list, this split puts it into an array
var cookieArr = document.cookie.split(";");
// This object will hold all of the key value pairs
var cookieObj = {};
// Iterate the array of flat cookies to get their key value pair
for(var i = 0; i < cookieArr.length; i++){
// Remove the standardized whitespace
var cookieSeg = cookieArr[i].trim();
// Index of the split between key and value
var firstEq = cookieSeg.indexOf("=");
// Assignments
var name = cookieSeg.substr(0,firstEq);
var value = cookieSeg.substr(firstEq+1);
cookieObj[name] = value;
}
return cookieObj;
}
Try this:
For example, let's define res/drawable/my_custom_background.xml as:
(create this layout in your drawable folder) layout_border.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<stroke android:width="2dp" android:height="2dp"
android:color="#FF0000" />
<solid android:color="#000000" />
<padding android:left="1dp" android:top="1dp" android:right="1dp"
android:bottom="1dp" />
<corners android:radius="1dp" android:bottomRightRadius="5dp"
android:bottomLeftRadius="0dp" android:topLeftRadius="5dp"
android:topRightRadius="0dp" />
</shape>
</item>
</layer-list>
main.xml
<LinearLayout
android:layout_gravity="center"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="@drawable/layout_border" />
</LinearLayout>
I think to have the real next or previous row in SQL table we need the real value with equal, (< or >) return more than one if you need to change position of row in a ordering table.
we need the value $position
to search the neighbours
row
In my table I created a column 'position'
and SQL query for getting the needed row is :
for next :
SELECT *
FROM `my_table`
WHERE id = (SELECT (id)
FROM my_table
WHERE position = ($position+1))
LIMIT 1
for previous:
SELECT *
FROM my_table
WHERE id = (SELECT (id)
FROM my_table
WHERE `position` = ($position-1))
LIMIT 1
I like a few usages of Java enum:
enum with value parameters:
enum StateEnum {
UNDEFINED_POLL ( 1 * 1000L, 4 * 1000L),
SUPPORT_POLL ( 1 * 1000L, 5 * 1000L),
FAST_POLL ( 2 * 1000L, 4 * 60 * 1000L),
NO_POLL ( 1 * 1000L, 6 * 1000L);
...
}
switch example:
private void queuePoll(StateEnum se) {
// debug print se.name() if needed
switch (se) {
case UNDEFINED_POLL:
...
break;
case SUPPORT_POLL:
...
break;
Yes, it is, you will want to use the static Load method on the Assembly class, and then call then call the CreateInstance method on the Assembly instance returned to you from the call to Load.
Also, you can call one of the other static methods starting with "Load" on the Assembly class, depending on your needs.
You need to specify how you'll authenticate with the database. If you want to use integrated security (this means using Windows authentication using your local or domain Windows account), add this to the connection string:
Integrated Security = True;
If you want to use SQL Server authentication (meaning you specify a login and password rather than using a Windows account), add this:
User ID = "username"; Password = "password";
Sorry for comment in an old post but if you want to use an else if statement this will help you
{% if title == source %}
Do This
{% elif title == value %}
Do This
{% else %}
Do This
{% endif %}
For more info see Django Documentation
I had this same issue but my fix was much more basic:
If the LogCat panel is empty in Eclipse the emulator doesn't have the focus. Go to the DDMS perspective and try clicking on the 'emulator' entry in the Devices panel (top-left screen).
On chrome when are in the SVG URL, you can do CTRL+S or CMD+S and it automatically propose you to save the page as an .SVG try it out : https://upload.wikimedia.org/wikipedia/commons/9/90/Benjamin_Franklin-10_Dollar_Bill_Portrait-Vector.svg
Have you tried adding a magic comment in the script where you use non-ASCII chars? It should go on top of the script.
#!/bin/env ruby
# encoding: utf-8
It worked for me like a charm.
I don’t know for sure but I’m reading a book right now and what I am getting is that a program need to handle its signal ( as when I press CTRL-C
). Now a program can use SIG_IGN
to ignore all signals or SIG_DFL
to restore the default action.
Now if you do $ command &
then this process running as background process simply ignores all signals that will occur. For foreground processes these signals are not ignored.
set DNS 8.8.4.4 and run emulator -avd react-native-device -dns-server 8.8.4.4
this work for me