1) Add On Error Resume Next
at top of the page
2) Add following code at bottom of the page
If Err.Number <> 0 Then
Response.Write (Err.Description)
Response.End
End If
On Error GoTo 0
A silly hack I did was to set the height of the element to zero but overflow:visible; combining this with pointer-events:none; seems to cover all the bases.
.overlay {
height:0px;
overflow:visible;
pointer-events:none;
background:none !important;
}
versions:update-child-modules
sounds like what you're looking for. You could do versions:set as mentioned, but this is a light-weight way to update the parent version numbers. For the child modules, it's my opinion that you should remove the <version>
definitions, since they will inherit the parent module's version number.
I think you're looking for: SELECT a, b, COUNT(a) FROM tbl GROUP BY a, b
I was facing the same issue,
I have enabled Network Link Conditioner for slow network testing for the app. That was creating this error some times,
When i have disabled it from Settings > Developer > Network Link Conditioner
, it solved my problem.
Hope this help someone.
I know it's already answered but here is a solution I find more elegant:
arsort($array);
reset($array);
echo key($array);
and voila!
With version 1.7 of the official 10gen driver, this is the current (non-obsolete) API:
const string uri = "mongodb://localhost/mydb";
var client = new MongoClient(uri);
var db = client.GetServer().GetDatabase(new MongoUrl(uri).DatabaseName);
var collection = db.GetCollection("mycollection");
Manoj answer above is correct, but another option is to use MESSAGE.encode() or encode('utf-8') to convert to bytes. bytes and encode are mostly the same, encode is compatible with python 2. see here for more
full code:
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"
print("UDP target IP: %s" % UDP_IP)
print("UDP target port: %s" % UDP_PORT)
print("message: %s" % MESSAGE)
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode(), (UDP_IP, UDP_PORT))
array_search('20120504', array_keys($your_array));
This worked for me,
$recipient_email = '[email protected],[email protected]';
$success = mail($recipient_email, $subject, $body, $headers);
http://en.wikipedia.org/wiki/Hexspeak
http://www.urbandictionary.com/define.php?term=dead%3Abeef
"Dead beef" is a very popular sentence in programming, because it is built only from letters a-f, which are used in hexadecimal notation. Colons in the beginning and in the middle of the sentence make this sentence a (theoretically) valid IPv6 address.
Lots of good answers already. I personally go with awk. For convenience, if you use bash, just add the below to your ~/.bash_profile
. And, the next time you log in (or if you source your .bash_profile after this update), you will have a new nifty "nth" function available to pipe your files through.
Execute this or put it in your ~/.bash_profile (if using bash) and reopen bash (or execute source ~/.bach_profile
)
# print just the nth piped in line
nth () { awk -vlnum=${1} 'NR==lnum {print; exit}'; }
Then, to use it, simply pipe through it. E.g.,:
$ yes line | cat -n | nth 5
5 line
In a bash-like environment you can use:
keytool -list -v -keystore cacerts.jks | grep 'Alias name:' | grep -i foo
This command consist of 3 parts. As stated above, the 1st part will list all trusted certificates with all the details and that's why the 2nd part comes to filter only the alias information among those details. And finally in the 3rd part you can search for a specific alias (or part of it). The -i turns the case insensitive mode on. Thus the given command will yield all aliases containing the pattern 'foo', f.e. foo, 123_FOO, fooBar, etc. For more information man grep
.
Check Ayende post on the topic: Combating the Select N + 1 Problem In NHibernate.
Basically, when using an ORM like NHibernate or EntityFramework, if you have a one-to-many (master-detail) relationship, and want to list all the details per each master record, you have to make N + 1 query calls to the database, "N" being the number of master records: 1 query to get all the master records, and N queries, one per master record, to get all the details per master record.
More database query calls ? more latency time ? decreased application/database performance.
However, ORMs have options to avoid this problem, mainly using JOINs.
for a non-nested dict (since the title does not mention that case, it might be interesting for other people)
{str(k): str(v) for k, v in my_dict.items()}
This worked for me. Each month on X axis
str_month_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
ax.set_xticks(range(0,12))
ax.set_xticklabels(str_month_list)
UltraID3Lib...
Be aware that UltraID3Lib is no longer officially available, and thus no longer maintained. See comments below for the link to a Github project that includes this library
//using HundredMilesSoftware.UltraID3Lib;
UltraID3 u = new UltraID3();
u.Read(@"C:\mp3\song.mp3");
//view
Console.WriteLine(u.Artist);
//edit
u.Artist = "New Artist";
u.Write();
You need to use the method equals()
when comparing a string, otherwise you're just comparing the object references to each other, so in your case you want:
if (!statusCheck.equals("success")) {
...or alternatively if you only want to show a portion of the time value use "Custom":
timePicker = new DateTimePicker();
timePicker.Format = DateTimePickerFormat.Custom;
timePicker.CustomFormat = "HH:mm"; // Only use hours and minutes
timePicker.ShowUpDown = true;
You can use this two commands: tasklist
and netstat -oan
Tasklist.exe
is like taskmgr.exe
but in text mode.
With tasklist.exe
or taskmgr.exe
you can obtain a PID of sqlservr.exe
With netstat -oan
, it shows a connection PID, and you can filter it.
Example:
C:\>tasklist | find /i "sqlservr.exe"
sqlservr.exe 1184 Services 0 3.181.800 KB
C:\>netstat -oan | find /i "1184"
TCP 0.0.0.0:1280 0.0.0.0:0 LISTENING 1184
In this example, the SQLServer port is 1280
Extracted from: http://www.sysadmit.com/2016/03/mssql-ver-puerto-de-una-instancia.html
Join the table with itself and give it two different aliases (A
and B
in the following example). This allows to compare different rows of the same table.
SELECT DISTINCT A.Id
FROM
Address A
INNER JOIN Address B
ON A.Id = B.Id AND A.[Adress Code] < B.[Adress Code]
WHERE
A.Address <> B.Address
The "less than" comparison <
ensures that you get 2 different addresses and you don't get the same 2 address codes twice. Using "not equal" <>
instead, would yield the codes as (1, 2) and (2, 1); each one of them for the A
alias and the B
alias in turn.
The join clause is responsible for the pairing of the rows where as the where-clause tests additional conditions.
The query above works with any address codes. If you want to compare addresses with specific address codes, you can change the query to
SELECT A.Id
FROM
Address A
INNER JOIN Address B
ON A.Id = B.Id
WHERE
A.[Adress Code] = 1 AND
B.[Adress Code] = 2 AND
A.Address <> B.Address
I imagine that this might be useful to find customers having a billing address (Adress Code = 1 as an example) differing from the delivery address (Adress Code = 2) .
It sounds like you are talking about aggregation. Each instance of your player
class can contain zero or more instances of Airplane
, which, in turn, can contain zero or more instances of Flight
. You can implement this in Python using the built-in list
type to save you naming variables with numbers.
class Flight(object):
def __init__(self, duration):
self.duration = duration
class Airplane(object):
def __init__(self):
self.flights = []
def add_flight(self, duration):
self.flights.append(Flight(duration))
class Player(object):
def __init__ (self, stock = 0, bank = 200000, fuel = 0, total_pax = 0):
self.stock = stock
self.bank = bank
self.fuel = fuel
self.total_pax = total_pax
self.airplanes = []
def add_planes(self):
self.airplanes.append(Airplane())
if __name__ == '__main__':
player = Player()
player.add_planes()
player.airplanes[0].add_flight(5)
From Apple Docs
You can use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."
VERY IMPORTANT Additional info on difference between .text() and .html():
If your selector selects more than one item, e.g you have two spans like so
<span class="foo">bar1</span>
<span class="foo">bar2</span>
,
then
$('.foo').text();
appends the two texts and give you that; whereas
$('.foo').html();
gives you only one of those.
I've resolved it by checking the 'UNICODE'checkbox. Click on below Image link:
You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
OpenId - Used only for Authentication.
OAuth - Used for both Authentication and Authorization. Authorization depends on the access_token which comes as part of JWT token. It can have details of user permissions or any useful information.
Both can rely on 3rd party auth provider which maintains their accounts. For example OKTA identity provider, User provides the credentials on OKTA login page and on successful login the user is redirected on the consumer application with the JWT token in the header.
This should work fine.
Workbook wb = new XSSFWorkbook("myWorkbook.xlsx");
Row row=sheet.getRow(0);
CellStyle style=null;
XSSFFont defaultFont= wb.createFont();
defaultFont.setFontHeightInPoints((short)10);
defaultFont.setFontName("Arial");
defaultFont.setColor(IndexedColors.BLACK.getIndex());
defaultFont.setBold(false);
defaultFont.setItalic(false);
XSSFFont font= wb.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("Arial");
font.setColor(IndexedColors.WHITE.getIndex());
font.setBold(true);
font.setItalic(false);
style=row.getRowStyle();
style.setFillBackgroundColor(IndexedColors.DARK_BLUE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFont(font);
If you do not create defaultFont
all your workbook will be using the other one as default.
member b of object pointed to by a a->b
my_data
is a struct with name
as a field and data[]
is arry of structs, you are initializing each index. read following:
5.20 Designated Initializers:
In a structure initializer, specify the name of a field to initialize with
.fieldname ='
before the element value. For example, given the following structure,struct point { int x, y; };
the following initialization
struct point p = { .y = yvalue, .x = xvalue };
is equivalent to
struct point p = { xvalue, yvalue };
Another syntax which has the same meaning, obsolete since GCC 2.5, is
fieldname:'
, as shown here:struct point p = { y: yvalue, x: xvalue };
You can also write:
my_data data[] = {
{ .name = "Peter" },
{ .name = "James" },
{ .name = "John" },
{ .name = "Mike" }
};
as:
my_data data[] = {
[0] = { .name = "Peter" },
[1] = { .name = "James" },
[2] = { .name = "John" },
[3] = { .name = "Mike" }
};
or:
my_data data[] = {
[0].name = "Peter",
[1].name = "James",
[2].name = "John",
[3].name = "Mike"
};
Second and third forms may be convenient as you don't need to write in order for example all of the above example are equivalent to:
my_data data[] = {
[3].name = "Mike",
[1].name = "James",
[0].name = "Peter",
[2].name = "John"
};
If you have multiple fields in your struct (for example, an int age
), you can initialize all of them at once using the following:
my_data data[] = {
[3].name = "Mike",
[2].age = 40,
[1].name = "James",
[3].age = 23,
[0].name = "Peter",
[2].name = "John"
};
To understand array initialization read Strange initializer expression?
Additionally, you may also like to read @Shafik Yaghmour's answer for switch case: What is “…” in switch-case in C code
Better to find cells from gridview instead of static/fix index so it will not generate any problem whenever you will add/remove any columns on gridview.
ASPX:
<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" >
<Columns>
<asp:BoundField HeaderText="Date" DataField="CreatedDate" />
</Columns>
</asp:GridView>
CS:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
if (string.Compare(e.Row.Cells[i].Text, "Date", true) == 0)
{
e.Row.Cells[i].Text = "Created Date";
}
}
}
}
Its better if you use validation code to the users input for making it restricted to use symbols and part of code in your input form. If you embeed php in html code your php code have to become on the top to make sure that it is not ignored as comment if a hacker edit the page and add /* in your html code
You can use the %p
formatter. It's always best practice cast your pointer void*
before printing.
The C standard says:
The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.
Here's how you do it:
printf("%p", (void*)p);
Someone who also has xml files, might want to look at my Xidel. It is a cli, dependency-free JSONiq processor. (i.e. it also supports XQuery for xml or json processing)
The example in the question would be:
xidel -e 'json("http://twitter.com/users/username.json")("name")'
Or with my own, non standard extension syntax:
xidel -e 'json("http://twitter.com/users/username.json").name'
I try to explain this problem step by step in following example.
0) Question
I try to ask you like this :
i want to open page like facebook profile www.facebook.com/kaila.piyush
it get id from url and parse it to profile.php file and return featch data from database and show user to his profile
normally when we develope any website its link look like www.website.com/profile.php?id=username example.com/weblog/index.php?y=2000&m=11&d=23&id=5678
now we update with new style not rewrite we use www.website.com/username or example.com/weblog/2000/11/23/5678 as permalink
http://example.com/profile/userid (get a profile by the ID)
http://example.com/profile/username (get a profile by the username)
http://example.com/myprofile (get the profile of the currently logged-in user)
1) .htaccess
Create a .htaccess file in the root folder or update the existing one :
Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
# Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php
What does that do ?
If the request is for a real directory or file (one that exists on the server), index.php isn't served, else every url is redirected to index.php.
2) index.php
Now, we want to know what action to trigger, so we need to read the URL :
In index.php :
// index.php
// This is necessary when index.php is not in the root folder, but in some subfolder...
// We compare $requestURL and $scriptName to remove the inappropriate values
$requestURI = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
$scriptName = explode(‘/’,$_SERVER[‘SCRIPT_NAME’]);
for ($i= 0; $i < sizeof($scriptName); $i++)
{
if ($requestURI[$i] == $scriptName[$i])
{
unset($requestURI[$i]);
}
}
$command = array_values($requestURI);
With the url http://example.com/profile/19837, $command would contain :
$command = array(
[0] => 'profile',
[1] => 19837,
[2] => ,
)
Now, we have to dispatch the URLs. We add this in the index.php :
// index.php
require_once("profile.php"); // We need this file
switch($command[0])
{
case ‘profile’ :
// We run the profile function from the profile.php file.
profile($command([1]);
break;
case ‘myprofile’ :
// We run the myProfile function from the profile.php file.
myProfile();
break;
default:
// Wrong page ! You could also redirect to your custom 404 page.
echo "404 Error : wrong page.";
break;
}
2) profile.php
Now in the profile.php file, we should have something like this :
// profile.php
function profile($chars)
{
// We check if $chars is an Integer (ie. an ID) or a String (ie. a potential username)
if (is_int($chars)) {
$id = $chars;
// Do the SQL to get the $user from his ID
// ........
} else {
$username = mysqli_real_escape_string($char);
// Do the SQL to get the $user from his username
// ...........
}
// Render your view with the $user variable
// .........
}
function myProfile()
{
// Get the currently logged-in user ID from the session :
$id = ....
// Run the above function :
profile($id);
}
scanf
needs to know the size of the data being pointed at by &d
to fill it properly, whereas variadic functions promote floats to doubles (not entirely sure why), so printf
is always getting a double
.
Wasabii's answer in Swift 2.3:
let shadowPath = UIBezierPath(rect: view.bounds)
view.layer.masksToBounds = false
view.layer.shadowColor = UIColor.blackColor().CGColor
view.layer.shadowOffset = CGSize(width: 0, height: 0.5)
view.layer.shadowOpacity = 0.2
view.layer.shadowPath = shadowPath.CGPath
And in Swift 3/4/5:
let shadowPath = UIBezierPath(rect: view.bounds)
view.layer.masksToBounds = false
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOffset = CGSize(width: 0, height: 0.5)
view.layer.shadowOpacity = 0.2
view.layer.shadowPath = shadowPath.cgPath
Put this code in layoutSubviews() if you're using AutoLayout.
In SwiftUI, this is all much easier:
Color.yellow // or whatever your view
.shadow(radius: 3)
.frame(width: 200, height: 100)
Check this Image… You can change your simulator size from here
or press CMD+1, CMD+2 or CMD+3
When you run into a problem where it cats all.txt into all.txt, You can try check all.txt is existing or not, if exists, remove
Like this:
[ -e $"all.txt" ] && rm $"all.txt"
TruckClass
sounds like it were a class of Truck
, I think that recommended solution is to add Impl
suffix. In my opinion the best solution is to contain within implementation name some information, what's going on in that particular implementation (like we have with List
interface and implementations: ArrayList
or LinkedList
), but sometimes you have just one implementation and have to have interface due to remote usage (for example), then (as mentioned at the beginning) Impl
is the solution.
Sometimes this doesn't work if:
1) you have an error in the java script code before your line with $('#myModal').on('show.bs.modal'...)
. To troubleshoot put an alert message before the line to see if it comes up when you load the page. To resolve eliminate JSs above to see which one is the problem
2) Another problem is if you load up the JS in wrong order. For example you can have the $('#myModal').on('show.bs.modal'...)
part before you actually load JQuery.js. In that case your call will be ignored, so first in the HTML (view page source to be sure) check if the script link to JQuery is above your modal onShow
call, otherwise it will be ignored. To troubleshoot put an alert inside the on show an one before. If you see the one before and not the one inside the onShow function it is clear that the function cannot execute. If the spelling is right more than likely your call to JQuery.js is not made or it is made after the onShow
part
In your public View getView
method change return null;
to return convertView;
.
If that's all what you want to do, you don't need to convert it into an array. You can just access it as:
string myData=yourDataTable.Rows[0][1].ToString();//Gives you USA
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'To address'
mail.Subject = 'Message subject'
mail.Body = 'Message body'
mail.HTMLBody = '<h2>HTML Message body</h2>' #this field is optional
# To attach a file to the email (optional):
attachment = "Path to the attachment"
mail.Attachments.Add(attachment)
mail.Send()
Will use your local outlook account to send.
Note if you are trying to do something not mentioned above, look at the COM docs properties/methods: https://msdn.microsoft.com/en-us/vba/outlook-vba/articles/mailitem-object-outlook. In the code above, mail
is a MailItem Object.
bs := string(body)
should be enough to give you a string.
From there, you can use it as a regular string.
A bit as in this thread:
var client http.Client
resp, err := client.Get(url)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
bodyString := string(bodyBytes)
log.Info(bodyString)
}
See also GoByExample.
As commented below (and in zzn's answer), this is a conversion (see spec).
See "How expensive is []byte(string)
?" (reverse problem, but the same conclusion apply) where zzzz mentioned:
Some conversions are the same as a cast, like
uint(myIntvar)
, which just reinterprets the bits in place.
Sonia adds:
Making a string out of a byte slice, definitely involves allocating the string on the heap. The immutability property forces this.
Sometimes you can optimize by doing as much work as possible with []byte and then creating a string at the end. Thebytes.Buffer
type is often useful.
You need to use something like iteritems
.
for field, possible_values in fields.iteritems():
print field, possible_values
See this answer for more information on iterating through dictionaries, such as using items()
, across python versions.
Since Python 3 iteritems()
is no longer supported. Use items()
instead.
for field, possible_values in fields.items():
print(field, possible_values)
In SQL Server Enterprise Manager, open \Server Objects\Linked Servers\Providers
, right click on the OraOLEDB.Oracle
provider, select properties and check the "Allow inprocess"
option. Recreate your linked server and test again.
You can also execute the following query if you don't have access to SQL Server Management Studio :
EXEC master.dbo.sp_MSset_oledb_prop N'OraOLEDB.Oracle', N'AllowInProcess', 1
At Microsoft website, it shows that native OLEDB provider is applied to SQL server directly and another OLEDB provider called OLEDB Provider for ODBC to access other Database, such as Sysbase, DB2 etc. There are different kinds of component under OLEDB Provider. See Distributed Queries on MSDN for more.
The accepted answer didn't work for me, I had to add a value to the href attribute:
<link rel="shortcut icon" href="#" />
As answered on a similar issue i found this to be working for me:
apkname.apk
file you want to know the hash of to the 'Java\jdk1.7.0_79\bin' folderkeytool -list -printcert -jarfile apkname.apk
SHA1
value and convert it using this siteYou could read the entire input line from scanner, then split the line by ,
then you have a String[]
, parse each number into int[]
with index one to one matching...(assuming valid input and no NumberFormatExceptions
) like
String line = scanner.nextLine();
String[] numberStrs = line.split(",");
int[] numbers = new int[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
// Note that this is assuming valid input
// If you want to check then add a try/catch
// and another index for the numbers if to continue adding the others (see below)
numbers[i] = Integer.parseInt(numberStrs[i]);
}
As YoYo's answer suggests, the above can be achieved more concisely in Java 8:
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();
To handle invalid input
You will need to consider what you want need to do in this case, do you want to know that there was bad input at that element or just skip it.
If you don't need to know about invalid input but just want to continue parsing the array you could do the following:
int index = 0;
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[index] = Integer.parseInt(numberStrs[i]);
index++;
}
catch (NumberFormatException nfe)
{
//Do nothing or you could print error if you want
}
}
// Now there will be a number of 'invalid' elements
// at the end which will need to be trimmed
numbers = Arrays.copyOf(numbers, index);
The reason we should trim the resulting array is that the invalid elements at the end of the int[]
will be represented by a 0
, these need to be removed in order to differentiate between a valid input value of 0
.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,10]
If you need to know about invalid input later you could do the following:
Integer[] numbers = new Integer[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[i] = Integer.parseInt(numberStrs[i]);
}
catch (NumberFormatException nfe)
{
numbers[i] = null;
}
}
In this case bad input (not a valid integer) the element will be null.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,null,10]
You could potentially improve performance by not catching the exception (see this question for more on this) and use a different method to check for valid integers.
Here an option using a list written on some range, populating an array that will be fiiltered. The information will be erased then the columns sorted.
Sub Filter_Out_Values()
'Automation to remove some codes from the list
Dim ws, ws1 As Worksheet
Dim myArray() As Variant
Dim x, lastrow As Long
Dim cell As Range
Set ws = Worksheets("List")
Set ws1 = Worksheets(8)
lastrow = ws.Cells(Application.Rows.Count, 1).End(xlUp).Row
'Go through the list of codes to exclude
For Each cell In ws.Range("A2:A" & lastrow)
If cell.Offset(0, 2).Value = "X" Then 'If the Code is associated with "X"
ReDim Preserve myArray(x) 'Initiate array
myArray(x) = CStr(cell.Value) 'Populate the array with the code
x = x + 1 'Increase array capacity
ReDim Preserve myArray(x) 'Redim array
End If
Next cell
lastrow = ws1.Cells(Application.Rows.Count, 1).End(xlUp).Row
ws1.Range("C2:C" & lastrow).AutoFilter field:=3, Criteria1:=myArray, Operator:=xlFilterValues
ws1.Range("A2:Z" & lastrow).SpecialCells(xlCellTypeVisible).ClearContents
ws1.Range("A2:Z" & lastrow).AutoFilter field:=3
'Sort columns
lastrow = ws1.Cells(Application.Rows.Count, 1).End(xlUp).Row
'Sort with 2 criteria
With ws1.Range("A1:Z" & lastrow)
.Resize(lastrow).Sort _
key1:=ws1.Columns("B"), order1:=xlAscending, DataOption1:=xlSortNormal, _
key2:=ws1.Columns("D"), order1:=xlAscending, DataOption1:=xlSortNormal, _
Header:=xlYes, MatchCase:=False, Orientation:=xlTopToBottom, SortMethod:=xlPinYin
End With
End Sub
To get employee names starting with A or B listed in order...
select employee_name
from employees
where employee_name LIKE 'A%' OR employee_name LIKE 'B%'
order by employee_name
If you are using Microsoft SQL Server you could use
....
where employee_name LIKE '[A-B]%'
order by employee_name
This is not standard SQL though it just gets translated to the following which is.
WHERE employee_name >= 'A'
AND employee_name < 'C'
For all variants you would need to consider whether you want to include accented variants such as Á
and test whether the queries above do what you want with these on your RDBMS and collation options.
console.cloud.google.com >> select project >> Networking > VPC network >> firewalls >> create firewall.
To apply the rule to VM instances, select Targets, "Specified target tags", and enter into "Target tags" the name of the tag. This tag will be used to apply the new firewall rule onto whichever instance you'd like.
in "Protocols and Ports" enter tcp:9090
Click Save.
The code snippet:
spyOn(myOtherService, "makeRemoteCallReturningPromise").and.callFake(function() {
var deferred = $q.defer();
deferred.resolve('Remote call result');
return deferred.promise;
});
Can be written in a more concise form:
spyOn(myOtherService, "makeRemoteCallReturningPromise").and.returnValue(function() {
return $q.resolve('Remote call result');
});
The problem is due to older version of ojdbc - ojdbc14.
Place the latest version of ojdbc jar file in your application or shared library. (Only one version should be there and it should be the latest one) As of today - ojdbc6.jar
Check the application libraries and shared libraries on server.
Some firewalls do that if a connection is idle for x number of minutes. Some ISPs set their routers to do that for various reasons as well.
In this day and age, you'll need to gracefully handle (re-establish as needed) that condition.
To find the Unix Timestamp in seconds:
moment().unix()
The documentation is your friend. :)
FOR FADE add this first line with your animation's object.
.animate().alpha(1).setDuration(2000);
You should not attempt to parse HTML with regex. HTML is not a regular language, so any regex you come up with will likely fail on some esoteric edge case. Please refer to the seminal answer to this question for specifics. While mostly formatted as a joke, it makes a very good point.
The following examples are Java, but the regex will be similar -- if not identical -- for other languages.
String target = someString.replaceAll("<[^>]*>", "");
Assuming your non-html does not contain any < or > and that your input string is correctly structured.
If you know they're a specific tag -- for example you know the text contains only <td>
tags, you could do something like this:
String target = someString.replaceAll("(?i)<td[^>]*>", "");
Edit: Omega brought up a good point in a comment on another post that this would result in multiple results all being squished together if there were multiple tags.
For example, if the input string were <td>Something</td><td>Another Thing</td>
, then the above would result in SomethingAnother Thing
.
In a situation where multiple tags are expected, we could do something like:
String target = someString.replaceAll("(?i)<td[^>]*>", " ").replaceAll("\\s+", " ").trim();
This replaces the HTML with a single space, then collapses whitespace, and then trims any on the ends.
The top answers here didn't work for me for a couple of reasons (un-commented code with a dead link and an incomplete solution). So I spent a few hours trying everyone's out and getting the best I could: here's mine, including jQuery and non-jQuery.
Note that jQuery normalizes the event object so some checks are missing. I've also narrowed it to all password fields (since that's the biggest reason to need it) and added a warning message. This has been tested in Chrome, Mozilla, Opera, and IE6-8. Stable and catches all capslock states EXCEPT when numbers or spaces are pressed.
/* check for CAPS LOCK on all password fields */
$("input[type='password']").keypress(function(e) {
var $warn = $(this).next(".capsWarn"); // handle the warning mssg
var kc = e.which; //get keycode
var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
// event.shiftKey does not seem to be normalized by jQuery(?) for IE8-
var isShift = ( e.shiftKey ) ? e.shiftKey : ( (kc == 16) ? true : false ); // shift is pressed
// uppercase w/out shift or lowercase with shift == caps lock
if ( (isUp && !isShift) || (isLow && isShift) ) {
$warn.show();
} else {
$warn.hide();
}
}).after("<span class='capsWarn error' style='display:none;'>Is your CAPSLOCK on?</span>");
Some of the other jQuery-less solutions lacked IE fallbacks. @Zappa patched it.
document.onkeypress = function ( e ) {
e = (e) ? e : window.event;
var kc = ( e.keyCode ) ? e.keyCode : e.which; // get keycode
var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
var isShift = ( e.shiftKey ) ? e.shiftKey : ( (kc == 16) ? true : false ); // shift is pressed -- works for IE8-
// uppercase w/out shift or lowercase with shift == caps lock
if ( (isUp && !isShift) || (isLow && isShift) ) {
alert("CAPSLOCK is on."); // do your thing here
} else {
// no CAPSLOCK to speak of
}
}
Note: Check out the solutions of @Borgar, @Joe Liversedge, and @Zappa, and the plugin developed by @Pavel Azanov, which I have not tried but is a good idea. If someone knows a way to expand the scope beyond A-Za-z, please edit away. Also, jQuery versions of this question are closed as duplicate, so that's why I'm posting both here.
Was this "cheating"? I just made my Configuration in the Startup class static, and then I can access it from anywhere else:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public static IConfiguration Configuration { get; set; }
You could either get your strings by index (System.out.println(S.get(0));
) or iterate through it:
for (String s : S) {
System.out.println(s);
}
For other ways to iterate through a list (and their implications) see traditional for loop vs Iterator in Java.
Additionally:
If you create an Audio element using:
var a = new Audio("my_audio_file.wav");
And add a suspend
event listener via:
a.addEventListener("suspend", function () {console.log('suspended')}, false);
And then load the file into mobile Safari (iPad or iPhone), you'll see the 'suspended' get logged in the developer console. According to the HTML5 spec, this means, "The user agent is intentionally not currently fetching media data, but does not have the entire media resource downloaded."
Calling a subsequent a.load(), testing for the "canplay" event and then using a.play() seems like a suitable method for auto triggering the sound.
If you're on Chrome, Firefox or IE10 + why not extend the console and use
(function() {
console.dump = function(object) {
if (window.JSON && window.JSON.stringify)
console.log(JSON.stringify(object));
else
console.log(object);
};
})();
for a concise, cross-browser solution.
you can replace all occurrence of any string/character using RegExp javasscript object.
Here is the code,
var mystring = 'okay.this.is.a.string';
var patt = new RegExp("\\.");
while(patt.test(mystring)){
mystring = mystring .replace(".","");
}
From the Linux Kernel source:
linux/include/asm-i386/hw_irq.h:
/*
* subtle. orig_eax is used by the signal code to distinct between
* system calls and interrupted 'random user-space'. Thus we have
* to put a negative value into orig_eax here. (the problem is that
* both system calls and IRQs want to have small integer numbers in
* orig_eax, and the syscall code has won the optimization conflict ;)
*
* Subtle as a pigs ear. VY
*/
graphics.h
appears to something once bundled with Borland and/or Turbo C++, in the 90's.
http://www.daniweb.com/software-development/cpp/threads/17709/88149#post88149
It's unlikely that you will find any support for that file with modern compiler. For other graphics libraries check the list of "related" questions (questions related to this one). E.g., "A Simple, 2d cross-platform graphics library for c or c++?".
You need to use jQuery to do this. This approach gives you the abbility to have dynamic images and do them round no matter the size.
My demo has one flaw right now I don't center the image in the container, but ill return to it in a minute (need to finish a script I'm working on).
<div class="container">
<img src="" class="image" alt="lambo" />
</div>
//script
var container = $('.container'),
image = container.find('img');
container.width(image.height());
//css
.container {
height: auto;
overflow: hidden;
border-radius: 50%;
}
.image {
height: 100%;
display: block;
}
grep -Fxq "String to be found" | ls -a
I took a look at the datejs and stripped out the code necessary to add months to a date handling edge cases (leap year, shorter months, etc):
Date.isLeapYear = function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
};
Date.getDaysInMonth = function (year, month) {
return [31, (Date.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};
Date.prototype.isLeapYear = function () {
return Date.isLeapYear(this.getFullYear());
};
Date.prototype.getDaysInMonth = function () {
return Date.getDaysInMonth(this.getFullYear(), this.getMonth());
};
Date.prototype.addMonths = function (value) {
var n = this.getDate();
this.setDate(1);
this.setMonth(this.getMonth() + value);
this.setDate(Math.min(n, this.getDaysInMonth()));
return this;
};
This will add "addMonths()" function to any javascript date object that should handle edge cases. Thanks to Coolite Inc!
Use:
var myDate = new Date("01/31/2012");
var result1 = myDate.addMonths(1);
var myDate2 = new Date("01/31/2011");
var result2 = myDate2.addMonths(1);
->> newDate.addMonths -> mydate.addMonths
result1 = "Feb 29 2012"
result2 = "Feb 28 2011"
I was working with a list of toasts (alert messages), List<Alert>
from C# and needed it as JavaScript array for Toastr in a partial view (.cshtml
file). The JavaScript code below is what worked for me:
var toasts = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(alerts));
toasts.forEach(function (entry) {
var command = entry.AlertStyle;
var message = entry.Message;
if (command === "danger") { command = "error"; }
toastr[command](message);
});
I think you are a bit confused on the purpose of custom data attributes. From the w3 spec
Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.
By itself an attribute of data-toggle=value
is basically a key-value pair, in which the key is "data-toggle" and the value is "value".
In the context of Bootstrap, the custom data in the attribute is almost useless without the context that their JavaScript library includes for the data. If you look at the non-minified version of bootstrap.js then you can do a search for "data-toggle" and find how it is being used.
Here is an example of Bootstrap JavaScript code that I copied straight from the file regarding the use of "data-toggle".
Button Toggle
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
else $parent.find('.active').removeClass('active')
}
if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
} else {
this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
}
if (changed) this.$element.toggleClass('active')
}
The context that the code provides shows that Bootstrap is using the data-toggle
attribute as a custom query selector to process the particular element.
From what I see these are the data-toggle options:
You may want to look at the Bootstrap JavaScript documentation to get more specifics of what each do, but basically the data-toggle
attribute toggles the element to active or not.
Because one moderator deleted my detailed image-supported answer on this question, just because I copied and pasted from another question, I am forced to put a less detailed answer and I will link the original answer if you want a more visual way to see the solution.
For Visual Studio 2019 and Visual Studio 2017 Users
For People who are missing this old feature in VS2019 (or maybe VS2017) from the old versions of Visual Studio
This feature still available, but it is NOT available by default, you have to install it separately.
see this answer also to see an image associated
https://stackoverflow.com/a/66289543/4390133
(whish that the moderator realized this is the same question and instead of deleting my answer, he could mark one of the questions as duplicated to the other)
Update to create a class-diagram for the whole project
I received a downvote because I did not mention how to generate a diagram for the whole project, here is how to do it (after applying the previous steps)
Preview Selected Items
is enabled in the solution explorer, disabled it temporarily, you can re-enable it lateryou could be shocked by the results to the point that you can change your mind and remove your downvote (please do NOT upvote, it is enough to remove your downvote)
you can do this with css3, this blurs the whole element
div (or whatever element) {
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
}
Fiddle: http://jsfiddle.net/H4DU4/
You shouldn't confuse arrays with lists.
This is a list: {...}
. It has no length or other Array properties.
This is an array: [...]
. You can use array functions, methods and so, like someone suggested here: someArray.toString()
;
someObj.toString();
will not work on any other object types, like lists.
create a keybinding for quickest way
{ "keys": ["super+alt+t"], "command": "unexpand_tabs", "args": { "set_translate_tabs": true } }
add this to Preferences > Key Bindings (user) when you press super+alt+t it will convert spaces to tabs
You can actually do what Chris Chalmers does in his answer, but you must make sure that HAML doesn't parse the JavaScript. This approach is actually useful when you need to use a different type than text/javascript
, which is was I needed to do for MathJax
.
You can use the plain
filter to keep HAML from parsing the script and throwing an illegal nesting error:
%script{type: "text/x-mathjax-config"}
:plain
MathJax.Hub.Config({
tex2jax: {
inlineMath: [["$","$"],["\\(","\\)"]]
}
});
Do you want something like in LINQ skip 5 and take 10?
SELECT TOP(10) * FROM MY_TABLE
WHERE ID not in (SELECT TOP(5) ID From My_TABLE);
This approach will work in any SQL version.
The only effective mechanism for passing parameters into a build is to use Java properties:
ant -Done=1 -Dtwo=2
The following example demonstrates how you can check and ensure the expected parameters have been passed into the script
<project name="check" default="build">
<condition property="params.set">
<and>
<isset property="one"/>
<isset property="two"/>
</and>
</condition>
<target name="check">
<fail unless="params.set">
Must specify the parameters: one, two
</fail>
</target>
<target name="build" depends="check">
<echo>
one = ${one}
two = ${two}
</echo>
</target>
</project>
I got the same error, when I was trying to import matplotlib.pyplot
In [1]: import matplotlib.pyplot as plt
...
...
ImportError: No module named PyQt4.QtCore
But in my case the problem was due to a missing linux library libGL.so.1
OS : Cent OS 64 bit
Python version : 3.5.2
$> locate libGL.so.1
If this command returns a value, your problem could be different, so please ignore my answer. If it does not return any value and your environment is same as mine, below steps would fix your problem.
$> yum install mesa-libGL.x86_64
This installs the necessary OpenGL libraries for 64 bit Cent OS.
$> locate libGL.so.1
/usr/lib/libGL.so.1
Now go back to iPython and try to import
In [1]: import matplotlib.pyplot as plt
This time it imported successfully.
It's creating the file in the same directory as your script. Try this instead.
$content = "some text here";
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
Methods like sleep()
and wait()
of class Thread
might throw an InterruptedException
. This will happen if some other thread
wanted to interrupt the thread
that is waiting or sleeping.
The simplest way is css transform:
.navbar-brand {
transform: translateX(-50%);
left: 50%;
position: absolute;
}
DEMO: http://codepen.io/candid/pen/dGPZvR
This way also works with dynamically sized background images for the logo and allows us to utilize the text-hide class:
CSS:
.navbar-brand {
background: url(http://disputebills.com/site/uploads/2015/10/dispute.png) center / contain no-repeat;
transform: translateX(-50%);
left: 50%;
position: absolute;
width: 200px; /* no height needed ... image will resize automagically */
}
HTML:
<a class="navbar-brand text-hide" href="http://disputebills.com">Brand Text
</a>
We can also use flexbox though. However, using this method we'd have to move navbar-brand
outside of navbar-header
. This way is great though because we can now have image and text side by side:
.brand-centered {
display: flex;
justify-content: center;
position: absolute;
width: 100%;
left: 0;
top: 0;
}
.navbar-brand {
display: flex;
align-items: center;
}
Demo: http://codepen.io/candid/pen/yeLZax
To only achieve these results on mobile simply wrap the above css inside a media query:
@media (max-width: 768px) {
}
Take a look from here https://www.regextester.com/?fam=114662
Use this following Regular Expression Details, This will support leap year also.
var reg = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([1][26]|[2468][048]|[3579][26])00))))$/g;
You can use such trick:
myObject = new ArrayList<Object>(myTempObject);
or use
myObject = (ArrayList<Object>)myTempObject.clone();
You can get some information about clone() method here
But you should remember, that all these ways will give you a copy of your List, not all of its elements. So if you change one of the elements in your copied List, it will also be changed in your original List.
No, but you can use the s///
substitution operator and the \s
whitespace assertion to get the same result.
@HostListener('window:click', ['$event']) onClick(event){ }
check this below link to detect CapsLock on click, keyup and keydown on current window. No need to add any event in html doc
To create a "drop down menu" you can use OptionMenu
in tkinter
Example of a basic OptionMenu
:
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
More information (including the script above) can be found here.
Creating an OptionMenu
of the months from a list would be as simple as:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
mainloop()
In order to retrieve the value the user has selected you can simply use a .get()
on the variable that we assigned to the widget, in the below case this is variable
:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
print ("value is:" + variable.get())
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.
I tried proposed solution and forward slash in the file name did not work for me, example: ...().getResourceAsStream("/my.properties"); null was returned
Removing the slash worked: ....getResourceAsStream("my.properties");
Here is from doc API: Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').
To expound on cletus' answer, at runtime all record of the generic types is removed. Generics are processed only in the compiler and are used to provide additional type safety. They are really just shorthand that allows the compiler to insert typecasts at the appropriate places. For example, previously you'd have to do the following:
List x = new ArrayList();
x.add(new SomeClass());
Iterator i = x.iterator();
SomeClass z = (SomeClass) i.next();
becomes
List<SomeClass> x = new ArrayList<SomeClass>();
x.add(new SomeClass());
Iterator<SomeClass> i = x.iterator();
SomeClass z = i.next();
This allows the compiler to check your code at compile-time, but at runtime it still looks like the first example.
Here's what I've learned as I determine the best way to move forward with a couple of my current app projects.
Async Storage (formerly "built-in" to React Native, now moved on its own)
I use AsyncStorage for an in-production app. Storage stays local to the device, is unencrypted (as mentioned in another answer), goes away if you delete the app, but should be saved as part of your device's backups and persists during upgrades (both native upgrades ala TestFlight and code upgrades via CodePush).
Conclusion: Local storage; you provide your own sync/backup solution.
SQLite
Other projects I have worked on have used sqlite3 for app storage. This gives you an SQL-like experience, with compressible databases that can also be transmitted to and from the device. I have not had any experience with syncing them to a back end, but I imagine various libraries exist. There are RN libraries for connecting to SQLite.
Data is stored in your traditional database format with databases, tables, keys, indices, etc. all saved to disk in a binary format. Direct access to the data is available via command line or apps that have SQLite drivers.
Conclusion: Local storage; you supply the sync and backup.
Firebase
Firebase offers, among other things, a real time noSQL database along with a JSON document store (like MongoDB) meant for keeping from 1 to n number of clients synchronized. The docs talk about offline persistence, but only for native code (Swift/Obj-C, Java). Google's own JavaScript option ("Web") which is used by React Native does not provide a cached storage option (see 2/18 update below). The library is written with the assumption that a web browser is going to be connecting, and so there will be a semi-persistent connection. You could probably write a local caching mechanism to supplement the Firebase storage calls, or you could write a bridge between the native libraries and React Native.
Update 2/2018 I have since found React Native Firebase which provides a compatible JavaScript interface to the native iOS and Android libraries (doing what Google probably could/should have done), giving you all the goodies of the native libraries with the bonus of React Native support. With Google's introduction of a JSON document store beside the real-time database, I'm giving Firebase a good second look for some real-time apps I plan to build.
The real-time database is stored as a JSON-like tree that you can edit on the website and import/export pretty simply.
Conclusion: With react-native-firebase, RN gets same benefits as Swift and Java. [/update] Scales well for network-connected devices. Low cost for low utilization. Combines nicely with other Google cloud offerings. Data readily visible and editable from their interface.
Realm
Update 4/2020 MongoDB has acquired Realm and is planning to combine it with MongoDB Stitch (discussed below). This looks very exciting.
Update 9/2020 Having used Realm vs. Stitch: Stitch API's essentially allowed a JS app (React Native or web) to talk directly to the Mongo database instead of going through an API server you build yourself.
Realm was meant to synchronize portions of the database whenever changes were made.
The combination of the two gets a little confusing. The formerly-known-as-Stitch API's still work like your traditional Mongo query and update calls, whereas the newer Realm stuff attaches to objects in code and handles synchronization all by itself... mostly. I'm still working through the right way to do things in one project, which is using SwiftUI, so it's a bit off-topic. But promising and neat nonetheless.
Also a real time object store with automagic network synchronization. They tout themselves as "device first" and the demo video shows how the devices handle sporadic or lossy network connectivity.
They offer a free version of the object store that you host on your own servers or in a cloud solution like AWS or Azure. You can also create in-memory stores that do not persist with the device, device-only stores that do not sync up with the server, read-only server stores, and the full read-write option for synchronization across one or more devices. They have professional and enterprise options that cost more up front per month than Firebase.
Unlike Firebase, all Realm capabilities are supported in React Native and Xamarin, just as they are in Swift/ObjC/Java (native) apps.
Your data is tied to objects in your code. Because they are defined objects, you do have a schema, and version control is a must for code sanity. Direct access is available via GUI tools Realm provides. On-device data files are cross-platform compatible.
Conclusion: Device first, optional synchronization with free and paid plans. All features supported in React Native. Horizontal scaling more expensive than Firebase.
iCloud
I honestly haven't done a lot of playing with this one, but will be doing so in the near future.
If you have a native app that uses CloudKit, you can use CloudKit JS to connect to your app's containers from a web app (or, in our case, React Native). In this scenario, you would probably have a native iOS app and a React Native Android app.
Like Realm, this stores data locally and syncs it to iCloud when possible. There are public stores for your app and private stores for each customer. Customers can even chose to share some of their stores or objects with other users.
I do not know how easy it is to access the raw data; the schemas can be set up on Apple's site.
Conclusion: Great for Apple-targeted apps.
Couchbase
Big name, lots of big companies behind it. There's a Community Edition and Enterprise Edition with the standard support costs.
They've got a tutorial on their site for hooking things up to React Native. I also haven't spent much time on this one, but it looks to be a viable alternative to Realm in terms of functionality. I don't know how easy it is to get to your data outside of your app or any APIs you build.
[Edit: Found an older link that talks about Couchbase and CouchDB, and CouchDB may be yet another option to consider. The two are historically related but presently completely different products. See this comparison.]
Conclusion: Looks to have similar capabilities as Realm. Can be device-only or synced. I need to try it out.
MongoDB
Update 4/2020
Mongo acquired Realm and plans to combine MongoDB Stitch (discussed below) with Realm (discussed above).
I'm using this server side for a piece of the app that uses AsyncStorage locally. I like that everything is stored as JSON objects, making transmission to the client devices very straightforward. In my use case, it's used as a cache between an upstream provider of TV guide data and my client devices.
There is no hard structure to the data, like a schema, so every object is stored as a "document" that is easily searchable, filterable, etc. Similar JSON objects could have additional (but different) attributes or child objects, allowing for a lot of flexibility in how you structure your objects/data.
I have not tried any client to server synchronization features, nor have I used it embedded. React Native code for MongoDB does exist.
Conclusion: Local only NoSQL solution, no obvious sync option like Realm or Firebase.
Update 2/2019
MongoDB has a "product" (or service) called Stitch. Since clients (in the sense of web browsers and phones) shouldn't be talking to MongoDB directly (that's done by code on your server), they created a serverless front-end that your apps can interface with, should you choose to use their hosted solution (Atlas). Their documentation makes it appear that there is a possible sync option.
This writeup from Dec 2018 discusses using React Native, Stitch, and MongoDB in a sample app, with other samples linked in the document (https://www.mongodb.com/blog/post/building-ios-and-android-apps-with-the-mongodb-stitch-react-native-sdk).
Twilio Sync
Another NoSQL option for synchronization is Twilio's Sync. From their site: "Sync lets you manage state across any number of devices in real time at scale without having to handle any backend infrastructure."
I looked at this as an alternative to Firebase for one of the aforementioned projects, especially after talking to both teams. I also like their other communications tools, and have used them for texting updates from a simple web app.
[Edit] I've spent some time with Realm since I originally wrote this. I like how I don't have to write an API to sync the data between the app and the server, similar to Firebase. Serverless functions also look to be really helpful with these two, limiting the amount of backend code I have to write.
I love the flexibility of the MongoDB data store, so that is becoming my choice for the server side of web-based and other connection-required apps.
I found RESTHeart, which creates a very simple, scalable RESTful API to MongoDB. It shouldn't be too hard to build a React (Native) component that reads and writes JSON objects to RESTHeart, which in turn passes them to/from MongoDB.
[Edit] I added info about how the data is stored. Sometimes it's important to know how much work you might be in for during development and testing if you've got to tweak and test the data.
Edits 2/2019 I experimented with several of these options when designing a high-concurrency project this past year (2018). Some of them mention hard and soft concurrency limits in their documentation (Firebase had a hard one at 10,000 connections, I believe, while Twilio's was a soft limit that could be bumped, according to discussions with both teams at AltConf).
If you are designing an app for tens to hundreds of thousands of users, be prepared to scale the data backend accordingly.
the term "smart pointer" includes shared pointers, auto pointers, locking pointers and others. you meant to say auto pointer (more ambiguously known as "owning pointer"), not smart pointer.
Dumb pointers (T*) are never the best solution. They make you do explicit memory management, which is verbose, error prone, and sometimes nigh impossible. But more importantly, they don't signal your intent.
Auto pointers delete the pointee at destruction. For arrays, prefer encapsulations like vector and deque. For other objects, there's very rarely a need to store them on the heap - just use locals and object composition. Still the need for auto pointers arises with functions that return heap pointers -- such as factories and polymorphic returns.
Shared pointers delete the pointee when the last shared pointer to it is destroyed. This is useful when you want a no-brainer, open-ended storage scheme where expected lifetime and ownership can vary widely depending on the situation. Due to the need to keep an (atomic) counter, they're a bit slower than auto pointers. Some say half in jest that shared pointers are for people who can't design systems -- judge for yourself.
For an essential counterpart to shared pointers, look up weak pointers too.
API is like the building blocks of some puzzling game that a child plays with to join blocks in different shapes and build something they can think of.
SDK, on the other hand, is a proper workshop where all of the development tools are available, rather than pre-shaped building blocks. In a workshop you have the actual tools and you are not limited to blocks, and can therefore make your own blocks, or can create something without any blocks to begin with.
coding without an SDK or API is like making everything from scratch without a workshop - you have to even make your own tools
First of all, thanks for guiding me and closing this issue. I found a way to fix this issue from your discussions. Yeah, Let's come to the point. The thing is I'm Using GoogleMapHelper v3 helper in CakePHP3. When i tried to open bootstrap modal popup, I got struck with the grey box issue over the map. It's been extended for 2 days. Finally i got a fix over this.
We need to Update the GoogleMapHelper to fix the issue
Need to add the below script in setCenterMap function
google.maps.event.trigger({$id}, \"resize\");
And need the include below code in JavaScript
google.maps.event.addListenerOnce({$id}, 'idle', function(){
setCenterMap(new google.maps.LatLng({$this->defaultLatitude},
{$this->defaultLongitude}));
});
actually, i think the best solution is described on this link:
http://blog.synyx.de/2011/11/android-listview-with-rounded-corners/
in short, it uses a different background for the top, middle and bottom items, so that the top and bottom ones would be rounded.
edit_text.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffff" />
<corners android:radius="5dp"/>
<stroke android:width="2dip" android:color="@color/button_color_submit" />
</shape>
use here
<EditText
-----
------
android:background="@drawable/edit_text.xml"
/>
Here is worked example See on Plunker
<body ng-controller="MainCtrl">
<input ng-model="search" type="text">
<br>
Showing {{data.length}} Persons; <br>
Filtered {{counted}}
<ul>
<li ng-repeat="person in data | filter:search">
{{person.name}}
</li>
</ul>
</body>
<script>
var app = angular.module('angularjs-starter', [])
app.controller('MainCtrl', function($scope, $filter) {
$scope.data = [
{
"name": "Jim", "age" : 21
}, {
"name": "Jerry", "age": 26
}, {
"name": "Alex", "age" : 25
}, {
"name": "Max", "age": 22
}
];
$scope.counted = $scope.data.length;
$scope.$watch("search", function(query){
$scope.counted = $filter("filter")($scope.data, query).length;
});
});
One should check if QtyToRepair
is updated at first.
ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
ON [dbo].[SCHEDULE]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF UPDATE (QtyToRepair)
BEGIN
UPDATE SCHEDULE
SET modified = GETDATE()
, ModifiedUser = SUSER_NAME()
, ModifiedHost = HOST_NAME()
FROM SCHEDULE S INNER JOIN Inserted I
ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
WHERE S.QtyToRepair <> I.QtyToRepair
END
END
By default it will be hidden in your home directory. Type ls -a ~
to view that.
you can give aviation to the view by adding z axis to it and can have default shadow to it. this feature was provided in L preview and will be available after it release. For now you can simply add a image the gives this look for button background
I was also getting the same issue. I resolved this issue by updating the chromedriver. So if anyone is facing same issue with chrome browser just update your chromedriver.
If you are using ActionBarSherlock, you can get the height with
@dimen/abs__action_bar_default_height
This is not how you initialize an array, but for:
The first declaration:
char buf[10] = "";
is equivalent to
char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
The second declaration:
char buf[10] = " ";
is equivalent to
char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};
The third declaration:
char buf[10] = "a";
is equivalent to
char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
As you can see, no random content: if there are fewer initializers, the remaining of the array is initialized with 0
. This the case even if the array is declared inside a function.
\D
is a non-digit, and so then \D*
is any number of non-digits in a row. So your whole string should match ^\D*$
.
Check on http://rubular.com/r/AoWBmrbUkN it works perfectly.
You can also try on http://regexpal.com/ OR http://www.regextester.com/
You can use the listings package. It supports many different languages and there are lots of options for customising the output.
\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[language=html]
<html>
<head>
<title>Hello</title>
</head>
<body>Hello</body>
</html>
\end{lstlisting}
\end{document}
It is just a hint for the Service Provider on what to expect from the NameID returned by the Identity Provider. It can be:
unspecified
emailAddress
– e.g. [email protected]
X509SubjectName
– e.g. CN=john,O=Company Ltd.,C=US
WindowsDomainQualifiedName
– e.g. CompanyDomain\John
kerberos
– e.g. john@realm
entity
– this one in used to identify entities that provide SAML-based services and looks like a URIpersistent
– this is an opaque service-specific identifier which must include a pseudo-random value and must not be traceable to the actual user, so this is a privacy feature.transient
– opaque identifier which should be treated as temporary.This is borderline programming, but look into using tr:
$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'
Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.
The following script works for me for multiple values of $COLUMNS
. I wonder if you are not setting COLUMNS
prior to this call?
#!/bin/bash
COLUMNS=30
svn diff $@ --diff-cmd /usr/bin/diff -x "-y -w -p -W $COLUMNS"
Can you echo $COLUMNS
inside your script to see if it set correctly?
Try $(this).load("/file_name.html");
. This method targets a local file.
You can also target remote files (on another domain) take a look at: http://en.wikipedia.org/wiki/Same_origin_policy
Depending on your use case, you can use an image which has already been created and specify it's name in docker-compose
.
We have a production use case where our CI server builds a named Docker image. (docker build -t <specific_image_name> .
). Once the named image is specified, our docker-compose
always builds off of the specific image. This allows a couple of different possibilities:
1- You can ensure that where ever you run your docker-compose
from, you will always be using the latest version of that specific image.
2- You can specify multiple named images in your docker-compose
file and let them be auto-wired through the previous build step.
So, if your image is already built, you can name the image with docker-compose
. Remove build
and specify image:
wildfly:
image: my_custom_wildfly_image
container_name: wildfly_server
ports:
- 9990:9990
- 80:8080
environment:
- MYSQL_HOST=mysql_server
- MONGO_HOST=mongo_server
- ELASTIC_HOST=elasticsearch_server
volumes:
- /Volumes/CaseSensitive/development/wildfly/deployments/:/opt/jboss/wildfly/standalone/deployments/
links:
- mysql:mysql_server
- mongo:mongo_server
- elasticsearch:elasticsearch_server
JVM is the virtual machine Java code executes on
JRE is the environment (standard libraries and JVM) required to run Java applications
JDK is the JRE with developer tools and documentations
OpenJDK is an open-source version of the JDK, unlike the common JDK owned by Oracle
It's all about performance and development speed. Of course, if you are a good programmer and design something that is really tailored to your needs, you might achieve better performance than if you had used a Javascript framework. But do you have the time to do it all by yourself?
My personal opinion is that Javascript is incredibly useful and overused, but that if you really need it, a framework is the way to go.
Now comes the choice of the framework. For what benchmarks are worth, you can find one at http://ejohn.org/files/142/ . It also depends on which plugins are available and what you intend to do with them. I started using jQuery because it seemed to be maintained and well featured, even though it wasn't the fastest at that moment. I do not regret it but I didn't test anything else since then.
If you don't want to convert the entire Map into an array beforehand, and/or destructure key-value arrays, you can use this silly function:
/**_x000D_
* Map over an ES6 Map._x000D_
*_x000D_
* @param {Map} map_x000D_
* @param {Function} cb Callback. Receives two arguments: key, value._x000D_
* @returns {Array}_x000D_
*/_x000D_
function mapMap(map, cb) {_x000D_
let out = new Array(map.size);_x000D_
let i = 0;_x000D_
map.forEach((val, key) => {_x000D_
out[i++] = cb(key, val);_x000D_
});_x000D_
return out;_x000D_
}_x000D_
_x000D_
let map = new Map([_x000D_
["a", 1],_x000D_
["b", 2],_x000D_
["c", 3]_x000D_
]);_x000D_
_x000D_
console.log(_x000D_
mapMap(map, (k, v) => `${k}-${v}`).join(', ')_x000D_
); // a-1, b-2, c-3
_x000D_
In my project I use this function for getting huge amount of files. It's pretty fast (put require("FS")
out to make it even faster):
var _getAllFilesFromFolder = function(dir) {
var filesystem = require("fs");
var results = [];
filesystem.readdirSync(dir).forEach(function(file) {
file = dir+'/'+file;
var stat = filesystem.statSync(file);
if (stat && stat.isDirectory()) {
results = results.concat(_getAllFilesFromFolder(file))
} else results.push(file);
});
return results;
};
usage is clear:
_getAllFilesFromFolder(__dirname + "folder");
There seems to be no way to place buttons (drawings, images) within cells in a way that would allow them to be linked to Apps Script functions.
This being said, there are some things that you can indeed do:
You can place images within cells using IMAGE(URL)
, but they cannot be linked to Apps Script functions.
You can place images within cells and link them to URLs using:
=HYPERLINK("http://example.com"; IMAGE("http://example.com/myimage.png"; 1))
You can create drawings as described in the answer of @Eduardo and they can be linked to Apps Script functions, but they will be stand-alone items that float freely "above" the spreadsheet and cannot be positioned in cells. They cannot be copied from cell to cell and they do not have a row or col position that the script function could read.
After=
dependency is only effective when service including After=
and service included by After=
are both scheduled to start as part of your boot up.
Ex:
a.service
[Unit]
After=b.service
This way, if both a.service
and b.service
are enabled, then systemd will order b.service
after a.service
.
If I am not misunderstanding, what you are asking is how to start b.service
when a.service
starts even though b.service
is not enabled.
The directive for this is Wants=
or Requires=
under [Unit]
.
website.service
[Unit]
Wants=mongodb.service
After=mongodb.service
The difference between Wants=
and Requires=
is that with Requires=
, a failure to start b.service
will cause the startup of a.service
to fail, whereas with Wants=
, a.service
will start even if b.service
fails. This is explained in detail on the man page of .unit
.
abort()
sends the calling process the SIGABRT
signal, this is how abort()
basically works.
abort()
is usually called by library functions which detect an internal error or some seriously broken constraint. For example malloc()
will call abort()
if its internal structures are damaged by a heap overflow.
".do" is the "standard" extension mapped to for Struts Java platform. See http://struts.apache.org/ .
I usually use:
l = [ word.strip() for word in text.split(',') ]
the strip
remove spaces around words.
Try these simple steps to create random numbers:
Create function:
private int randomnumber(int min, int max)
{
Random rnum = new Random();
return rnum.Next(min, max);
}
Use the above function in a location where you want to use random numbers. Suppose you want to use it in a text box.
textBox1.Text = randomnumber(0, 999).ToString();
0 is min and 999 is max. You can change the values to whatever you want.
The CPPFLAGS
macro is the one to use to specify #include
directories.
Both CPPFLAGS
and CFLAGS
work in your case because the make
(1) rule combines both preprocessing and compiling in one command (so both macros are used in the command).
You don't need to specify .
as an include-directory if you use the form #include "..."
. You also don't need to specify the standard compiler include directory. You do need to specify all other include-directories.
In my case I had to do this, because none of the suggested solutions were available:
List<SubProduct> subProducts = Model.subproduct.Cast<SubProduct>().ToList();
A clean way to do it is using format_exc()
and then parse the output to get the relevant part:
from traceback import format_exc
try:
1/0
except Exception:
print 'the relevant part is: '+format_exc().split('\n')[-2]
Regards
If you're at the top level - or able to cleanly get to the top level - of the thread, then just returning is nice. Throwing an exception isn't as clean, as you need to be able to check that nothing's going to catch the exception and ignore it.
The reason you need to use Thread.currentThread()
in order to call interrupt()
is that interrupt()
is an instance method - you need to call it on the thread you want to interrupt, which in your case happens to be the current thread. Note that the interruption will only be noticed the next time the thread would block (e.g. for IO or for a monitor) anyway - it doesn't mean the exception is thrown immediately.
If you're using Bootstrap Sass, here's another way that avoids having to add extra classes to your element markup:
@import "bootstrap/mixins/_border-radius";
@import "bootstrap/_variables";
.your-class {
$r: $border-radius-base; // or $border-radius-large, $border-radius-small, ...
@include border-top-radius($r);
@include border-bottom-radius($r);
}
According to this posting by the lead Jenkins developer, Kohsuke Kawaguchi, in 2009, there is no group support for the built-in Jenkins user database. Group support is only usable when integrating Jenkins with LDAP or Active Directory. This appears to be the same in 2012.
However, as Vadim wrote in his answer, you don't need group support for the built-in Jenkins user database, thanks to the Role strategy plug-in.
Create your file then return a reference to it with the correct header to trigger the Save As - edit the following as needed. Put your CSV data into $csvdata.
$fname = 'myCSV.csv';
$fp = fopen($fname,'wb');
fwrite($fp,$csvdata);
fclose($fp);
header('Content-type: application/csv');
header("Content-Disposition: inline; filename=".$fname);
readfile($fname);
Similarly to the approved answer. If you want to create an array from dictionary keys:
np.array( tuple(dict.keys()) )
If you want to create an array from dictionary values:
np.array( tuple(dict.values()) )
April 2020
Full steps to get current location, and avoid Last Known Location nullability.
According to official documentation, Last Known Location could be Null in case of:
In this case, you should requestLocationUpdates and receive the new location on the LocationCallback.
By the following steps your last known Location never null.
Pre-requisite: EasyPermission library
Step 1: In manifest file add this permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Step 2:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Create location callback when it's ready.
createLocationCallback()
//createing location request, how mant request would be requested.
createLocationRequest()
//Build check request location setting request
buildLocationSettingsRequest()
//FusedLocationApiClient which includes location
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
//Location setting client
mSettingsClient = LocationServices.getSettingsClient(this)
//Check if you have ACCESS_FINE_LOCATION permission
if (!EasyPermissions.hasPermissions(
this@MainActivity,
Manifest.permission.ACCESS_FINE_LOCATION)) {
requestPermissionsRequired()
}
else{
//If you have the permission we should check location is opened or not
checkLocationIsTurnedOn()
}
}
Step 3: Create required functions to be called in onCreate()
private fun requestPermissionsRequired() {
EasyPermissions.requestPermissions(
this,
getString(R.string.location_is_required_msg),
LOCATION_REQUEST,
Manifest.permission.ACCESS_FINE_LOCATION
)
}
private fun createLocationCallback() {
//Here the location will be updated, when we could access the location we got result on this callback.
mLocationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
super.onLocationResult(locationResult)
mCurrentLocation = locationResult.lastLocation
}
}
}
private fun buildLocationSettingsRequest() {
val builder = LocationSettingsRequest.Builder()
builder.addLocationRequest(mLocationRequest!!)
mLocationSettingsRequest = builder.build()
builder.setAlwaysShow(true)
}
private fun createLocationRequest() {
mLocationRequest = LocationRequest.create()
mLocationRequest!!.interval = 0
mLocationRequest!!.fastestInterval = 0
mLocationRequest!!.numUpdates = 1
mLocationRequest!!.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
public fun checkLocationIsTurnedOn() { // Begin by checking if the device has the necessary location settings.
mSettingsClient!!.checkLocationSettings(mLocationSettingsRequest)
.addOnSuccessListener(this) {
Log.i(TAG, "All location settings are satisfied.")
startLocationUpdates()
}
.addOnFailureListener(this) { e ->
val statusCode = (e as ApiException).statusCode
when (statusCode) {
LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> {
try {
val rae = e as ResolvableApiException
rae.startResolutionForResult(this@MainActivity, LOCATION_IS_OPENED_CODE)
} catch (sie: IntentSender.SendIntentException) {
}
}
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {
mRequestingLocationUpdates = false
}
}
}
}
private fun startLocationUpdates() {
mFusedLocationClient!!.requestLocationUpdates(
mLocationRequest,
mLocationCallback, null
)
}
Step 4:
Handle callbacks in onActivityResult() after ensuring the location is opened or the user accepts to open it in.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
LOCATION_IS_OPENED_CODE -> {
if (resultCode == AppCompatActivity.RESULT_OK) {
Log.d(TAG, "Location result is OK")
} else {
activity?.finish()
}
}
}
Step 5: Get last known location from FusedClientApi
override fun onMapReady(map: GoogleMap) {
mMap = map
mFusedLocationClient.lastLocation.addOnSuccessListener {
if(it!=null){
locateUserInMap(it)
}
}
}
private fun locateUserInMap(location: Location) {
showLocationSafetyInformation()
if(mMap!=null){
val currentLocation = LatLng(location.latitude,location.longitude )
addMarker(currentLocation)
}
}
private fun addMarker(currentLocation: LatLng) {
val cameraUpdate = CameraUpdateFactory.newLatLng(currentLocation)
mMap?.clear()
mMap?.addMarker(
MarkerOptions().position(currentLocation)
.title("Current Location")
)
mMap?.moveCamera(cameraUpdate)
mMap?.animateCamera(cameraUpdate)
mMap?.setMinZoomPreference(14.0f);
}
I hope this would help.
Happy Coding
os.walk
can be used if you need recursion:
import os
start_path = '.' # current directory
for path,dirs,files in os.walk(start_path):
for filename in files:
print os.path.join(path,filename)
I've faced the simpler problem and the solution i came up with was applying a transparent bachground THEME. Write these lines in your styles
<item name="android:windowBackground">@drawable/blue_searchbuttonpopupbackground</item>
</style>
<style name="Theme.Transparent" parent="android:Theme">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
And then add
android:theme="@style/Theme.Transparent"
in your main manifest file , inside the block of the dialog activity.
Plus in your dialog activity XML set
android:background= "#00000000"
You can access entire column as a range using the Worksheet.Columns
object
Something like:
Worksheets(sheetname).Columns(1).ClearContents
should clear contents of A column
There is also the Worksheet.Rows
object if you need to do something similar for rows
The error you are receiving is likely due to a missing with block.
You can read about with blocks here: Microsoft Help
Your regular expression [^a-zA-Z0-9]\s/g
says match any character that is not a number or letter followed by a space.
Remove the \s and you should get what you are after if you want a _ for every special character.
var newString = str.replace(/[^A-Z0-9]/ig, "_");
That will result in hello_world___hello_universe
If you want it to be single underscores use a + to match multiple
var newString = str.replace(/[^A-Z0-9]+/ig, "_");
That will result in hello_world_hello_universe
The low-cost method, regardless of the vendor implementation, would be to select something from the process memory or the server memory, like the DB version or the name of the current database. IsClosed is very poorly implemented.
Example:
java.sql.Connection conn = <connect procedure>;
conn.close();
try {
conn.getMetaData();
} catch (Exception e) {
System.out.println("Connection is closed");
}
The rvest
along with xml2
is another popular package for parsing html web pages.
library(rvest)
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
file<-read_html(theurl)
tables<-html_nodes(file, "table")
table1 <- html_table(tables[4], fill = TRUE)
The syntax is easier to use than the xml
package and for most web pages the package provides all of the options ones needs.
Simply put the following one. This works for me.
$('.className').datepicker('setDate', 'now');
Variables declared inside the class definition, but not inside a method are class or static variables:
>>> class MyClass:
... i = 3
...
>>> MyClass.i
3
As @millerdev points out, this creates a class-level i
variable, but this is distinct from any instance-level i
variable, so you could have
>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)
This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance.
See what the Python tutorial has to say on the subject of classes and class objects.
@Steve Johnson has already answered regarding static methods, also documented under "Built-in Functions" in the Python Library Reference.
class C:
@staticmethod
def f(arg1, arg2, ...): ...
@beidy recommends classmethods over staticmethod, as the method then receives the class type as the first argument, but I'm still a little fuzzy on the advantages of this approach over staticmethod. If you are too, then it probably doesn't matter.
here is another solution...
System.IO.Stream st = new System.IO.StreamReader (picturePath).BaseStream;
byte[] buffer = new byte[4096];
System.IO.MemoryStream m = new System.IO.MemoryStream ();
while (st.Read (buffer,0,buffer.Length) > 0) {
m.Write (buffer, 0, buffer.Length);
}
imgView.Tag = m.ToArray ();
st.Close ();
m.Close ();
hope it helps!
I got the same error but I solved by using regsvr32.exe in C:\Windows\SysWOW64. Because we use x64 system. So if your machine is also x64, the ocx/dll must registered also with regsvr32 x64 version
Well to just to have some saying about semicolon. In lot of country, comma is what use for decimal not period. Mostly EU colonies, which consist of half of the world, another half follow UK standard (how the hell UK so big O_O) so in turn make using comma for database that include number create much of the headache because Excel refuse to recognize it as delimiter.
Like wise in my country, Viet Nam, follow France's standard, our partner HongKong use UK standard so comma make CSV unusable, and we use \t or ; instead for international use, but it still not "standard" per the document of CSV.
#define twop22 (0x1.0p+22)
#define ABS(x) (fabs(x))
#define isFloatInteger(x) ((ABS(x) >= twop22) || (((ABS(x) + twop22) - twop22) == ABS(x)))
Well, the "last five rows" are actually the last five rows depending on your clustered index. Your clustered index, by definition, is the way that he rows are ordered. So you really can't get the "last five rows" without some order. You can, however, get the last five rows as it pertains to the clustered index.
SELECT TOP 5 * FROM MyTable
ORDER BY MyCLusteredIndexColumn1, MyCLusteredIndexColumnq, ..., MyCLusteredIndexColumnN DESC
This problem occurs because of UAC and only when you are running IE on the same computer SSRS is on.
To fix it, you have to add an AD group of the users with read priviledges to the actual SSRS website directories and push the security down. UAC is dumb in how if you are an admin on the box. It won't let you access the data unless you also have access to the data through other means such as a non-administrator AD group that is applied to the files.
Use JSTL tag libraries in JSP. That will work perfectly.
I improved the tütü response to properly disable EditText and RadioButton componentes. Besides, I'm sharing a way that I found to change the view visibility and add transparency in the disabled views.
private static void disableEnableControls(ViewGroup view, boolean enable){
for (int i = 0; i < view.getChildCount(); i++) {
View child = view.getChildAt(i);
child.setEnabled(enable);
if (child instanceof ViewGroup){
disableEnableControls((ViewGroup)child, enable);
}
else if (child instanceof EditText) {
EditText editText = (EditText) child;
editText.setEnabled(enable);
editText.setFocusable(enable);
editText.setFocusableInTouchMode(enable);
}
else if (child instanceof RadioButton) {
RadioButton radioButton = (RadioButton) child;
radioButton.setEnabled(enable);
radioButton.setFocusable(enable);
radioButton.setFocusableInTouchMode(enable);
}
}
}
public static void setLayoutEnabled(ViewGroup view, boolean enable) {
disableEnableControls(view, enable);
view.setEnabled(enable);
view.setAlpha(enable? 1f: 0.3f);
}
public static void setLayoutEnabled(ViewGroup view, boolean enable, boolean visibility) {
disableEnableControls(view, enable);
view.setEnabled(enable);
view.setAlpha(enable? 1f: 0.3f);
view.setVisibility(visibility? View.VISIBLE: View.GONE);
}
One of the ways to kill a process on a port is to use the python library: freeport (https://pypi.python.org/pypi/freeport/0.1.9) . Once installed, simply:
# install freeport
pip install freeport
# Once freeport is installed, use it as follows
$ freeport 3000
Port 3000 is free. Process 16130 killed successfully
It depends on how you define your multi-dimensional array. Here are two options:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
// First
string[,] arr1 = {
{ "aa", "aaa" },
{ "bb", "bbb" }
};
// Second
string[][] arr2 = new[] {
new[] { "aa", "aaa" },
new[] { "bb", "bbb" }
};
// Iterate through first
for (int x = 0; x <= arr1.GetUpperBound(0); x++)
for (int y = 0; y <= arr1.GetUpperBound(1); y++)
Console.Write(arr1[x, y] + "; ");
Console.WriteLine(Environment.NewLine);
// Iterate through second second
foreach (string[] entry in arr2)
foreach (string element in entry)
Console.Write(element + "; ");
Console.WriteLine(Environment.NewLine);
Console.WriteLine("Press any key to finish");
Console.ReadKey();
}
}
}
You can use the Directory.GetFiles method
Also see Directory.GetFiles Method (String, String, SearchOption)
You can specify the search option in this overload.
TopDirectoryOnly: Includes only the current directory in a search.
AllDirectories: Includes the current directory and all the subdirectories in a search operation. This option includes reparse points like mounted drives and symbolic links in the search.
// searches the current directory and sub directory
int fCount = Directory.GetFiles(path, "*", SearchOption.AllDirectories).Length;
// searches the current directory
int fCount = Directory.GetFiles(path, "*", SearchOption.TopDirectoryOnly).Length;
I vote for the dictionary.
I find that if I make a function that returns anything more than 2-3 variables I'll fold them up in a dictionary. Otherwise I tend to forget the order and content of what I'm returning.
Also, introducing a 'special' structure makes your code more difficult to follow. (Someone else will have to search through the code to find out what it is)
If your concerned about type look up, use descriptive dictionary keys, for example, 'x-values list'.
def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return {'y0':y0, 'y1':y1 ,'y2':y2 }
This answer applies to Jackson versions prior to 2+ (originally written for 1.8). See @SupunSameera's answer for a version that works with newer versions of Jackson.
The JSON terms for "node name" is "key." Since JsonNode#iterator()
does not include keys, you need to iterate differently:
for (Map.Entry<String, JsonNode> elt : rootNode.fields())
{
if ("foo".equals(elt.getKey()))
{
// bar
}
}
If you only need to see the keys, you can simplify things a bit with JsonNode#fieldNames()
:
for (String key : rootNode.fieldNames())
{
if ("foo".equals(key))
{
// bar
}
}
And if you just want to find the node with key "foo"
, you can access it directly. This will yield better performance (constant-time lookup) and cleaner/clearer code than using a loop:
JsonNode foo = rootNode.get("foo");
if (foo != null)
{
// frob that widget
}
Since you're using jQuery, you just need to attach to some specific events and some pre defined animations:
$('#cat').hover(function()
{
// Mouse Over Callback
}, function()
{
// Mouse Leave callback
});
Then, to do the animation, you simply need to call the fadeOut / fadeIn animations:
$('#dog').fadeOut(750 /* Animation Time */, function()
{
// animation complete callback
$('#cat').fadeIn(750);
});
Combining the two together, you would simply insert the animations in the hover callbacks (something like so, use this as a reference point):
$('#cat').hover(function()
{
if($('#dog').is(':visible'))
$('#dog').fadeOut(750 /* Animation Time */, function()
{
// animation complete callback
$('#cat').fadeIn(750);
});
}, function()
{
// Mouse Leave callback
});
Use the remainder operator (also known as the modulo operator) which returns the remainder of the division and check if it is zero:
if (j % 4 == 0) {
// j is an exact multiple of 4
}
Make sure that the string is in the following JSON format which is something like this:
{"result":"success","testid":"1"} (with " ") .
If not, then you can add "responsetype => json"
in your request params.
Then use json_decode($response,true)
to convert it into an array.
The trick of appending "*" can be made to work when the new extension is shorter. You need to pad the new extension with blanks, which can only be done by enclosing the destination file name in quotes. For example:
xcopy foo.shtml "foo.html *"
This will copy and rename without prompting.
"That's not a bug, it's a feature!" (I once saw a VW Beetle in the Microsoft parking lot with the vanity plate "FEATURE".) These semantics for rename go all the way back to when I wrote DOS v.1. Characters in the new name are substituted one by one for characters in the old name, unless a wildcard character (? or *) is present in the new name. Without adding the blank(s) to the new name, remaining characters are copied from the old name.
To add a bit to accepted answer ...
If you get an UnfinishedStubbingException
, be sure to set the method to be stubbed after the when
closure, which is different than when you write Mockito.when
Mockito.doNothing().when(mock).method() //method is declared after 'when' closes
Mockito.when(mock.method()).thenReturn(something) //method is declared inside 'when'
A couple things
(a) you cant have both background-color and background, background will always win. in the example below, i combined them through shorthand, but this will produce the color only as a fallback method when the image does not show.
(b) no-scroll does not work, i don't believe it is a valid property of a background-image. try something like fixed:
.button:after {
content: "";
width: 30px;
height: 30px;
background:red url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") no-repeat -30px -50px fixed;
top: 10px;
right: 5px;
position: absolute;
display: inline-block;
}
I updated your jsFiddle to this and it showed the image.
On your remote machine, System.Data.OracleClient need access to some of the oracle dll which are not part of .Net. Solutions:
On your local machine most probably path to Oracle Client is already added in Path environment variable to there required dll are available to application but not on remote machine
You can also use findIndex and pick to achieve the same result:
var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];
var data = {id: 2, name: 'Person 2 (updated)'};
var index = _.findIndex(arr, _.pick(data, 'id'));
if( index !== -1) {
arr.splice(index, 1, data);
} else {
arr.push(data);
}
I would say "Yes". As "Matz" had said something like this in one of his talks, "Ruby objects have no types." Not all of it but the part that he is trying to get across to us. Why would anyone have said "Everything is an Object" then? To add he said "Data has Types not objects".
So we might enjoy this.
https://www.youtube.com/watch?v=1l3U1X3z0CE
But Ruby doesn't care to much about the type of object just the class. We use classes not types. All data then has a class.
12345.class
'my string'.class
They may also have ancestors
Object.ancestors
They also have meta classes but I'll save you the details on that.
Once you know the class then you'll be able to lookup what methods you may use for it. That's where the "data type" is needed. If you really want to get into details the look up...
"The Ruby Object Model"
This is the term used for how Ruby handles objects. It's all internal so you don't really see much of this but it's nice to know. But that's another topic.
Yes! The class is the data type. Objects have classes and data has types. So if you know about data bases then you know there are only a finite set of types.
text blocks numbers
I was losing the will to live over this error, RN telling me that an imported file ./Foo
did not exist when it was right there!
The actual underlying error was not a typo but actually in another file that ./Foo
imported.
Be careful. If you are writing JSX
anywhere (eg. in ./Bar
):
<Bar>...</Bar>
then you must have:
import * as React from 'react'
(or similar)
present in that file (./Bar
).
When the syntactic sugar (angled brackets) is transpiled it naively spits out something like:
React.createComponent(...)
And if React
has not explicitly been imported this reference will be invalid, so the evaluation of this dependent file subsequently fails.
Unfortunately the result is that consequently ./Foo
(as well as ./Bar
) will be unavailable in your app, and thus RN says unhelpful things like module not found
and Indeed, none of these files exist
.
Hope that helps.
ps. you can also experience similar misery if you have circular dependencies between files! Such fun!
When you return something from a then()
callback, it's a bit magic. If you return a value, the next then()
is called with that value. However, if you return something promise-like, the next then()
waits on it, and is only called when that promise settles (succeeds/fails).
Source: https://web.dev/promises/#queuing-asynchronous-actions
DataSource is vendor-specific, for MySql you could use MysqlDataSource which is provided in the MySql Java connector jar:
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setDatabaseName("xyz");
dataSource.setUser("xyz");
dataSource.setPassword("xyz");
dataSource.setServerName("xyz.yourdomain.com");
@Autowired
to autowire(or search) by-type
@Qualifier
to autowire(or search) by-name
Other alternate option for @Qualifier
is @Primary
@Component
@Qualifier("beanname")
public class A{}
public class B{
//Constructor
@Autowired
public B(@Qualifier("beanname")A a){...} // you need to add @autowire also
//property
@Autowired
@Qualifier("beanname")
private A a;
}
//If you don't want to add the two annotations, we can use @Resource
public class B{
//property
@Resource(name="beanname")
private A a;
//Importing properties is very similar
@Value("${property.name}") //@Value know how to interpret ${}
private String name;
}
more about @value
I was also facing the same issue where I was receiving the Transaction_Date as YYYYMMDD in bigint format. So I converted it into Datetime format using below query and saved it in new column with datetime format. I hope this will help you as well.
SELECT
convert( Datetime, STUFF(STUFF(Transaction_Date, 5, 0, '-'), 8, 0, '-'), 120) As [Transaction_Date_New]
FROM mydb
You main Index.html file for Angular can use the body tag as the ng-view. Then all you need to do is include a script tag at the bottom of whatever page is being pulled into Index.html by Angular like so:
<script type="text/javascript">
$( function() {
$( "#mydatepickerid" ).datepicker({changeMonth: true, changeYear: true,
yearRange: '1930:'+new Date().getFullYear(), dateFormat: "yy-mm-dd"});
});
</script>
Why overcomplicate things??
This will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are doing is generally correct.
set.py:
import sys
sys.path.append("/tmp/TEST")
loop.py
import sys
import time
while True:
print sys.path
time.sleep(1)
run: python loop.py &
This will run loop.py, connected to your STDOUT, and it will continue to run in the background. You can then run python set.py
. Each has a different set of environment variables. Observe that the output from loop.py
does not change because set.py
does not change loop.py
's environment.
A note on importing
Python imports are dynamic, like the rest of the language. There is no static linking going on. The import is an executable line, just like sys.path.append...
.
I resolved the issue by double checking the "libs" directory and removing redundant jars, even though those jars were not manually added in the dependencies.
I think that Spring Data ignores the FetchMode. I always use the @NamedEntityGraph
and @EntityGraph
annotations when working with Spring Data
@Entity
@NamedEntityGraph(name = "GroupInfo.detail",
attributeNodes = @NamedAttributeNode("members"))
public class GroupInfo {
// default fetch mode is lazy.
@ManyToMany
List<GroupMember> members = new ArrayList<GroupMember>();
…
}
@Repository
public interface GroupRepository extends CrudRepository<GroupInfo, String> {
@EntityGraph(value = "GroupInfo.detail", type = EntityGraphType.LOAD)
GroupInfo getByGroupName(String name);
}
Check the documentation here
I have some edit, best working for collections:
Public Function Contains(col As collection, key As Variant) As Boolean_x000D_
Dim obj As Object_x000D_
On Error GoTo err_x000D_
Contains = True_x000D_
Set obj = col.Item(key)_x000D_
Exit Function_x000D_
_x000D_
err:_x000D_
Contains = False_x000D_
End Function
_x000D_
Call clearAnimation()
on whichever View
you called startAnimation()
.
Let's say you have two activities.
And on click of a Button, this happens.
1) Enable Content Transition
Go to your style.xml
and add this line to enable the content transition.
<item name="android:windowContentTransitions">true</item>
2) Write Default Enter and Exit Transition for your AllCastActivity
public void setAnimation()
{
if(Build.VERSION.SDK_INT>20) {
Slide slide = new Slide();
slide.setSlideEdge(Gravity.LEFT);
slide.setDuration(400);
slide.setInterpolator(new AccelerateDecelerateInterpolator());
getWindow().setExitTransition(slide);
getWindow().setEnterTransition(slide);
}
}
3) Start Activity with Intent
Write this method in Your MovieDetailActivity
to start AllCastActivity
public void startActivity(){
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putStringArrayListExtra(MOVIE_LIST, movie.getImages());
if(Build.VERSION.SDK_INT>20)
{
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(BlankActivity.this);
startActivity(i,options.toBundle());
}
else {
startActivity(i);
}
}
put your setAnimation()
method before setContentView()
method otherwise the animation will not work.
So your AllCastActivity.java
should look like this
class AllCastActivity extends AppcompatActivity {
@Override
protected void onCreate(Bundle savedInstaceState)
{
super.onCreate(savedInstaceState);
setAnimation();
setContentView(R.layout.all_cast_activity);
.......
}
private void setAnimation(){
if(Build.VERSION.SDK_INT>20) {
Slide slide = new Slide();
slide.setSlideEdge(Gravity.LEFT);
..........
}
}
Just for future reference, if you already have a boolean column and you just want to add a default do:
ALTER TABLE users
ALTER COLUMN priv_user SET DEFAULT false;
New in python 3.8, you can pass a delimiter argument to the hex
function, as in this example
>>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'
I am using this class for time in this format "hh:mm:ss" u can use it with "hh:mm:00" (zero seconds) for your example. Here is the complete code. It has compare and between function and also checks the time format (in case of invalid time and throws TimeException). Hope you can use it or modify it for your needs.
Time class:
package es.utility.time;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author adrian
*/
public class Time {
private int hours; //Hours of the day
private int minutes; //Minutes of the day
private int seconds; //Seconds of the day
private String time; //Time of the day
/**
* Constructor of Time class
*
* @param time
* @throws TimeException if time parameter is not valid
*/
public Time(String time) throws TimeException {
//Check if valid time
if (!validTime(time)) {
throw new TimeException();
}
//Init class parametars
String[] params = time.split(":");
this.time = time;
this.hours = Integer.parseInt(params[0]);
this.minutes = Integer.parseInt(params[1]);
this.seconds = Integer.parseInt(params[2]);
}
/**
* Constructor of Time class
*
* @param hours
* @param minutes
* @param seconds
* @throws TimeException if time parameter is not valid
*/
public Time(int hours, int minutes, int seconds) throws TimeException {
//Check if valid time
if (!validTime(hours, minutes, seconds)) {
throw new TimeException();
}
this.time = timeToString(hours, minutes, seconds);
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
/**
* Checks if the sting can be parsed as time
*
* @param time (correct from hh:mm:ss)
* @return true if ok <br/> false if not ok
*/
private boolean validTime(String time) {
String regex = "([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(time);
return m.matches();
}
/**
* Checks if the sting can be parsed as time
*
* @param hours hours
* @param minutes minutes
* @param seconds seconds
* @return true if ok <br/> false if not ok
*/
private boolean validTime(int hours, int minutes, int seconds) {
return hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59 && seconds >= 0 && seconds <= 59;
}
/**
* From Integer values to String time
*
* @param hours
* @param minutes
* @param seconds
* @return String generated from int values for hours minutes and seconds
*/
private String timeToString(int hours, int minutes, int seconds) {
StringBuilder timeBuilder = new StringBuilder("");
if (hours < 10) {
timeBuilder.append("0").append(hours);
} else {
timeBuilder.append(hours);
}
timeBuilder.append(":");
if (minutes < 10) {
timeBuilder.append("0").append(minutes);
} else {
timeBuilder.append(minutes);
}
timeBuilder.append(":");
if (seconds < 10) {
timeBuilder.append("0").append(seconds);
} else {
timeBuilder.append(seconds);
}
return timeBuilder.toString();
}
/**
* Compare this time to other
*
* @param compare
* @return -1 time is before <br/> 0 time is equal <br/> time is after
*/
public int compareTime(Time compare) {
//Check hours
if (this.getHours() < compare.getHours()) { //If hours are before return -1
return -1;
}
if (this.getHours() > compare.getHours()) { //If hours are after return 1
return 1;
}
//If no return hours are equeal
//Check minutes
if (this.getMinutes() < compare.getMinutes()) { //If minutes are before return -1
return -1;
}
if (this.getMinutes() > compare.getMinutes()) { //If minutes are after return 1
return 1;
}
//If no return minutes are equeal
//Check seconds
if (this.getSeconds() < compare.getSeconds()) { //If minutes are before return -1
return -1;
}
if (this.getSeconds() > compare.getSeconds()) { //If minutes are after return 1
return 1;
}
//If no return seconds are equeal and return 0
return 0;
}
public boolean isBetween(Time before, Time after) throws TimeException{
if(before.compareTime(after)== 1){
throw new TimeException("Time 'before' is after 'after' time");
}
//Compare with before and after
if (this.compareTime(before) == -1 || this.compareTime(after) == 1) { //If time is before before time return false or time is after after time
return false;
} else {
return true;
}
}
public int getHours() {
return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public int getSeconds() {
return seconds;
}
public void setSeconds(int seconds) {
this.seconds = seconds;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
/**
* Override the toString method and return all of the class private
* parameters
*
* @return String Time{" + "hours=" + hours + ", minutes=" + minutes + ",
* seconds=" + seconds + ", time=" + time + '}'
*/
@Override
public String toString() {
return "Time{" + "hours=" + hours + ", minutes=" + minutes + ", seconds=" + seconds + ", time=" + time + '}';
}
}
TimeException class:
package es.utility.time;
/**
*
* @author adrian
*/
public class TimeException extends Exception {
public TimeException() {
super("Cannot create time with this params");
}
public TimeException(String message) {
super(message);
}
}
http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells
CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
If your Service is started by your app then actually your service is running on main process. so when app is killed service will also be stopped. So what you can do is, send broadcast from onTaskRemoved
method of your service as follows:
Intent intent = new Intent("com.android.ServiceStopped");
sendBroadcast(intent);
and have an broadcast receiver which will again start a service. I have tried it. service restarts from all type of kills.
This is not an answer to the original question. But, as an original question is not a real-world problem it should not be a problem. I tried to explain to a friend what are promises in JavaScript and the difference between promise and callback.
Code below serves as an explanation:
//very basic callback example using setTimeout
//function a is asynchronous function
//function b used as a callback
function a (callback){
setTimeout (function(){
console.log ('using callback:');
let mockResponseData = '{"data": "something for callback"}';
if (callback){
callback (mockResponseData);
}
}, 2000);
}
function b (dataJson) {
let dataObject = JSON.parse (dataJson);
console.log (dataObject.data);
}
a (b);
//rewriting above code using Promise
//function c is asynchronous function
function c () {
return new Promise(function (resolve, reject) {
setTimeout (function(){
console.log ('using promise:');
let mockResponseData = '{"data": "something for promise"}';
resolve(mockResponseData);
}, 2000);
});
}
c().then (b);
^
matches position just before the first character of the string$
matches position just after the last character of the string.
matches a single character. Does not matter what character it is, except newline*
matches preceding match zero or more timesSo, ^.*$
means - match, from beginning to end, any character that appears zero or more times. Basically, that means - match everything from start to end of the string. This regex pattern is not very useful.
Let's take a regex pattern that may be a bit useful. Let's say I have two strings The bat of Matt Jones
and Matthew's last name is Jones
. The pattern ^Matt.*Jones$
will match Matthew's last name is Jones
. Why? The pattern says - the string should start with Matt and end with Jones and there can be zero or more characters (any characters) in between them.
Feel free to use an online tool like https://regex101.com/ to test out regex patterns and strings.
This error usually appears when you're missing a file from the jQuery UI set.
Double-check that you have all the files, the jQuery UI files as well as the CSS and images, and that they're in the correctly linked file/directory location on your server.
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
//section.SectionInformation.UnprotectSection();
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
config.Save();
The last 9 elements can be read from left to right using numlist[-9:], or from right to left using numlist[:-10:-1], as you want.
>>> a=range(17)
>>> print a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[-9:]
[8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[:-10:-1]
[16, 15, 14, 13, 12, 11, 10, 9, 8]
I know there are many answers already but the best one that worked for me for a complex json structure is:
var arr = [{ "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCSW", "desc": "SOUTHWEST", "code": "RCSW", "level": 0, "save": "RCSW : SOUTHWEST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCSW", "desc": "SOUTHWEST", "code": "RCSW", "level": 0, "save": "RCSW : SOUTHWEST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RCSW", "desc": "SOUTHWEST", "code": "RCSW", "level": 0, "save": "RCSW : SOUTHWEST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RCNW", "desc": "MIDWEST", "code": "RCNW", "level": 0, "save": "RCNW : MIDWEST", "attribute1": "", "attribute2": "" }, { "State": "RCSW", "desc": "SOUTHWEST", "code": "RCSW", "level": 0, "save": "RCSW : SOUTHWEST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCNW", "desc": "MIDWEST", "code": "RCNW", "level": 0, "save": "RCNW : MIDWEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCNW", "desc": "MIDWEST", "code": "RCNW", "level": 0, "save": "RCNW : MIDWEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCNW", "desc": "MIDWEST", "code": "RCNW", "level": 0, "save": "RCNW : MIDWEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }];_x000D_
_x000D_
var clean = arr.filter((arr, index, self) =>_x000D_
index === self.findIndex((t) => (t.save === arr.save && t.State === arr.State)))_x000D_
_x000D_
console.log(clean);
_x000D_
You can try this directly to chrome browser console and edit according to your need.
I hope this helps someone.
Here you are not fitting a normal distribution. Replacing sns.distplot(data)
by sns.distplot(data, fit=norm, kde=False)
should do the trick.
Local storage: It keeps store the user information data without expiration date this data will not be deleted when user closed the browser windows it will be available for day, week, month and year.
//Set the value in a local storage object
localStorage.setItem('name', myName);
//Get the value from storage object
localStorage.getItem('name');
//Delete the value from local storage object
localStorage.removeItem(name);//Delete specifice obeject from local storege
localStorage.clear();//Delete all from local storege
Session Storage: It is same like local storage date except it will delete all windows when browser windows closed by a web user.
//set the value to a object in session storege
sessionStorage.myNameInSession = "Krishna";
Read More Click
If you're using IDLE, and the Norwegian keyboard makes Ctrl-[ a problem, you can change the key.
I tried putting in shift-Tab and that worked nicely.
If writing to a protected file, @drAlberT and @rubo77 's answers might not work for you since one can't sudo >>
. A similarly simple solution, then, would be to use tee --append
(or, on MacOS, tee -a
):
LINE='include "/configs/projectname.conf"'
FILE=lighttpd.conf
grep -qF "$LINE" "$FILE" || echo "$LINE" | sudo tee --append "$FILE"
The ALTER TABLE
statement presented by Chris should work, but first you need to declare the columns NOT NULL
. All parts of a primary key need to be NOT NULL
.
Be carefull that the page does not contain any empty component which has "required" attribute as "true" before your selectOneMenu component running.
If you use a component such as
<p:inputText label="Nm:" id="id_name" value="#{ myHelper.name}" required="true"/>
then,
<p:selectOneMenu .....></p:selectOneMenu>
and forget to fill the required component, ajax listener of selectoneMenu cannot be executed.
To answer the updated part of your question: to style the drawer icon/arrow, you have two options:
To do this, override drawerArrowStyle
in your theme like so:
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
<item name="drawerArrowStyle">@style/MyTheme.DrawerArrowToggle</item>
</style>
<style name="MyTheme.DrawerArrowToggle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="color">@android:color/holo_purple</item>
<!-- ^ this will make the icon purple -->
</style>
This is probably not what you want, because the ActionBar itself should have consistent styling with the arrow, so, most probably, you want the option two:
Override the android:actionBarTheme
(actionBarTheme
for appcompat) attribute of the global application theme with your own theme (which you probably should derive from ThemeOverlay.Material.ActionBar/ThemeOverlay.AppCompat.ActionBar
) like so:
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
<item name="actionBarTheme">@style/MyTheme.ActionBar</item>
</style>
<style name="MyTheme.ActionBar" parent="ThemeOverlay.AppCompat.ActionBar">
<item name="android:textColorPrimary">@android:color/white</item>
<!-- ^ this will make text and arrow white -->
<!-- you can also override drawerArrowStyle here -->
</style>
An important note here is that when using a custom layout with a Toolbar
instead of stock ActionBar implementation (e.g. if you're using the DrawerLayout
-NavigationView
-Toolbar
combo to achieve the Material-style drawer effect where it's visible under translucent statusbar), the actionBarTheme
attribute is obviosly not picked up automatically (because it's meant to be taken care of by the AppCompatActivity
for the default ActionBar
), so for your custom Toolbar
don't forget to apply your theme manually:
<!--inside your custom layout with DrawerLayout
and NavigationView or whatever -->
<android.support.v7.widget.Toolbar
...
app:theme="?actionBarTheme">
-- this will resolve to either AppCompat's default ThemeOverlay.AppCompat.ActionBar
or your override if you set the attribute in your derived theme.
PS a little comment about the drawerArrowStyle
override and the spinBars
attribute -- which a lot of sources suggest should be set to true
to get the drawer/arrow animation. Thing is, spinBars
it is true
by default in AppCompat (check out the Base.Widget.AppCompat.DrawerArrowToggle.Common
style), you don't have to override actionBarTheme
at all to get the animation working. You get the animation even if you do override it and set the attribute to false
, it's just a different, less twirly animation. The important thing here is to use ActionBarDrawerToggle
, it's what pulls in the fancy animated drawable.
For developers using VB.NET
Private Function GetCheckedRadio(container) As RadioButton
For Each control In container.Children
Dim radio As RadioButton = TryCast(control, RadioButton)
If radio IsNot Nothing AndAlso radio.IsChecked Then
Return radio
End If
Next
Return Nothing
End Function
I think the xpath query you want goes something like this:
/xml/box[@stepId="$stepId"]/components/component[@id="$componentId"]/variables/variable[@nom="Enabled" and @valeur="Yes"]
This should get you the variables that are named "Enabled" with a value of "Yes" for the specified $stepId and $componentId. This is assuming that your xml starts with an tag like you show, and not
If the SQL Server 2005 XPath stuff is pretty straightforward (I've never used it), then the above query should work. Otherwise, someone else may have to help you with that.
In my project with netcore 2.2 I use this code:
[HttpGet]
[Route( "something" )]
public IActionResult GetSomething()
{
string payload = "Something";
OkObjectResult result = Ok( payload );
// currently result.Formatters is empty but we'd like to ensure it will be so in the future
result.Formatters.Clear();
// force response as xml
result.Formatters.Add( new Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter() );
return result;
}
It forces only one action within a controller to return a xml without effect to other actions. Also this code doesn't contain neither HttpResponseMessage or StringContent or ObjectContent which are disposable objects and hence should be handled appropriately (it is especially a problem if you use any of code analyzers that reminds you about it).
Going further you could use a handy extension like this:
public static class ObjectResultExtensions
{
public static T ForceResultAsXml<T>( this T result )
where T : ObjectResult
{
result.Formatters.Clear();
result.Formatters.Add( new Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter() );
return result;
}
}
And your code will become like this:
[HttpGet]
[Route( "something" )]
public IActionResult GetSomething()
{
string payload = "Something";
return Ok( payload ).ForceResultAsXml();
}
In addition, this solution looks like an explicit and clean way to force return as xml and it is easy to add to your existent code.
P.S. I used fully-qualified name Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter just to avoid ambiguity.
You can find globally installed modules by the command
npm list -g
It will provide you the location where node.js modules have been installed.
C:\Users\[Username]\AppData\Roaming\npm
If you install node.js modules locally in a folder, you can type the following command to see the location.
npm list
Swift 4.2
Result:
testButton.on(.touchUpInside) { (sender, event) in
// You can use any reference initialized before the code block here
// You can access self by adding [weak self] before (sender, event)
// You can then either make self strong by using a guard statement or use a optional operator (?)
print("user did press test button")
}
In the file UIButton+Events.swift
I've created an extension method for UIButton
that binds a UIControl.Event
to a completion handler called EventHandler
:
import UIKit
fileprivate var bindedEvents: [UIButton:EventBinder] = [:]
fileprivate class EventBinder {
let event: UIControl.Event
let button: UIButton
let handler: UIButton.EventHandler
let selector: Selector
required init(
_ event: UIControl.Event,
on button: UIButton,
withHandler handler: @escaping UIButton.EventHandler
) {
self.event = event
self.button = button
self.handler = handler
self.selector = #selector(performEvent(on:ofType:))
button.addTarget(self, action: self.selector, for: event)
}
deinit {
button.removeTarget(self, action: selector, for: event)
if let index = bindedEvents.index(forKey: button) {
bindedEvents.remove(at: index)
}
}
}
private extension EventBinder {
@objc func performEvent(on sender: UIButton, ofType event: UIControl.Event) {
handler(sender, event)
}
}
extension UIButton {
typealias EventHandler = (UIButton, UIControl.Event) -> Void
func on(_ event: UIControl.Event, handler: @escaping EventHandler) {
bindedEvents[self] = EventBinder(event, on: self, withHandler: handler)
}
}
The reason why I used a custom class for binding the event is to be able to dispose the reference later when the button is deintialised. This will prevent a possible memory leak from occurring. This wasn't possible within the UIButton
its extension, because I'm not allowed to implement a property nor the deinit
method.
The 2019 optimal solution for this is HTTP/2 Server Push.
You do not need any hacky javascript solutions or inline styles. However, you do need a server that supports HTTP 2.0 (any modern server version will), which itself requires your server to run SSL. However, with Let's Encrypt there's no reason not to be using SSL anyway.
My site https://r.je/ has a 100/100 score for both mobile and desktop.
The reason for these errors is that the browser gets the HTML, then has to wait for the CSS to be downloaded before the page can be rendered. Using HTTP2 you can send both the HTML and the CSS at the same time.
You can use HTTP/2 push by setting the Link header.
Apache example (.htaccess):
Header add Link "</style.css>; as=style; rel=preload, </font.css>; as=style; rel=preload"
For NGINX you can add the header to your location tag in the server configuration:
location = / {
add_header Link "</style.css>; as=style; rel=preload, </font.css>; as=style; rel=preload";
}
With this header set, the browser receives the HTML and CSS at the same time which stops the CSS from blocking rendering.
You will want to tweak it so that the CSS is only sent on the first request, but the Link header is the most complete and least hacky solution to "Eliminate Render Blocking Javascript and CSS"
For a detailed discussion, take a look at my post here: Eliminate Render Blocking CSS using HTTP/2 Push
Check example link below and click on the div to get the color value in hex.
var color = '';_x000D_
$('div').click(function() {_x000D_
var x = $(this).css('backgroundColor');_x000D_
hexc(x);_x000D_
console.log(color);_x000D_
})_x000D_
_x000D_
function hexc(colorval) {_x000D_
var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);_x000D_
delete(parts[0]);_x000D_
for (var i = 1; i <= 3; ++i) {_x000D_
parts[i] = parseInt(parts[i]).toString(16);_x000D_
if (parts[i].length == 1) parts[i] = '0' + parts[i];_x000D_
}_x000D_
color = '#' + parts.join('');_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class='div' style='background-color: #f5b405'>Click me!</div>
_x000D_
Check working example at http://jsfiddle.net/DCaQb/