If you wants to know how aria-label
helps you practically .. then follow the steps ... you will get it by your own ..
Create a html page having below code
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<button title="Close"> X </button>
<br />
<br />
<br />
<br />
<button aria-label="Back to the page" title="Close" > X </button>
</body>
</html>
Now, you need a virtual screen reader emulator which will run on browser to observe the difference. So, chrome browser users can install chromevox extension and mozilla users can go with fangs screen reader addin
Once done with installation, put headphones in your ears, open the html page and make focus on both button(by pressing tab) one-by-one .. and you can hear .. focusing on first x button
.. will tell you only x button
.. but in case of second x button
.. you will hear back to the page button
only..
i hope you got it well now!!
I think you are right by saying that people cannot click half pixels, so personally, I would use rounded jQuery offset...
A nice and easy way for those people who always forget the command axhline
is the following
plt.plot(x, [y]*len(x))
In your case xs = x
and y = 40
.
If len(x) is large, then this becomes inefficient and you should really use axhline
.
I tried restart: always
, it works at some containers(like php-fpm), but i faced the problem that some containers(like nginx) is still not restarting after reboot.
Solved the problem.
crontab -e
@reboot (sleep 30s ; cd directory_has_dockercomposeyml ; /usr/local/bin/docker-compose up -d )&
"SELECT "+_ID+" , "+_DESCRIPTION +","+_CREATED_DATE +","+_DATE_TIME+" FROM "+TBL_NOTIFICATION+" ORDER BY "+"strftime(%s,"+_DATE_TIME+") DESC";
Simplest idea as mentioned:
[WatchedFileHandler][1]
. The reasons for this handler are discussed in detail here, but in short there are certain worse race conditions with the other logging handlers. This one has the shortest window for the race condition.
Date and time input is accepted in almost any reasonable format, including ISO 8601, SQL-compatible, traditional POSTGRES, and others. For some formats, ordering of month, day, and year in date input is ambiguous and there is support for specifying the expected ordering of these fields.
In other words: just write anything and it will work.
Or check this table with all the unambiguous formats.
To see the window height while (or after) it is resized, try it:
$(window).resize(function() {
$('body').prepend('<div>' + $(window).height() - 46 + '</div>');
});
select @i:=uuid();
update some_table set guid = (@i:=uuid());
lambda
is a Python keyword that is used to generate anonymous functions.
>>> (lambda x: x+2)(3)
5
public static bool AreAllCellsEmpty(DataRow row)
{
if (row == null) throw new ArgumentNullException("row");
for (int i = row.Table.Columns.Count - 1; i >= 0; i--)
if (!row.IsNull(i))
return false;
return true;
}
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
To get the content of a directory you can use
$files = Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files\"
Then you can loop over this variable as well:
for ($i=0; $i -lt $files.Count; $i++) {
$outfile = $files[$i].FullName + "out"
Get-Content $files[$i].FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}
An even easier way to put this is the foreach
loop (thanks to @Soapy and @MarkSchultheiss):
foreach ($f in $files){
$outfile = $f.FullName + "out"
Get-Content $f.FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}
How to POST mixed data: File, String[], String in one request.
You can use only what you need.
private String doPOST(File file, String[] array, String name) {
RestTemplate restTemplate = new RestTemplate(true);
//add file
LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("file", new FileSystemResource(file));
//add array
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://my_url");
for (String item : array) {
builder.queryParam("array", item);
}
//add some String
builder.queryParam("name", name);
//another staff
String result = "";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
new HttpEntity<>(params, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(
builder.build().encode().toUri(),
HttpMethod.POST,
requestEntity,
String.class);
HttpStatus statusCode = responseEntity.getStatusCode();
if (statusCode == HttpStatus.ACCEPTED) {
result = responseEntity.getBody();
}
return result;
}
The POST request will have File in its Body and next structure:
POST https://my_url?array=your_value1&array=your_value2&name=bob
To translate your *nix style command script to windows/command batch style it would go like this:
SET PROJ_HOME=%USERPROFILE%/proj/111
SET PROJECT_BASEDIR=%PROJ_HOME%/exercises/ex1
mkdir "%PROJ_HOME%"
mkdir on windows doens't have a -p parameter : from the MKDIR /? help:
MKDIR creates any intermediate directories in the path, if needed.
which basically is what mkdir -p (or --parents for purists) on *nix does, as taken from the man guide
Yesterday, I shortened the code (just added <Provider store={store}>
) and still got this invalid hook call problem. This made me suddenly realized what mistake I did: I didn't install the react-redux software in that folder.
I had installed this software in the other project folder, so I didn't realize this one also needed it. After installing it, the error is gone.
"commentLine" is the name of function you are looking for. This function coment and uncoment with the same keybinding
Download the developer edition. There you can choose Express as license when installing.
Inspired by Mohit's answer in this thread. Applicable only for Java 8.
The following can be used to copy everything recursively from one folder to another:
public static void main(String[] args) throws IOException {
Path source = Paths.get("/path/to/source/dir");
Path destination = Paths.get("/path/to/dest/dir");
List<Path> sources = Files.walk(source).collect(toList());
List<Path> destinations = sources.stream()
.map(source::relativize)
.map(destination::resolve)
.collect(toList());
for (int i = 0; i < sources.size(); i++) {
Files.copy(sources.get(i), destinations.get(i));
}
}
Stream-style FTW.
Upd 2019-06-10: important note - close the stream (e.g. using try-with-resource) acquired by Files.walk call. Thanks to @jannis for the point.
This works for me:
https://www.linkedin.com/shareArticle?mini=true&url=articleUrl&title=YourarticleTitle&summary=YourarticleSummary&source=YourarticleSource
You can use this link by replacing it with your content. It works 100%.
If you are using rest template, you can use this piece of code
fun getClientHttpRequestFactory(): ClientHttpRequestFactory {
val timeout = envTimeout.toInt()
val config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout)
.build()
val acceptingTrustStrategy = TrustStrategy { chain: Array<X509Certificate?>?, authType: String? -> true }
val sslContext: SSLContext = SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build()
val csf = SSLConnectionSocketFactory(sslContext)
val client = HttpClientBuilder
.create()
.setDefaultRequestConfig(config)
.setSSLSocketFactory(csf)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build()
return HttpComponentsClientHttpRequestFactory(client)
}
@Bean
fun getRestTemplate(): RestTemplate {
return RestTemplate(getClientHttpRequestFactory())
}
http://www.exocortex.org/dsp/ is an open-source C# mathematics library with FFT algorithms.
I think you are not asking the right question--
A string in python has no property corresponding to 'ascii', utf-8, or any other encoding. The source of your string (whether you read it from a file, input from a keyboard, etc.) may have encoded a unicode string in ascii to produce your string, but that's where you need to go for an answer.
Perhaps the question you can ask is: "Is this string the result of encoding a unicode string in ascii?" -- This you can answer by trying:
try:
mystring.decode('ascii')
except UnicodeDecodeError:
print "it was not a ascii-encoded unicode string"
else:
print "It may have been an ascii-encoded unicode string"
E:>move "blogger code.txt" d:/"blogger code.txt"
1 file(s) moved.
"blogger code.txt" is a file name
The file move from E: drive to D: drive
Instant i = Instant.ofEpochSecond(cal.getTime);
Read more here and here
I too had this problem after updating to the latest Xcode Beta. The settings on the simulator are refreshed, so the laptop (external) keyboard was being detected. If you simply press:
iOS Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard
so that the entry is UNchecked then the software keyboard will be displayed once again.
I tried this, but it is not possible to remove "Watch on YouTube" icon. Following solution of mine does not remove the icon itself but "blocks" the mouse hover so that watch on YouTube is not click-able. I added a div over icon, so no mouseover will be affected for that logo.
<div class="holder">
<div class="frame" id="player" style="height 350"></div>
<div class="bar" id="bottom-layer">.</div>
</div>
Where frame is my embedded player. include following to your css file
.holder{
position:relative;
width:640px;
height:350px;
}
.frame{
width: 100%;
height:100%;
}
.bar{
position:absolute;
bottom:0;
right:0;
width:100%;
height:40px;
}
This is not full solution but helps you if you are bothered with users' getting full youtube url.
Do this.
var x=parseInt(document.forms["frmOrder"]["txtTotal"].value);
var y=parseInt(document.forms["frmOrder"]["totalpoints"].value);
In theory and by the specification, these are safe basically anywhere, except the domain name. Percent-encode anything not listed, and you're good to go.
A-Z a-z 0-9 - . _ ~ ( ) ' ! * : @ , ;
Only safe when used within specific URL components; use with care.
Paths: + & =
Queries: ? /
Fragments: ? / # + & =
According to the URI specification (RFC 3986), all other characters must be percent-encoded. This includes:
<space> <control-characters> <extended-ascii> <unicode>
% < > [ ] { } | \ ^
If maximum compatibility is a concern, limit the character set to A-Z a-z 0-9 - _ . (with periods only for filename extensions).
Even if valid per the specification, a URL can still be "unsafe", depending on context. Such as a file:/// URL containing invalid filename characters, or a query component containing "?", "=", and "&" when not used as delimiters. Correct handling of these cases are generally up to your scripts and can be worked around, but it's something to keep in mind.
Here the code with getting the error message working with MSSQL Server 2016:
BEGIN TRY
BEGIN TRANSACTION
-- Do your stuff that might fail here
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRAN
DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE()
DECLARE @ErrorSeverity INT = ERROR_SEVERITY()
DECLARE @ErrorState INT = ERROR_STATE()
-- Use RAISERROR inside the CATCH block to return error
-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH
I just restarted the adb (Android Debug Bridge) this way:
and it works again!
You can use object-fit property:
.my-image {
width: 100px;
height: 100px;
object-fit: contain;
}
This will fit image, without changing the proportionally.
You are right that it should work; perhaps you forgot to instantiate something. Does your code look something like this?
String rssFeedURL = "http://stackoverflow.com";
this.rssFeedURLS = new ArrayList<String>();
this.rssFeedURLS.add(rssFeedURL);
if(this.rssFeedURLs.contains(rssFeedURL)) {
// this code will execute
}
For reference, note that the following conditional will also execute if you append this code to the above:
String copyURL = new String(rssFeedURL);
if(this.rssFeedURLs.contains(copyURL)) {
// code will still execute because contains() checks equals()
}
Even though (rssFeedURL == copyURL) is false, rssFeedURL.equals(copyURL) is true. The contains method cares about the equals method.
I usually:
rake db:migrate VERSION=XXX
on all environments, to the version before the one I want to delete.rake db:migrate
again.If your application is already on production or staging, it's safer to just write another migration that destroys your table or columns.
Another great reference for migrations is: http://guides.rubyonrails.org/migrations.html
Function FileExists(fullFileName As String) As Boolean
FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function
I faced this problem
Forbidden You don't have permission to access /phpmyadmin/ on this server
Some help about this:
First check you installed a fresh wamp or replace the existing one. If it's fresh there is no problem, For done existing installation.
Follow these steps.
Another alternative to the accepted answer that avoids any issues with matrix multiplication:
def MSE(Y, YH):
return np.square(Y - YH).mean()
From the documents for np.square: "Return the element-wise square of the input."
Wrong method was used for errors, here is the working code:
BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
Since this page is the number 1 result for the google search "c++ floating point exception", I want to add another thing that can cause such a problem: use of undefined variables.
It looks like you've just finished step 3. Instead of running a function, you just print out a statement. A function is defined in the following way:
def addstudent():
print("Student Added.")
then called by writing addstudent()
.
I would recommend using a while
loop for your input. You can define the menu option outside the loop, put the print statement inside the loop, and do while(#valid option is not picked)
, then put the if statements after the while. Or you can do a while
loop and continue
the loop if a valid option is not selected.
Additionally, a dictionary is defined in the following way:
my_dict = {key:definition,...}
Replace this :
$('#subscription_order_form').submit(function(e){
e.preventDefault();
});
with this:
$('#subscription_order_form').on('keydown', function(e){
if (e.which===13) e.preventDefault();
});
That will prevent the form from submitting when Enter key is pressed as it prevents the default action of the key, but the form will submit normally on click.
JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"].ToList<JToken>();
foreach (JToken attribute in attributes)
{
JProperty jProperty = attribute.ToObject<JProperty>();
string propertyName = jProperty.Name;
}
I used builder in home-grown messaging library. The library core was receiving data from the wire, collecting it with Builder instance, then, once Builder decided it've got everything it needed to create a Message instance, Builder.GetMessage() was constructing a message instance using the data collected from the wire.
\if what you have posted is exactly what you are using then your problem is a bit obvious. Now assuming in your web.config you have you connection string defined like this
<add name="SiteSqlServer" connectionString="Data Source=(local);Initial Catalog=some_db;User ID=sa;Password=uvx8Pytec" providerName="System.Data.SqlClient" />
In your code you should use the value in the name attribute to refer to the connection string you want (you could actually define several connection strings to different databases), so you would have
con.ConnectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
This is may have 2 reasons
1.I found the connection string error in my web.config file i had changed the connection string and its working.
In case entire entity is being return, better solution in spring JPA is use @Query(value = "from entity where Id in :ids")
This return entity type rather than object type
Thanks HansUp for your answer, it is very helpful and it works!
I found three patterns working in Access, yours is the best, because it works in all cases.
INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM
((class
INNER JOIN person AS cr
ON class.C_P_ClassRep=cr.P_Nr
)
INNER JOIN person AS cr2
ON class.C_P_ClassRep2nd=cr2.P_Nr
)
;
INNER JOIN "chained-set pattern"
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM person AS cr
INNER JOIN ( class
INNER JOIN ( person AS cr2
) ON class.C_P_ClassRep2nd=cr2.P_Nr
) ON class.C_P_ClassRep=cr.P_Nr
;
CROSS JOIN with WHERE
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM class, person AS cr, person AS cr2
WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
;
Microsoft Docs gives us two approaches.
Recommended HttpPost Edit code: Read and update
This is the same old way we used to do in previous versions of Entity Framework. and this is what Microsoft recommends for us.
Advantages
Modified
flag on the fields that are changed by form input.Alternative HttpPost Edit code: Create and attach
an alternative is to attach an entity created by the model binder to the EF context and mark it as modified.
As mentioned in the other answer the read-first approach requires an extra database read, and can result in more complex code for handling concurrency conflicts.
I had (have) a similar problem in a Java application. I wrote a JDBC driver wrapper around the Oracle driver so all output is sent to a log file.
The first syntax is redundant - the WITH CHECK
is default for new constraints, and the constraint is turned on by default as well.
This syntax is generated by the SQL management studio when generating sql scripts -- I'm assuming it's some sort of extra redundancy, possibly to ensure the constraint is enabled even if the default constraint behavior for a table is changed.
A good idea could be to encapsulate everything inside groups, no matter if need to identify them or not. That way you can use them in your replacement string. For example:
var pattern = @"(-)(\d+)(-)";
var replaced = Regex.Replace(text, pattern, "$1AA$3");
or using a MatchEvaluator:
var replaced = Regex.Replace(text, pattern, m => m.Groups[1].Value + "AA" + m.Groups[3].Value);
Another way, slightly messy, could be using a lookbehind/lookahead:
(?<=-)(\d+)(?=-)
Here's the one that may be little easier to read. Hope this is helpful.
from PIL import Image
from PIL import ExifTags
exifData = {}
img = Image.open(picture.jpg)
exifDataRaw = img._getexif()
for tag, value in exifDataRaw.items():
decodedTag = ExifTags.TAGS.get(tag, tag)
exifData[decodedTag] = value
var fileInput = $('#uploadCaptureInputFile');
fileInput.replaceWith(fileInput.val('').clone(true));
The wiki lists some more wrappers:
For a <br>
on each line, use
<textarea wrap="physical"></textarea>
You will get \n
s in the value of the textarea. Then, use the nl2br()
function to create <br>
s, or you can explode() it for <br>
or \n
.
Hope this helps
The answer is to use Welford's algorithm, which is very clearly defined after the "naive methods" in:
It's more numerically stable than either the two-pass or online simple sum of squares collectors suggested in other responses. The stability only really matters when you have lots of values that are close to each other as they lead to what is known as "catastrophic cancellation" in the floating point literature.
You might also want to brush up on the difference between dividing by the number of samples (N) and N-1 in the variance calculation (squared deviation). Dividing by N-1 leads to an unbiased estimate of variance from the sample, whereas dividing by N on average underestimates variance (because it doesn't take into account the variance between the sample mean and the true mean).
I wrote two blog entries on the topic which go into more details, including how to delete previous values online:
You can also take a look at my Java implement; the javadoc, source, and unit tests are all online:
I connected to a VPN and it worked. I was using school's WiFi.
Incase someone is still trying to figure this out. This is how you get the center X and Y of the view
.
int pos[] = new int[2];
view.getLocationOnScreen(pos);
int centerX = pos[0] + view.getMeasuredWidth() / 2;
int centerY = pos[1] + view.getMeasuredHeight() / 2;
Educated guess: You have a ISO-8859-1 encoded pound sign in a UTF-8 encoded page.
Make sure your data is in the right encoding and everything will work fine.
Use geom_boxplot(outlier.shape = NA)
to not display the outliers and scale_y_continuous(limits = c(lower, upper))
to change the axis limits.
An example.
n <- 1e4L
dfr <- data.frame(
y = exp(rlnorm(n)), #really right-skewed variable
f = gl(2, n / 2)
)
p <- ggplot(dfr, aes(f, y)) +
geom_boxplot()
p # big outlier causes quartiles to look too slim
p2 <- ggplot(dfr, aes(f, y)) +
geom_boxplot(outlier.shape = NA) +
scale_y_continuous(limits = quantile(dfr$y, c(0.1, 0.9)))
p2 # no outliers plotted, range shifted
Actually, as Ramnath showed in his answer (and Andrie too in the comments), it makes more sense to crop the scales after you calculate the statistic, via coord_cartesian
.
coord_cartesian(ylim = quantile(dfr$y, c(0.1, 0.9)))
(You'll probably still need to use scale_y_continuous
to fix the axis breaks.)
You will to have to set header content type in your php like this:
<?php
header('Content-type:application/json');
?>
Watch these Video for better understanding....
Reference: http://www.youtube.com/watch?v=EvFXWqEqh6o
In git 2.27, it looks like git sparse checkout has evolved. Solution in this answer does not work exactly the same way (compared to git 2.25)
git clone <URL> --no-checkout <directory> cd <directory> git sparse-checkout init --cone # to fetch only root files git sparse-checkout set apps/my_app libs/my_lib # etc, to list sub-folders to checkout # they are checked out immediately after this command, no need to run git pull
These commands worked better:
git clone --sparse <URL> <directory>
cd <directory>
git sparse-checkout init --cone # to fetch only root files
git sparse-checkout add apps/my_app
git sparse-checkout add libs/my_lib
See also : git-clone --sparse and git-sparse-checkout add
If you are using SQL Server 2012, 2014 or newer, use the Format Function instead:
select Format( decimalColumnName ,'FormatString','en-US' )
Review the Microsoft topic and .NET format syntax for how to define the format string.
An example for this question would be:
select Format( MyDecimalColumn ,'N','en-US' )
The following should work:
$now = date('Y-m-d');
$reservations = Reservation::where('reservation_from', '>=', $now)
->where('reservation_from', '<=', $to)
->get();
Suggest you add handling to test if any of the sheets to be renamed already exist:
Sub Test()
Dim ws As Worksheet
Dim ws1 As Worksheet
Dim strErr As String
On Error Resume Next
For Each ws In ActiveWorkbook.Sheets
Set ws1 = Sheets(ws.Name & "_v1")
If ws1 Is Nothing Then
ws.Name = ws.Name & "_v1"
Else
strErr = strErr & ws.Name & "_v1" & vbNewLine
End If
Set ws1 = Nothing
Next
On Error GoTo 0
If Len(strErr) > 0 Then MsgBox strErr, vbOKOnly, "these sheets already existed"
End Sub
i have this error using datatables.net
i fixed changing the default ajax Get to POST in te properties of the DataTable()
"ajax": {
"url": "../ControllerName/MethodJson",
"type": "POST"
},
If you are using moment.js then it is pretty simple to find date difference.
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private
).
If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons base_class::foo(...)
. You should note that unlike Java and C#, C++ does not have a keyword for "the base class" (super
or base
) since C++ supports multiple inheritance which may lead to ambiguity.
class left {
public:
void foo();
};
class right {
public:
void foo();
};
class bottom : public left, public right {
public:
void foo()
{
//base::foo();// ambiguous
left::foo();
right::foo();
// and when foo() is not called for 'this':
bottom b;
b.left::foo(); // calls b.foo() from 'left'
b.right::foo(); // call b.foo() from 'right'
}
};
Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.
class bottom : public left, public left { // Illegal
};
git revert
simply creates a new commit that is the opposite of an existing commit.
It leaves the files in the same state as if the commit that has been reverted never existed. For example, consider the following simple example:
$ cd /tmp/example
$ git init
Initialized empty Git repository in /tmp/example/.git/
$ echo "Initial text" > README.md
$ git add README.md
$ git commit -m "initial commit"
[master (root-commit) 3f7522e] initial commit
1 file changed, 1 insertion(+)
create mode 100644 README.md
$ echo "bad update" > README.md
$ git commit -am "bad update"
[master a1b9870] bad update
1 file changed, 1 insertion(+), 1 deletion(-)
In this example the commit history has two commits and the last one is a mistake. Using git revert:
$ git revert HEAD
[master 1db4eeb] Revert "bad update"
1 file changed, 1 insertion(+), 1 deletion(-)
There will be 3 commits in the log:
$ git log --oneline
1db4eeb Revert "bad update"
a1b9870 bad update
3f7522e initial commit
So there is a consistent history of what has happened, yet the files are as if the bad update never occured:
cat README.md
Initial text
It doesn't matter where in the history the commit to be reverted is (in the above example, the last commit is reverted - any commit can be reverted).
do you have to do something else after?
A git revert
is just another commit, so e.g. push to the remote so that other users can pull/fetch/merge the changes and you're done.
Do you have to commit the changes revert made or does revert directly commit to the repo?
git revert
is a commit - there are no extra steps assuming reverting a single commit is what you wanted to do.
Obviously you'll need to push again and probably announce to the team.
Indeed - if the remote is in an unstable state - communicating to the rest of the team that they need to pull to get the fix (the reverting commit) would be the right thing to do :).
My issue is a little different, I need to switch from one childViewController in 1st tabBar to home viewController of 2nd tabBar. I simply use the solution provided in the upstairs:
tabBarController.selectedIndex = 2
However when it switched to the home page of 2nd tabBar, the content is invisible. And when I debug, viewDidAppear, viewWillAppear, viewDidLoad, none of them is called. My solutions is to add the following code in the UITabBarController:
override var shouldAutomaticallyForwardAppearanceMethods: Bool
{
return true
}
why don't you give a try to inkscape command line, this is my bat file to convert all svg in this dir to png:
FOR %%x IN (*.svg) DO C:\Ink\App\Inkscape\inkscape.exe %%x -z --export-dpi=500 --export-area-drawing --export-png="%%~nx.png"
Use the FileSystemObject
object, namely, its CreateFolder
and CopyFile
methods. Basically, this is what your script will look like:
Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
' Create a new folder
oFSO.CreateFolder "C:\MyFolder"
' Copy a file into the new folder
' Note that the destination folder path must end with a path separator (\)
oFSO.CopyFile "\\server\folder\file.ext", "C:\MyFolder\"
You may also want to add additional logic, like checking whether the folder you want to create already exists (because CreateFolder
raises an error in this case) or specifying whether or not to overwrite the file being copied. So, you can end up with this:
Const strFolder = "C:\MyFolder\", strFile = "\\server\folder\file.ext"
Const Overwrite = True
Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
If Not oFSO.FolderExists(strFolder) Then
oFSO.CreateFolder strFolder
End If
oFSO.CopyFile strFile, strFolder, Overwrite
The Java Native Access library is typically used for calling native shared libraries from Java. Within this library there exist methods for determining the size of Java objects:
The getNativeSize(Class cls)
method and its overloads will provide the size for most classes.
Alternatively, if your classes inherit from JNA's Structure class the calculateSize(boolean force)
method will be available.
u can use this :
@Override
public void afterTextChanged(Editable s) {
super.afterTextChanged(s);
if (s.length() == Bank.PAN_MINIMUM_RECOGNIZABLE_LENGTH + 10) {
Bank bank = BankUtil.findByPan(s.toString());
if (null != bank && mNewPanEntered && !mNameDefined) {
mNewPanEntered = false;
suggestCardName(bank);
}
private void suggestCardName(Bank bank) {
mLastSuggestTime = System.currentTimeMillis();
if (!bank.getName().trim().matches(getActivity().getString(R.string.bank_eghtesadnovin))) {
inputCardNumber.setError(R.string.balance_not_enmb, true);
}
}
As a little trick to know what you are obtaining you can use var, so the compiler will tell you the type to expect:
int a = 1;
int b = 2;
var result = a/b;
your compiler will tell you that result would be of type int here.
Adding to Gisheri's answer
Following code worked for me
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYGON
]
},
markerOptions: {
icon: 'images/beachflag.png'
},
circleOptions: {
fillColor: '#ffff00',
fillOpacity: 1,
strokeWeight: 5,
clickable: false,
editable: true,
zIndex: 1
}
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
//console.log(polygon.overlay.latLngs.j[0].j);return false;
$.each(polygon.overlay.latLngs.j[0].j, function(key, LatLongsObject){
var LatLongs = LatLongsObject;
var lat = LatLongs.k;
var lon = LatLongs.B;
console.log("Lat is: "+lat+" Long is: "+lon); //do something with the coordinates
});
You can toggle a child div during onmouseover
and onmouseout
like this:
function Tooltip(el, text) {
el.onmouseover = function() {
el.innerHTML += '<div class="tooltip">' + text + '</div>'
}
el.onmouseout = function() {
el.removeChild(el.querySelector(".tooltip"))
}
}
//Sample Usage
Tooltip(document.getElementById("mydiv"),"hello im a tip div")
function Tooltip(el, text) {_x000D_
el.onmouseover = function() {_x000D_
el.innerHTML += '<div class="tooltip">' + text + '</div>'_x000D_
}_x000D_
el.onmouseout = function() {_x000D_
el.removeChild(el.querySelector(".tooltip"))_x000D_
}_x000D_
}_x000D_
_x000D_
//Sample Usage_x000D_
Tooltip(document.getElementById("mydiv"), "I'm a tooltip")
_x000D_
#mydiv {_x000D_
position: relative;_x000D_
display: flex;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
width: 120px;_x000D_
height: 50px;_x000D_
padding: 5px 10px;_x000D_
background-color: #e2f7ff;_x000D_
box-shadow: 1px 1px 1px 0px #cecece;_x000D_
}_x000D_
_x000D_
.tooltip {_x000D_
position: absolute;_x000D_
display: inline-block;_x000D_
white-space: nowrap;_x000D_
width: auto;_x000D_
height: auto;_x000D_
background-color: #11121b;_x000D_
color: white;_x000D_
padding: 4px 6px;_x000D_
border-radius: 3px;_x000D_
z-index: 99;_x000D_
left: 100%;_x000D_
top: 0;_x000D_
}
_x000D_
<div id="mydiv"> This is just a div </div>
_x000D_
Do this:
In the Android Manifest file, declare the following.
<application android:name="com.xyz.MyApplication">
</application>
Then write the class:
public class MyApplication extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
MyApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MyApplication.context;
}
}
Now everywhere call MyApplication.getAppContext()
to get your application context statically.
Use position: fixed
on the div
that contains your header, with something like
#header {
position: fixed;
}
#content {
margin-top: 100px;
}
In this example, when #content
starts off 100px below #header
, but as the user scrolls, #header
stays in place. Of course it goes without saying that you'll want to make sure #header
has a background so that its content will actually be visible when the two div
s overlap. Have a look at the position
property here: http://reference.sitepoint.com/css/position
I came across this post looking for a "shaking" implementation. millenomi's answer worked well for me, although i was looking for something that required a bit more "shaking action" to trigger. I've replaced to Boolean value with an int shakeCount. I also reimplemented the L0AccelerationIsShaking() method in Objective-C. You can tweak the ammount of shaking required by tweaking the ammount added to shakeCount. I'm not sure i've found the optimal values yet, but it seems to be working well so far. Hope this helps someone:
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
if (self.lastAcceleration) {
if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7] && shakeCount >= 9) {
//Shaking here, DO stuff.
shakeCount = 0;
} else if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7]) {
shakeCount = shakeCount + 5;
}else if (![self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.2]) {
if (shakeCount > 0) {
shakeCount--;
}
}
}
self.lastAcceleration = acceleration;
}
- (BOOL) AccelerationIsShakingLast:(UIAcceleration *)last current:(UIAcceleration *)current threshold:(double)threshold {
double
deltaX = fabs(last.x - current.x),
deltaY = fabs(last.y - current.y),
deltaZ = fabs(last.z - current.z);
return
(deltaX > threshold && deltaY > threshold) ||
(deltaX > threshold && deltaZ > threshold) ||
(deltaY > threshold && deltaZ > threshold);
}
PS: I've set the update interval to 1/15th of a second.
[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / 15)];
no real explanation is given by Java (in either JavaDoc or much coveted code comments), but looking at the code, it seems that this is magic:
calling stack:
String.indexOf(char[], int, int, char[], int, int, int) line: 1591
String.indexOf(String, int) line: 1564
String.indexOf(String) line: 1546
String.contains(CharSequence) line: 1934
code:
/**
* Code shared by String and StringBuffer to do searches. The
* source is the character array being searched, and the target
* is the string being searched for.
*
* @param source the characters being searched.
* @param sourceOffset offset of the source string.
* @param sourceCount count of the source string.
* @param target the characters being searched for.
* @param targetOffset offset of the target string.
* @param targetCount count of the target string.
* @param fromIndex the index to begin searching from.
*/
static int indexOf(char[] source, int sourceOffset, int sourceCount,
char[] target, int targetOffset, int targetCount,
int fromIndex) {
if (fromIndex >= sourceCount) {
return (targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {//my comment: this is where it returns, the size of the
return fromIndex; // incoming string is 0, which is passed in as targetCount
} // fromIndex is 0 as well, as the search starts from the
// start of the source string
...//the rest of the method
The solution given by luschn and pillravi works fine unless you receive a Strict-Transport-Security header in the response.
Adding withCredentials: true will solve that issue.
axios.post(session_url, {
withCredentials: true,
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
}
},{
auth: {
username: "USERNAME",
password: "PASSWORD"
}}).then(function(response) {
console.log('Authenticated');
}).catch(function(error) {
console.log('Error on Authentication');
});
I think you should consider using the shelve
module which provides persistent file-backed dictionary-like objects. It's easy to use in place of a "real" dictionary because it almost transparently provides your program with something that can be used just like a dictionary, without the need to explicitly convert it to a string and then write to a file (or vice-versa).
The main difference is needing to initially open()
it before first use and then close()
it when you're done (and possibly sync()
ing it, depending on the writeback
option being used). Any "shelf" file objects create can contain regular dictionaries as values, allowing them to be logically nested.
Here's a trivial example:
import shelve
shelf = shelve.open('mydata') # open for reading and writing, creating if nec
shelf.update({'one':1, 'two':2, 'three': {'three.1': 3.1, 'three.2': 3.2 }})
shelf.close()
shelf = shelve.open('mydata')
print shelf
shelf.close()
Output:
{'three': {'three.1': 3.1, 'three.2': 3.2}, 'two': 2, 'one': 1}
.split method will work, but it uses regular expressions. In this example it would be (to steal from Cristian):
String[] separated = CurrentString.split("\\:");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"
Also, this came from: Android split not working correctly
Well, you're on the right path, Benno!
There are some tips regarding VBA programming that might help you out.
Use always explicit references to the sheet you want to interact with. Otherwise, Excel may 'assume' your code applies to the active sheet and eventually you'll see it screws your spreadsheet up.
As lionz mentioned, get in touch with the native methods Excel offers. You might use them on most of your tricks.
Explicitly declare your variables... they'll show the list of methods each object offers in VBA. It might save your time digging on the internet.
Now, let's have a draft code...
Remember this code must be within the Excel Sheet object, as explained by lionz. It only applies to Sheet 2, is up to you to adapt it to both Sheet 2 and Sheet 3 in the way you prefer.
Hope it helps!
Private Sub Worksheet_Change(ByVal Target As Range)
Dim oSheet As Excel.Worksheet
'We only want to do something if the changed cell is B6, right?
If Target.Address = "$B$6" Then
'Checks if it's a number...
If IsNumeric(Target.Value) Then
'Let's avoid values out of your bonds, correct?
If Target.Value > 0 And Target.Value < 51 Then
'Let's assign the worksheet we'll show / hide rows to one variable and then
' use only the reference to the variable itself instead of the sheet name.
' It's safer.
'You can alternatively replace 'sheet 2' by 2 (without quotes) which will represent
' the sheet index within the workbook
Set oSheet = ActiveWorkbook.Sheets("Sheet 2")
'We'll unhide before hide, to ensure we hide the correct ones
oSheet.Range("A7:A56").EntireRow.Hidden = False
oSheet.Range("A" & Target.Value + 7 & ":A56").EntireRow.Hidden = True
End If
End If
End If
End Sub
I needed the same function and have read the previous solutions, however i also needed to have the unbalanced chunk to be at the end i.e if i have 10 elements to split them into vectors of 3 each, then my result should have vectors with 3,3,4 elements respectively. So i used the following (i left the code unoptimised for readability, otherwise no need to have many variables):
chunk <- function(x,n){
numOfVectors <- floor(length(x)/n)
elementsPerVector <- c(rep(n,numOfVectors-1),n+length(x) %% n)
elemDistPerVector <- rep(1:numOfVectors,elementsPerVector)
split(x,factor(elemDistPerVector))
}
set.seed(1)
x <- rnorm(10)
n <- 3
chunk(x,n)
$`1`
[1] -0.6264538 0.1836433 -0.8356286
$`2`
[1] 1.5952808 0.3295078 -0.8204684
$`3`
[1] 0.4874291 0.7383247 0.5757814 -0.3053884
There is no way to get the old password back. Log into the SQL server management console as a machine or domain admin using integrated authentication, you can then change any password (including sa).
Start the SQL service again and use the new created login (recovery in my example) Go via the security panel to the properties and change the password of the SA account.
Now write down the new SA password.
You can make your app as device/profile owner and call setScreenCaptureDisabled()
. From the docs, this api does the following:
public void setScreenCaptureDisabled (ComponentName admin, boolean disabled) Added in API level 21
Called by a device/profile owner to set whether the screen capture is disabled. Disabling screen capture also prevents the content from being shown on display devices that do not have a secure video output. See FLAG_SECURE for more details about secure surfaces and secure displays.
The calling device admin must be a device or profile owner. If it is not, a security exception will be thrown. Parameters admin Which DeviceAdminReceiver this request is associated with. disabled Whether screen capture is disabled or not.
Alternatively you can become an MDM(Mobile Device Management) partner app.OEMs provides additional APIs to their MDM partner apps to control the device.For example samsung provides api to control screen recording on the device to their MDM partners.
Currently this is the only way you can enforce screen capture restrictions.
This builds on the answer from kgaidis from https://stackoverflow.com/a/34343418/4316579
I am not sure when the extension stopped working, but at the time of this writing (Swift 4), it appears that the extension will no longer be executed unless you declare UINavigationBarDelegate conformity as described below.
Hope this helps people that are wondering why their extension no longer works.
extension UINavigationController: UINavigationBarDelegate {
public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
}
}
In Visual Studio please click 'Folder.ico' file in the Solution Explorer pane. Then you will see Properties pane. Change 'Copy to Output Directory' behavior to 'Copy if newer'. This will make Visual Studio copy the file to the output bin directory.
Now to get the file path using relative path just type:
string pathToIcoFile = AppDomain.CurrentDomain.BaseDirectory + "//FolderIcon//Folder.ico";
Hope that helped.
It works for me when I define the complete border
property. (JSFiddle here)
.field_set{
border: 1px #F00 solid;
}?
the reason is the border-style
that is set to none
by default for fieldsets. You need to override that as well.
Try using document.getElementById("myForm")
instead of document.myForm.
<script>
var auto_refresh = setInterval(function() { submitform(); }, 10000);
function submitform()
{
alert('test');
document.getElementById("myForm").submit();
}
</script>
Two options:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
String enums look different than regular ones, for example:
enum MyEnum {
A = "a",
B = "b",
C = "c"
}
Compiles into:
var MyEnum;
(function (MyEnum) {
MyEnum["A"] = "a";
MyEnum["B"] = "b";
MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));
Which just gives you this object:
{
A: "a",
B: "b",
C: "c"
}
You can get all the keys (["A", "B", "C"]
) like this:
Object.keys(MyEnum);
And the values (["a", "b", "c"]
):
Object.keys(MyEnum).map(key => MyEnum[key])
Or using Object.values():
Object.values(MyEnum)
If you wish to load them by webpack you can simply use :src='require('path/to/file')'
Make sure you use :
otherwise it won't execute the require statement as Javascript.
In typescript you can do almost the exact same operation: :src="require('@/assets/image.png')"
Why the following is generally considered bad practice:
<template>
<div id="app">
<img src="./assets/logo.png">
</div>
</template>
<script>
export default {
}
</script>
<style lang="scss">
</style>
When building using the Vue cli, webpack is not able to ensure that the assets file will maintain a structure that follows the relative importing. This is due to webpack trying to optimize and chunk items appearing inside of the assets folder. If you wish to use a relative import you should do so from within the static
folder and use: <img src="./static/logo.png">
It is now possible to create command line launcher automatically from JetBrains Toolbox. This is how you do it:
Generate shell scripts
;Shell script location
textbox with the location where you want the launchers to reside. You have to do this manually it will not fill automatically at this time!On Mac the location could be /usr/local/bin
. For the novices, you can use any path inside the PATH variable or add a new path to the PATH variable in your bash profile. Use echo $PATH
to see which paths are there.
Note! It did not work right away for me, I had to fiddle around a little before the scripts were generated. You can go to the gearbox of the IDEA (PyCharm for example) and see/change the launcher name. So for PyCharm, the default name is pycharm
but you can change this to whatever you prefer.
If you do not use the toolbox you can still use my original answer.
~~For some reason, the Create Command Line Launcher
is not available anymore in 2019.1.~~ Because it is now part of JetBrains Toolbox
This is how you can create the script yourself:
If you already used the charm command before use type -a charm
to find the script. Change the pycharm version in the file paths. Note that the numbering in the first variable RUN_PATH
is different. You will have to look this up in the dir yourself.
RUN_PATH = u'/Users/boatfolder/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/191.6183.50/PyCharm.app'
CONFIG_PATH = u'/Users/boatfolder/Library/Preferences/PyCharm2019.1'
SYSTEM_PATH = u'/Users/boatfolder/Library/Caches/PyCharm2019.1'
If you did not use the charm command before, you will have to create it.
Create the charm file somewhere like this: /usr/local/bin/charm
Then add this code (change version number to your version as explained above):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import struct
import sys
import os
import time
# see com.intellij.idea.SocketLock for the server side of this interface
RUN_PATH = u'/Users/boatfolder/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/191.6183.50/PyCharm.app'
CONFIG_PATH = u'/Users/boatfolder/Library/Preferences/PyCharm2019.1'
SYSTEM_PATH = u'/Users/boatfolder/Library/Caches/PyCharm2019.1'
def print_usage(cmd):
print(('Usage:\n' +
' {0} -h | -? | --help\n' +
' {0} [project_dir]\n' +
' {0} [-l|--line line] [project_dir|--temp-project] file[:line]\n' +
' {0} diff <left> <right>\n' +
' {0} merge <local> <remote> [base] <merged>').format(cmd))
def process_args(argv):
args = []
skip_next = False
for i, arg in enumerate(argv[1:]):
if arg == '-h' or arg == '-?' or arg == '--help':
print_usage(argv[0])
exit(0)
elif i == 0 and (arg == 'diff' or arg == 'merge' or arg == '--temp-project'):
args.append(arg)
elif arg == '-l' or arg == '--line':
args.append(arg)
skip_next = True
elif skip_next:
args.append(arg)
skip_next = False
else:
path = arg
if ':' in arg:
file_path, line_number = arg.rsplit(':', 1)
if line_number.isdigit():
args.append('-l')
args.append(line_number)
path = file_path
args.append(os.path.abspath(path))
return args
def try_activate_instance(args):
port_path = os.path.join(CONFIG_PATH, 'port')
token_path = os.path.join(SYSTEM_PATH, 'token')
if not (os.path.exists(port_path) and os.path.exists(token_path)):
return False
try:
with open(port_path) as pf:
port = int(pf.read())
with open(token_path) as tf:
token = tf.read()
except (ValueError):
return False
s = socket.socket()
s.settimeout(0.3)
try:
s.connect(('127.0.0.1', port))
except (socket.error, IOError):
return False
found = False
while True:
try:
path_len = struct.unpack('>h', s.recv(2))[0]
path = s.recv(path_len).decode('utf-8')
if os.path.abspath(path) == os.path.abspath(CONFIG_PATH):
found = True
break
except (socket.error, IOError):
return False
if found:
cmd = 'activate ' + token + '\0' + os.getcwd() + '\0' + '\0'.join(args)
if sys.version_info.major >= 3: cmd = cmd.encode('utf-8')
encoded = struct.pack('>h', len(cmd)) + cmd
s.send(encoded)
time.sleep(0.5) # don't close the socket immediately
return True
return False
def start_new_instance(args):
if sys.platform == 'darwin':
if len(args) > 0:
args.insert(0, '--args')
os.execvp('/usr/bin/open', ['-a', RUN_PATH] + args)
else:
bin_file = os.path.split(RUN_PATH)[1]
os.execv(RUN_PATH, [bin_file] + args)
ide_args = process_args(sys.argv)
if not try_activate_instance(ide_args):
start_new_instance(ide_args)
Er - that would imply that you are invoking your function with arguments which aren't in the proper order... which I would not recommend.
I would recommend instead feeding an object to your function like so:
function getData( props ) {
props = props || {};
props.params = props.params || {};
props.id = props.id || 1;
props.callback = props.callback || function(){};
alert( props.callback )
};
getData( {
id: 3,
callback: function(){ alert('hi'); }
} );
Benefits:
Drawbacks:
If you have no choice, you could use a function to detect whether an object is indeed a function ( see last example ).
Note: This is the proper way to detect a function:
function isFunction(obj) {
return Object.prototype.toString.call(obj) === "[object Function]";
}
isFunction( function(){} )
To get the top N elements from your python dictionary one can use the following line of code:
list(dictionaryName.items())[:N]
In your case you can change it to:
list(d.items())[:4]
Just replace with "/" for file path :
open("description_files/program_description.txt","r")
You can achieve this using different ways but with different performance,
1. Using bracket notation:
var str = "Test";
var lastLetter = str[str.length - 1];
But it's not recommended to use brackets. Check the reasons here
2. charAt[index]:
var lastLetter = str.charAt(str.length - 1)
This is readable and fastest among others. It is most recommended way.
3. substring:
str.substring(str.length - 1);
4. slice:
str.slice(-1);
It's slightly faster than substring.
You can check the performance here
With ES6:
You can use str.endsWith("t");
But it is not supported in IE. Check more details about endsWith here
If you want to continue use https instead ssh, and avoid type into your username and password for security reason.
You can also try Github OAuth token, then you can do
git config remote.origin.url 'https://{token}@github.com/{username}/{project}.git'
or
git remote add origin 'https://{token}@github.com/{username}/{project}.git'
This works for me!
If this happens in visual studio then clean your project and run it again.
Build --> Clean Solution
Run (or F5)
One difference observed (Python27):
os.environ
raises an exception if the environmental variable does not exist.
os.getenv
does not raise an exception, but returns None
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
Extending activity using baseadapter
used this
Toast.makeText(getActivity(),
"Your Message", Toast.LENGTH_LONG).show();
or if you are using activity or mainactivity
Toast.makeText(MainActivity.this,
"Your Message", Toast.LENGTH_LONG).show();
You can use this:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// Actions to do after 10 seconds
}
}, 10000);
For Stop the Handler, You can try this:
handler.removeCallbacksAndMessages(null);
The best and the easiest way, for me was this..
->Simply create a thread with Handler containing sleep().
private ImageView myImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shape_count); myImageView= (ImageView)findViewById(R.id.shape1);
Animation myFadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fadein);
myImageView.startAnimation(myFadeInAnimation);
new Thread(new Runnable() {
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
Log.w("hendler", "recived");
Animation myFadeOutAnimation = AnimationUtils.loadAnimation(getBaseContext(), R.anim.fadeout);
myImageView.startAnimation(myFadeOutAnimation);
myImageView.setVisibility(View.INVISIBLE);
}
};
@Override
public void run() {
try{
Thread.sleep(2000); // your fadein duration
}catch (Exception e){
}
handler.sendEmptyMessage(1);
}
}).start();
}
The color you are using is white "#ffffff" is white so try a different one change in the values if you want until you get your need from this link Color Codes and it should go fine
@echo off
setlocal
set "list=a b c d"
(
for %%i in (%list%) do (
echo(%%i
echo(
)
)>file.txt
You don't need - actually, can't "declare" variables in batch. Assigning a value to a variable creates it, and assigning an empty string deletes it. Any variable name that doesn't have an assigned value HAS a value of an empty string. ALL variables are strings - WITHOUT exception. There ARE operations that appear to perform (integer) mathematical functions, but they operate by converting back and forth from strings.
Batch is sensitive to spaces in variable names, so your assignment as posted would assign the string "A B C D"
- including the quotes, to the variable "list "
- NOT including the quotes, but including the space. The syntax set "var=string"
is used to assign the value string
to var
whereas set var=string
will do the same thing. Almost. In the first case, any stray trailing spaces after the closing quote are EXCLUDED from the value assigned, in the second, they are INCLUDED. Spaces are a little hard to see when printed.
ECHO
echoes strings. Clasically, it is followed by a space - one of the default separators used by batch (the others are TAB, COMMA, SEMICOLON - any of these do just as well BUT TABS often get transformed to a space-squence by text-editors and the others have grown quirks of their own over the years.) Other characters following the O
in ECHO
have been found to do precisely what the documented SPACE should do. DOT is common. Open-parenthesis (
is probably the most useful since the command
ECHO.%emptyvalue%
will produce a report of the ECHO
state (ECHO is on/off
) whereas
ECHO(%emptyvalue%
will produce an empty line.
The problem with ECHO(
is that the result "looks" unbalanced.
List asList = Arrays.asList(array);
Set<String> mySet = new HashSet<String>(asList);
for(String s: mySet){
System.out.println(s + " " + Collections.frequency(asList,s));
}
This is my solution, i have the same issue and its seems like this solution work for me.
yourObj = [].concat(yourObj);
In case you use spring boot, you must not set the properties spring.mvc.view.prefix
and spring.mvc.view.suffix
in your application.properties file, instead configure the bean ViewResolver
from a configuration class.
application.properties
# Configured in @Configuration GuestNav
#spring.mvc.view.prefix=/WEB-INF/views/
#spring.mvc.view.suffix=.jsp
# Live reload
spring.devtools.restart.additional-paths=.
# Better logging
server.tomcat.accesslog.directory=logs
server.tomcat.accesslog.file-date-format=yyyy-MM-dd
server.tomcat.accesslog.prefix=access_log
server.tomcat.accesslog.suffix=.log
Main method
@SpringBootApplication
public class WebApp extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(WebApp.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(WebApp.class, args);
}
}
Configuration class
@Configuration
@EnableWebMvc
public class DispatcherConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/views/**").addResourceLocations("/views/");
}
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/notinuse/");
viewResolver.setSuffix("");
return viewResolver;
}
}
A controller class
@Controller
public class GuestNav {
@GetMapping("/")
public String home() {
return "forward:/views/guest/index.html";
}
}
You must place your files in the directory /webapp/views/guest/index.html
, be careful, the webapp directory is outside of the resources directory.
In this way you may use the url patterns of spring-mvc but serve static context.
sed 's/^.....//'
means
replace ("s", substitute) beginning-of-line then 5 characters (".") with nothing.
There are more compact or flexible ways to write this using sed or cut.
In SSMS: right-click on SQL server icon, Activity Monitor. Open Processes. Find the processed connected. Right-click on the process, Kill.
In plain-old JavaScript you can do this:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type.toLowerCase() == 'text') {
alert(inputs[i].value);
}
}
In jQuery, you would just do:
// select all inputs of type 'text' on the page
$("input:text")
// hide all text inputs which are descendants of div class="foo"
$("div.foo input:text").hide();
You can create Array of ArrayList
List<Integer>[] outer = new List[number];
for (int i = 0; i < number; i++) {
outer[i] = new ArrayList<>();
}
This will be helpful in scenarios like this. You know the size of the outer one. But the size of inner ones varies. Here you can create an array of fixed length which contains size-varying Array lists. Hope this will be helpful for you.
In Java 8 and above you can do it in a much better way.
List<Integer>[] outer = new List[number];
Arrays.setAll(outer, element -> new ArrayList<>());
Even better using method reference
List<Integer>[] outer = new List[10];
Arrays.setAll(outer, ArrayList :: new);
In Linux(Ubuntu) just install the driver like so:
sudo apt-get install php-pgsql
This will install the driver with using your php current version.
NOTE: This solution will return the children of sets of certain lengths, not the parent element as you have asked. Hopefully, it's still useful.
Andre Luis came up with a method: http://lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/ Unfortunately, it only works in IE9 and above.
Essentially, you combine :nth-child() with other pseudo classes that deal with the position of an element. This approach allows you to specify elements from sets of elements with specific lengths.
For instance :nth-child(1):nth-last-child(3)
matches the first element in a set while also being the 3rd element from the end of the set. This does two things: guarantees that the set only has three elements and that we have the first of the three. To specify the second element of the three element set, we'd use :nth-child(2):nth-last-child(2)
.
Example 1 - Select all list elements if set has three elements:
li:nth-child(1):nth-last-child(3),
li:nth-child(2):nth-last-child(2),
li:nth-child(3):nth-last-child(1) {
width: 33.3333%;
}
Example 1 alternative from Lea Verou:
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
width: 33.3333%;
}
Example 2 - target last element of set with three list elements:
li:nth-child(3):last-child {
/* I'm the last of three */
}
Example 2 alternative:
li:nth-child(3):nth-last-child(1) {
/* I'm the last of three */
}
Example 3 - target second element of set with four list elements:
li:nth-child(2):nth-last-child(3) {
/* I'm the second of four */
}
If you frequently need to access the Nth element of a sequence, std::list
, which is implemented as a doubly linked list, is probably not the right choice. std::vector
or std::deque
would likely be better.
That said, you can get an iterator to the Nth element using std::advance
:
std::list<Object> l;
// add elements to list 'l'...
unsigned N = /* index of the element you want to retrieve */;
if (l.size() > N)
{
std::list<Object>::iterator it = l.begin();
std::advance(it, N);
// 'it' points to the element at index 'N'
}
For a container that doesn't provide random access, like std::list
, std::advance
calls operator++
on the iterator N
times. Alternatively, if your Standard Library implementation provides it, you may call std::next
:
if (l.size() > N)
{
std::list<Object>::iterator it = std::next(l.begin(), N);
}
std::next
is effectively wraps a call to std::advance
, making it easier to advance an iterator N
times with fewer lines of code and fewer mutable variables. std::next
was added in C++11.
Selector > child:
.text-center-row>th,_x000D_
.text-center-row>td {_x000D_
text-align: center;_x000D_
}
_x000D_
<table border="1" width='500px'>_x000D_
<tr class="text-center-row">_x000D_
<th>Text</th>_x000D_
<th>Text</th>_x000D_
<th>Text</th>_x000D_
<th>Text</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
</tr>_x000D_
<tr class="text-center-row">_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
</tr>_x000D_
</table>
_x000D_
If you are on CloudFlare, make sure you use something like this.
# BEGIN SSL Redirect
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
# END SSL Redirect
This will save you from the redirect loop and will redirect your site to SSL safely.
P.S. It is a good idea to if check the mod_rewrite.c!
sometimes while not found sp_send_dbmail directly. You may use 'msdb.dbo.sp_send_dbmail' to try (Work fine on Windows Server 2008 R2 and is tested)
An update if one is using Express 4.2 then the timeout middleware has been removed so need to manually add it with
npm install connect-timeout
and in the code it has to be (Edited as per comment, how to include it in the code)
var timeout = require('connect-timeout');
app.use(timeout('100s'));
The easiest way is to use to_datetime
:
df['col'] = pd.to_datetime(df['col'])
It also offers a dayfirst
argument for European times (but beware this isn't strict).
Here it is in action:
In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0 2005-05-23 00:00:00
dtype: datetime64[ns]
You can pass a specific format:
In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0 2005-05-23
dtype: datetime64[ns]
By multiplying, bits are shifted to the left. This uses more of the available space of hash codes, reducing collisions.
By not using a power of two, the lower-order, rightmost bits are populated as well, to be mixed with the next piece of data going into the hash.
The expression n * 31
is equivalent to (n << 5) - n
.
On an Arm7 (armhf) device running Debian Stretch, I had to issue either of the following:
$ nodejs -v
$ nodejs -h
The following did not work:
$ node -v
$ node -h
$ apm -v
Hope this helps someone else.
I Had the same problem and finally reached to the solution.
add "--stacktrace --debug" to your command-line options(File -> Settings -> Compiler) then run it. This will show the problem(unwanted code) in your code.
It looks like your permissions are messed up. Type chown -R markwalker ~
in the Terminal and try pip
again? Let me know if you're sorted.
In order to avoid duplicate code, I recommend you to define the color once, for both states:
a, a:visited{
color: /* some color */;
}
This, indeeed, will mantain your <a>
color (whatever this color is) even when the link has been visited.
Notice that, if the color of the element inside of the <a>
is being inherited (e.g. the color is set in the body
), you could do the following trick:
a, a:visited {
color: inherit;
}
OP is using python, but in javascript (something to be careful of since the syntaxes are similar.
// only replaces the first instance of ' ' with '_'
"one two three".replace(' ', '_');
=> "one_two three"
// replaces all instances of ' ' with '_'
"one two three".replace(/\s/g, '_');
=> "one_two_three"
From your ant buildfile, I assume that what you want is to create a single JAR archive that will contain not only your application classes, but also the contents of other JARs required by your application.
However your build-jar
file is just putting required JARs inside your own JAR; this will not work as explained here (see note).
Try to modify this:
<jar destfile="${jar.file}"
basedir="${build.dir}"
manifest="${manifest.file}">
<fileset dir="${classes.dir}" includes="**/*.class" />
<fileset dir="${lib.dir}" includes="**/*.jar" />
</jar>
to this:
<jar destfile="${jar.file}"
basedir="${build.dir}"
manifest="${manifest.file}">
<fileset dir="${classes.dir}" includes="**/*.class" />
<zipgroupfileset dir="${lib.dir}" includes="**/*.jar" />
</jar>
More flexible and powerful solutions are the JarJar or One-Jar projects. Have a look into those if the above does not satisfy your requirements.
new Buffer(number) // Old
Buffer.alloc(number) // New
new Buffer(string) // Old
Buffer.from(string) // New
new Buffer(string, encoding) // Old
Buffer.from(string, encoding) // New
new Buffer(...arguments) // Old
Buffer.from(...arguments) // New
Note that Buffer.alloc() is also faster on the current Node.js versions than new Buffer(size).fill(0), which is what you would otherwise need to ensure zero-filling.
This solution is applicable for Windows machine.
MongoDB needs data directory to store data. Default path is C:\data\db
. In case you don't have the data directory, create one in your C: drive. (P.S.: data\db means there is a directory named 'db' inside the directory 'data')
Place the json you want to import in this path: C:\data\db\
.
Open the command prompt and type the following command
mongoimport --db databaseName --collections collectionName --file fileName.json --type json --batchSize 1
Here,
Tiff images can be displayed directly onto IE and safari only.. no support of tiff images on chrome and firefox. you can encode the image and then display it on browser by decoding the encoded image to some other format. Hope this works for you
I managed to get the value of the DataKeys using this code:
In the GridView I added:
DataKeyNames="ID" OnRowCommand="myRowCommand"
Then in my row command function:
protected void myRowCommand(object sender, GridViewCommandEventArgs e)
{
LinkButton lnkBtn = (LinkButton)e.CommandSource; // the button
GridViewRow myRow = (GridViewRow)lnkBtn.Parent.Parent; // the row
GridView myGrid = (GridView)sender; // the gridview
string ID = myGrid.DataKeys[myRow.RowIndex].Value.ToString(); // value of the datakey
switch (e.CommandName)
{
case "cmd1":
// do something using the ID
break;
case "cmd2":
// do something else using the ID
break;
}
}
Following the JSON-P 1.0 specs (JSR-353) a more current solution for a given JsonStructure
(JsonObject
or JsonArray
) could look like this:
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.json.Json;
import javax.json.JsonStructure;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;
public class PrettyJson {
private static JsonWriterFactory FACTORY_INSTANCE;
public static String toString(final JsonStructure status) {
final StringWriter stringWriter = new StringWriter();
final JsonWriter jsonWriter = getPrettyJsonWriterFactory()
.createWriter(stringWriter);
jsonWriter.write(status);
jsonWriter.close();
return stringWriter.toString();
}
private static JsonWriterFactory getPrettyJsonWriterFactory() {
if (null == FACTORY_INSTANCE) {
final Map<String, Object> properties = new HashMap<>(1);
properties.put(JsonGenerator.PRETTY_PRINTING, true);
FACTORY_INSTANCE = Json.createWriterFactory(properties);
}
return FACTORY_INSTANCE;
}
}
This method will drop the old column and create new columns with same values and new datatype. My original datatypes when the DataFrame was created were:-
root
|-- id: integer (nullable = true)
|-- flag1: string (nullable = true)
|-- flag2: string (nullable = true)
|-- name: string (nullable = true)
|-- flag3: string (nullable = true)
After this I ran following code to change the datatype:-
df=df.withColumnRenamed(<old column name>,<dummy column>) // This was done for both flag1 and flag3
df=df.withColumn(<old column name>,df.col(<dummy column>).cast(<datatype>)).drop(<dummy column>)
After this my result came out to be:-
root
|-- id: integer (nullable = true)
|-- flag2: string (nullable = true)
|-- name: string (nullable = true)
|-- flag1: boolean (nullable = true)
|-- flag3: boolean (nullable = true)
With data.table, the solutions is:
DT[, idnat2 := ifelse(idbp %in% "foreign", "foreign",
ifelse(idbp %in% c("colony", "overseas"), "overseas", "mainland" ))]
The ifelse
is vectorized. The if-else
is not. Here, DT is:
idnat idbp
1 french mainland
2 french colony
3 french overseas
4 foreign foreign
This gives:
idnat idbp idnat2
1: french mainland mainland
2: french colony overseas
3: french overseas overseas
4: foreign foreign foreign
This will capture everything up to the ' in backreference 1 - and everything after the ' in backreference 2. You may need to escape the apostrophes though depending on language (\')
/^([^']*)'?(.*)$/
Quick modification: if the line doesn't have an ' - backreference 1 should still catch the whole line.
^ - start of string
([^']*) - capture any number of not ' characters
'? - match the ' 0 or 1 time
(.*) - capture any number of characters
$ - end of string
It is not necessary to encode a colon as %3B in the query, although doing so is not illegal.
URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
query = *( pchar / "/" / "?" )
pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded = "%" HEXDIG HEXDIG
sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
It also seems that only percent-encoded spaces are valid, as I doubt that space is an ALPHA or a DIGIT
look to the URI specification for more details.
is there a way to pass param from
navigate.goback()
and parent can listen to the params and update its state?
You can pass a callback function as parameter (as mentioned in other answers).
Here is a more clear example, when you navigate from A to B and you want B to communicate information back to A you can pass a callback (here onSelect
):
ViewA.js
import React from "react";
import { Button, Text, View } from "react-native";
class ViewA extends React.Component {
state = { selected: false };
onSelect = data => {
this.setState(data);
};
onPress = () => {
this.props.navigate("ViewB", { onSelect: this.onSelect });
};
render() {
return (
<View>
<Text>{this.state.selected ? "Selected" : "Not Selected"}</Text>
<Button title="Next" onPress={this.onPress} />
</View>
);
}
}
ViewB.js
import React from "react";
import { Button } from "react-native";
class ViewB extends React.Component {
goBack() {
const { navigation } = this.props;
navigation.goBack();
navigation.state.params.onSelect({ selected: true });
}
render() {
return <Button title="back" onPress={this.goBack} />;
}
}
Hats off for debrice - Refer to https://github.com/react-navigation/react-navigation/issues/288#issuecomment-315684617
For React Navigation v5
ViewB.js
import React from "react";
import { Button } from "react-native";
class ViewB extends React.Component {
goBack() {
const { navigation, route } = this.props;
navigation.goBack();
route.params.onSelect({ selected: true });
}
render() {
return <Button title="back" onPress={this.goBack} />;
}
}
On WorkBench I resolved it By deactivating the safe update mode:
-Edit -> Preferences -> Sql Editor then uncheck Safe update.
You can use the excecl command
int execl(const char *path, const char *arg, ...);
Like shown here
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
int main (void) {
return execl ("/bin/pwd", "pwd", NULL);
}
The second argument will be the name of the process as it will appear in the process table.
Alternatively, you can use the getcwd() function to get the current working directory:
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#define MAX 255
int main (void) {
char wd[MAX];
wd[MAX-1] = '\0';
if(getcwd(wd, MAX-1) == NULL) {
printf ("Can not get current working directory\n");
}
else {
printf("%s\n", wd);
}
return 0;
}
In my case, the reason the buttons got pushed up was because the view above them was a ScrollView
, and it got collapsed with the buttons pushed up above the keyboard no matter what value of android:windowSoftInputMode
I was setting.
I was able to avoid my bottom row of buttons getting pushed up by the soft keyboard by setting
android:isScrollContainer="false"
on the ScrollView
that sits above the buttons.
If any of other solution doesn't fix it, try to override the styles to hide the sort togglers:
.sorting_asc:after, .sorting_desc:after {
content: "";
}
Here's an extension method version if anyone is interested
public static TEnum ConvertEnum<TEnum >(this Enum source)
{
return (TEnum)Enum.Parse(typeof(TEnum), source.ToString(), true);
}
// Usage
NewEnumType newEnum = oldEnumVar.ConvertEnum<NewEnumType>();
I think this can not be perfectly done for the time being. There are 2 basic problems:
How can you make sure the sms is already in the inbox when you try to delete it?
Notice that SMS_RECEIVED is not an ordered broadcast.
So dmyung's solution is completely trying one's luck; even the delay in Doug's answer is not a guarantee.
The SmsProvider is not thread safe.(refer to http://code.google.com/p/android/issues/detail?id=2916#c0)
The fact that more than one clients are requesting delete and insert in it at the same time will cause data corruption or even immediate Runtime Exception.
Assuming you just need to reverse an indexed array (not associative or multidimensional) a simple for loop would suffice:
$fruits = ['bananas', 'apples', 'pears'];
for($i = count($fruits)-1; $i >= 0; $i--) {
echo $fruits[$i] . '<br>';
}
The property
in meta tags allows you to specify values to property fields which come from a property library. The property library (RDFa format) is specified in the head tag.
For example, to use that code you would have to have something like this in your <head
tag. <head xmlns:og="http://example.org/">
and inside the http://example.org/
there would be a specification for title
(og:title).
The tag from your example was almost definitely from the Open Graph Protocol, the purpose is to specify structured information about your website for the use of Facebook (and possibly other search engines).
Or just use a fake-git-history to generate it for a specific data range.
You indicated that you're using Angular 1.2.0... as one of the other comments indicated, ng-bind-html-unsafe
has been deprecated.
Instead, you'll want to do something like this:
<div ng-bind-html="preview_data.preview.embed.htmlSafe"></div>
In your controller, inject the $sce
service, and mark the HTML as "trusted":
myApp.controller('myCtrl', ['$scope', '$sce', function($scope, $sce) {
// ...
$scope.preview_data.preview.embed.htmlSafe =
$sce.trustAsHtml(preview_data.preview.embed.html);
}
Note that you'll want to be using 1.2.0-rc3 or newer. (They fixed a bug in rc3 that prevented "watchers" from working properly on trusted HTML.)
I was having multiple date formats into json, and was extracting csv with universal format. I looked multiple places, tried different ways, but at the end I'm able to convert with the following simple code.
private String getDate(String anyDateFormattedString) {
@SuppressWarnings("deprecation")
Date date = new Date(anyDateFormattedString);
SimpleDateFormat dateFormat = new SimpleDateFormat(yourDesiredDateFormat);
String convertedDate = dateFormat.format(date);
return convertedDate;
}
Check the port defined in postgresql.conf
. My installation of postgres 9.4 uses port 5433
instead of 5432
As nobody has mentioned I will add it (even if it is a stupid mistake). In case you are on Windows 10 you don't usually need to restart, but
-> Make sure to CLOSE any open properties pages of the "services"-window in case you have just installed the service (and still have opened the properties page of the old service).
I'm talking about this window:
After closing all services windows and re-trying -> it worked. In contrast to the OP I got Error 1053
basically immediately (without windows waiting on anything)
With HttpWebRequest.GetRequestStream
Code example from http://msdn.microsoft.com/en-us/library/d4cek6cc.aspx
string postData = "firstone=" + inputData;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);
// Set the content type of the data being posted.
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
// Set the content length of the string being posted.
myHttpWebRequest.ContentLength = byte1.Length;
Stream newStream = myHttpWebRequest.GetRequestStream ();
newStream.Write (byte1, 0, byte1.Length);
From one of my own code:
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = this.credentials;
request.Method = method;
request.ContentType = "application/atom+xml;type=entry";
using (Stream requestStream = request.GetRequestStream())
using (var xmlWriter = XmlWriter.Create(requestStream, new XmlWriterSettings() { Indent = true, NewLineHandling = NewLineHandling.Entitize, }))
{
cmisAtomEntry.WriteXml(xmlWriter);
}
try
{
return (HttpWebResponse)request.GetResponse();
}
catch (WebException wex)
{
var httpResponse = wex.Response as HttpWebResponse;
if (httpResponse != null)
{
throw new ApplicationException(string.Format(
"Remote server call {0} {1} resulted in a http error {2} {3}.",
method,
uri,
httpResponse.StatusCode,
httpResponse.StatusDescription), wex);
}
else
{
throw new ApplicationException(string.Format(
"Remote server call {0} {1} resulted in an error.",
method,
uri), wex);
}
}
catch (Exception)
{
throw;
}
You have the wrong table set on the command. You should use the following on your setup:
ALTER TABLE scode_tracker.ap_visits ENGINE=MyISAM;
Yet another option via Visual Studio, add a reference to the DLL to any project, then right-clicking on the new reference and click Properties, you can see what you are looking for in Runtime version:
I use a generic query I call "dump" (why? I don't know) that looks like this:
SET NEWPAGE NONE
SET PAGESIZE 0
SET SPACE 0
SET LINESIZE 16000
SET ECHO OFF
SET FEEDBACK OFF
SET VERIFY OFF
SET HEADING OFF
SET TERMOUT OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET COLSEP |
spool &1..txt
@@&1
spool off
exit
I then call SQL*Plus passing the actual SQL script I want to run as an argument:
sqlplus -S user/password@database @dump.sql my_real_query.sql
The result is written to a file
my_real_query.sql.txt
.
This is caused when your request response is not received in given time(by timeout
request module option).
Basically to catch that error first, you need to register a handler on error
, so the unhandled error won't be thrown anymore: out.on('error', function (err) { /* handle errors here */ })
. Some more explanation here.
In the handler you can check if the error is ETIMEDOUT and apply your own logic: if (err.message.code === 'ETIMEDOUT') { /* apply logic */ }
.
If you want to request for the file again, I suggest using node-retry or node-backoff modules. It makes things much simpler.
If you want to wait longer, you can set timeout
option of request yourself. You can set it to 0 for no timeout.
I have created an appender that will do that. http://stauffer.james.googlepages.com/DateFormatFileAppender.java
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software
* License version 1.1, a copy of which has been included with this
* distribution in the LICENSE.txt file. */
package sps.log.log4j;
import java.io.IOException;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.*;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;
/**
* DateFormatFileAppender is a log4j Appender and extends
* {@link FileAppender} so each log is
* named based on a date format defined in the File property.
*
* Sample File: 'logs/'yyyy/MM-MMM/dd-EEE/HH-mm-ss-S'.log'
* Makes a file like: logs/2004/04-Apr/13-Tue/09-45-15-937.log
* @author James Stauffer
*/
public class DateFormatFileAppender extends FileAppender {
/**
* The default constructor does nothing.
*/
public DateFormatFileAppender() {
}
/**
* Instantiate a <code>DailyRollingFileAppender</code> and open the
* file designated by <code>filename</code>. The opened filename will
* become the ouput destination for this appender.
*/
public DateFormatFileAppender (Layout layout, String filename) throws IOException {
super(layout, filename, true);
}
private String fileBackup;//Saves the file pattern
private boolean separate = false;
public void setFile(String file) {
super.setFile(file);
this.fileBackup = getFile();
}
/**
* If true each LoggingEvent causes that file to close and open.
* This is useful when the file is a pattern that would often
* produce a different filename.
*/
public void setSeparate(boolean separate) {
this.separate = separate;
}
protected void subAppend(LoggingEvent event) {
if(separate) {
try {//First reset the file so each new log gets a new file.
setFile(getFile(), getAppend(), getBufferedIO(), getBufferSize());
} catch(IOException e) {
LogLog.error("Unable to reset fileName.");
}
}
super.subAppend(event);
}
public
synchronized
void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)
throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat(fileBackup);
String actualFileName = sdf.format(new Date());
makeDirs(actualFileName);
super.setFile(actualFileName, append, bufferedIO, bufferSize);
}
/**
* Ensures that all of the directories for the given path exist.
* Anything after the last / or \ is assumed to be a filename.
*/
private void makeDirs (String path) {
int indexSlash = path.lastIndexOf("/");
int indexBackSlash = path.lastIndexOf("\\");
int index = Math.max(indexSlash, indexBackSlash);
if(index > 0) {
String dirs = path.substring(0, index);
// LogLog.debug("Making " + dirs);
File dir = new File(dirs);
if(!dir.exists()) {
boolean success = dir.mkdirs();
if(!success) {
LogLog.error("Unable to create directories for " + dirs);
}
}
}
}
}
Have you tried using str.splitlines()
method?:
From the docs:
Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless
keepends
is given and true.
For example:
>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()
['Line 1', '', 'Line 3', 'Line 4']
>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines(True)
['Line 1\n', '\n', 'Line 3\r', 'Line 4\r\n']
This method uses the universal newlines approach to splitting lines.
The main difference between Python 2.X
and Python 3.X
is that the former uses the universal newlines approach to splitting lines, so "\r"
, "\n"
, and "\r\n"
are considered line boundaries for 8-bit strings, while the latter uses a superset of it that also includes:
\v
or \x0b
: Line Tabulation (added in Python 3.2
).\f
or \x0c
: Form Feed (added in Python 3.2
).\x1c
: File Separator.\x1d
: Group Separator.\x1e
: Record Separator.\x85
: Next Line (C1 Control Code).\u2028
: Line Separator.\u2029
: Paragraph Separator.Unlike
str.split()
when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:
>>> ''.splitlines()
[]
>>> 'Line 1\n'.splitlines()
['Line 1']
While str.split('\n')
returns:
>>> ''.split('\n')
['']
>>> 'Line 1\n'.split('\n')
['Line 1', '']
If you also need to remove additional leading or trailing whitespace, like spaces, that are ignored by str.splitlines()
, you could use str.splitlines()
together with str.strip()
:
>>> [str.strip() for str in 'Line 1 \n \nLine 3 \rLine 4 \r\n'.splitlines()]
['Line 1', '', 'Line 3', 'Line 4']
Lastly, if you want to filter out the empty strings from the resulting list, you could use filter()
:
>>> # Python 2.X:
>>> filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines())
['Line 1', 'Line 3', 'Line 4']
>>> # Python 3.X:
>>> list(filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()))
['Line 1', 'Line 3', 'Line 4']
As the error you posted indicates and Burhan suggested, the problem is from the print. There's a related question about that could be useful to you: UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function
To start with, from the Oracle Database Data Warehousing Guide:
Restrictions on Fast Refresh on Materialized Views with Joins Only
...
- Rowids of all the tables in the FROM list must appear in the SELECT list of the query.
This means that your statement will need to look something like this:
CREATE MATERIALIZED VIEW MV_Test
NOLOGGING
CACHE
BUILD IMMEDIATE
REFRESH FAST ON COMMIT
AS
SELECT V.*, P.*, V.ROWID as V_ROWID, P.ROWID as P_ROWID
FROM TPM_PROJECTVERSION V,
TPM_PROJECT P
WHERE P.PROJECTID = V.PROJECTID
Another key aspect to note is that your materialized view logs must be created as with rowid
.
Below is a functional test scenario:
CREATE TABLE foo(foo NUMBER, CONSTRAINT foo_pk PRIMARY KEY(foo));
CREATE MATERIALIZED VIEW LOG ON foo WITH ROWID;
CREATE TABLE bar(foo NUMBER, bar NUMBER, CONSTRAINT bar_pk PRIMARY KEY(foo, bar));
CREATE MATERIALIZED VIEW LOG ON bar WITH ROWID;
CREATE MATERIALIZED VIEW foo_bar
NOLOGGING
CACHE
BUILD IMMEDIATE
REFRESH FAST ON COMMIT AS SELECT foo.foo,
bar.bar,
foo.ROWID AS foo_rowid,
bar.ROWID AS bar_rowid
FROM foo, bar
WHERE foo.foo = bar.foo;
If you are using terminal just type the following:
locate my.cnf
dynamic MsgResult = this.ShowMessageBox("Do you want to cancel all pending changes ?", "Cancel Changes", MessageBoxOption.YesNo);
if (MsgResult == System.Windows.MessageBoxResult.Yes)
{
enter code here
}
else
{
enter code here
}
Check more detail from here
There are multiple ways to set profiles for your springboot application.
You can add this in your property file:
spring.profiles.active=dev
Programmatic way:
SpringApplication.setAdditionalProfiles("dev");
Tests make it very easy to specify what profiles are active
@ActiveProfiles("dev")
In a Unix environment
export spring_profiles_active=dev
JVM System Parameter
-Dspring.profiles.active=dev
Example: Running a springboot jar file with profile.
java -jar -Dspring.profiles.active=dev application.jar
I have not tried this, so I am not guarantueeing anything, however
foreach Bar f in filterBars
{
search(f)
}
Foo search(Bar b)
{
fooSelect = (from f in fooBunch
where !(from b in f.BarList select b.BarId).Contains(b.ID)
select f).ToList();
return fooSelect;
}
I like the fundamental differences in the way that Ruby and Python method invocations operate.
Ruby methods are invoked via a form "message passing" and need not be explicitly first-class functions (there are ways to lift methods into "proper" function-objects) -- in this aspect Ruby is similar to Smalltalk.
Python works much more like JavaScript (or even Perl) where methods are functions which are invoked directly (there is also stored context information, but...)
While this might seem like a "minor" detail it is really just the surface of how different the Ruby and Python designs are. (On the other hand, they are also quite the same :-)
One practical difference is the concept of method_missing
in Ruby (which, for better or worse, seems to be used in some popular frameworks). In Python, one can (at least partially) emulate the behavior using __getattr__/__getattribute__, albeit non-idiomatically.
Really annoying thing in PS 5, where $_ won't be the full path within foreach. These are the string versions of FileInfo and DirectoryInfo objects. For some reason a wildcard in the path fixes it, or use Powershell 6 or 7. You can also pipe to get-item in the middle.
Get-ChildItem -path C:\WINDOWS\System32\*.txt -Recurse | foreach { "$_" }
Get-ChildItem -path C:\WINDOWS\System32 -Recurse | get-item | foreach { "$_" }
This seems to have been an issue with .Net that got resolved in .Net Core (Powershell 7): Stringification behavior of FileInfo / Directory instances has changed since v6.0.2 #7132
How about calling the .NET Framework methods?
You can do ANYTHING with them... :
[System.IO.File]::Copy($src, $dest, $true);
The $true
argument makes it overwrite.
when LD_PRELOAD is used that file will be loaded before any other
$export LD_PRELOAD=/path/lib
lib to be pre loaded, even this can be used in programs too
JavaScript that allows for syntax checking
JSHint-Eclipse
and autosuggestions for .js files in Eclipse?
http://www.nodeclipse.org/updates/anide/
As Nodeclipse lead, I am always looking for what is available in Eclipse ecosystem. Nodeclipse site has even more links, and I am inviting to collaborate on the JavaScript tools on GitHub
I tried almost anything but no help...
Everytime was just this
? ~ adb devices
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
aeef5e4e unauthorized
However I've managed to connect device!
There is tutor, step by step.
$ rm -v .android/adbkey*
.android/adbkey
.android/adbkey.pub
Remove existing authorized adb keys on device, path is /data/misc/adb/adb_keys
Now create new adb keypair
? ~ adb keygen .android/adbkey
adb I 47453 711886 adb_auth_host.cpp:220] generate_key '.android/adbkey'
adb I 47453 711886 adb_auth_host.cpp:173] Writing public key to '.android/adbkey.pub'
Manually copy from PC .android/adbkey.pub
(pubkic key) to Device on path /data/misc/adb/adb_keys
Reboot device and check adb devices
:
? ~ adb devices
List of devices attached
aeef5e4e device
Permissions of /data/misc/adb/adb_keys
are (766/-rwxrw-rw-)
on my device
I also wanted an email sent if the service was started this way so added a bit to @Ic code just thought I would post it in case it helped anyone. I used SendMail but there are other command line options How to send a simple email from a Windows batch file?
set service=MyServiceName
for /F "tokens=3 delims=: " %%H in ('sc query %service% ^| findstr " STATE"') do (
if /I "%%H" NEQ "RUNNING" (
net start %service%
for /F "tokens=3 delims=: " %%H in ('sc query %service% ^| findstr " STATE"') do (
if /I "%%H" EQ "RUNNING" (
SendMail /smtpserver localhost /to [email protected] /from [email protected] /subject Service Autostart Notification /body Autostart on service %service% succeded.
) else (
SendMail /smtpserver localhost /to [email protected] /from [email protected] /subject Service Autostart Notification /body Autostart on service %service% failed.
)
)
)
)
Try
var marker = new google.maps.Marker({
position: map.getCenter(),
icon: 'http://imageshack.us/a/img826/9489/x1my.png',
map: map
});
from here
https://developers.google.com/maps/documentation/javascript/examples/marker-symbol-custom
Notice you're not dynamically allocating the variable, which pretty much means the data inside str
, in your function, will be lost by the end of the function.
You should have:
char * createStr() {
char char1= 'm';
char char2= 'y';
char *str = malloc(3);
str[0] = char1;
str[1] = char2;
str[2] = '\0';
return str;
}
Then, when you call the function, the type of the variable that will receive the data must match that of the function return. So, you should have:
char *returned_str = createStr();
It worths mentioning that the returned value must be freed to prevent memory leaks.
char *returned_str = createStr();
//doSomething
...
free(returned_str);
You can make a ImageButton
with circular background image.
I had this issue in a very simple DELETE statement, and it is now solved.
My issue was due to using backticks around the column (this column was named "id").
This query DID NOT WORK and resulted in "No operator matches the given name and argument type(s)
"
DELETE FROM mytable WHERE `id` = 3 -- DO NOT USE BACKTICKS
Coming from mysql, in dynamic queries, I always `backtick` columns.
The following query DID WORK (with backticks removed):
DELETE FROM mytable WHERE id = 3
My code uses a Source
table that changes, and a Destination
table that must match those changes.
--
-- Sample SQL to update only rows in a "Destination" Table
-- based on only rows that have changed in a "Source" table
--
--
-- Drop and Create a Temp Table to use as the "Source" Table
--
IF OBJECT_ID('tempdb..#tSource') IS NOT NULL drop table #tSource
create table #tSource (Col1 int, Col2 int, Col3 int, Col4 int)
--
-- Insert some values into the source
--
Insert #tSource (Col1, Col2, Col3, Col4) Values(1,1,1,1)
Insert #tSource (Col1, Col2, Col3, Col4) Values(2,1,1,2)
Insert #tSource (Col1, Col2, Col3, Col4) Values(3,1,1,3)
Insert #tSource (Col1, Col2, Col3, Col4) Values(4,1,1,4)
Insert #tSource (Col1, Col2, Col3, Col4) Values(5,1,1,5)
Insert #tSource (Col1, Col2, Col3, Col4) Values(6,1,1,6)
--
-- Drop and Create a Temp Table to use as the "Destination" Table
--
IF OBJECT_ID('tempdb..#tDest') IS NOT NULL drop Table #tDest
create table #tDest (Col1 int, Col2 int, Col3 int, Col4 int)
--
-- Add all Rows from the Source to the Destination
--
Insert #tDest
Select Col1, Col2, Col3, Col4 from #tSource
--
-- Look at both tables to see that they are the same
--
select *
from #tSource
Select *
from #tDest
--
-- Make some changes to the Source
--
update #tSource
Set Col3=19
Where Col1=1
update #tSource
Set Col3=29
Where Col1=2
update #tSource
Set Col2=38
Where Col1=3
update #tSource
Set Col2=48
Where Col1=4
--
-- Look at the Differences
-- Note: Only 4 rows are different. 2 Rows have remained the same.
--
Select Col1, Col2, Col3, Col4
from #tSource
except
Select Col1, Col2, Col3, Col4
from #tDest
--
-- Update only the rows that have changed
-- Note: I am using Col1 like an ID column
--
Update #tDest
Set Col2=S.Col2,
Col3=S.Col3,
Col4=S.Col4
From ( Select Col1, Col2, Col3, Col4
from #tSource
except
Select Col1, Col2, Col3, Col4
from #tDest
) S
Where #tDest.Col1=S.Col1
--
-- Look at the tables again to see that
-- the destination table has changed to match
-- the source table.
select *
from #tSource
Select *
from #tDest
--
-- Clean Up
--
drop table #tSource
drop table #tDest
var currencyInput = document.querySelector('input[type="currency"]')
var currency = 'GBP' // https://www.currency-iso.org/dam/downloads/lists/list_one.xml
// format inital value
onBlur({target:currencyInput})
// bind event listeners
currencyInput.addEventListener('focus', onFocus)
currencyInput.addEventListener('blur', onBlur)
function localStringToNumber( s ){
return Number(String(s).replace(/[^0-9.-]+/g,""))
}
function onFocus(e){
var value = e.target.value;
e.target.value = value ? localStringToNumber(value) : ''
}
function onBlur(e){
var value = e.target.value
var options = {
maximumFractionDigits : 2,
currency : currency,
style : "currency",
currencyDisplay : "symbol"
}
e.target.value = (value || value === 0)
? localStringToNumber(value).toLocaleString(undefined, options)
: ''
}
_x000D_
input{
padding: 10px;
font: 20px Arial;
width: 70%;
}
_x000D_
<input type='currency' value="123" placeholder='Type a number & click outside' />
_x000D_
Here's a very simple demo illustrating the above method (HTML-only)
I've made a tiny React component if anyone's interested
Look at the System.IO.Directory
class and the static method GetFiles
. It has an overload that accepts a path and a search pattern. Example:
string[] files = System.IO.Directory.GetFiles(path, "*.txt");
REGEX should be a last resort. PHP has a few functions that will validate for you. In your case, checkdate is the best option. http://php.net/manual/en/function.checkdate.php
Partridge and Gareths comments above are great. They deserve a separate answer. Apparently, hash and search properties are available on any html Link object:
<a id="test" href="foo.html?bar#quz">test</a>
<script type="text/javascript">
alert(document.getElementById('test').search); //bar
alert(document.getElementById('test').hash); //quz
</script>
Or
<a href="bar.html?foo" onclick="alert(this.search)">SAY FOO</a>
Should you need this on a regular string variable and happen to have jQuery around, this should work:
var mylink = "foo.html?bar#quz";
if ($('<a href="'+mylink+'">').get(0).search=='bar')) {
// do stuff
}
(but its maybe a bit overdone .. )
require(ggplot2)
require(nlme)
set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)
mp <- within(mp,
{
wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
wow <- rnorm(N)*wav+rnorm(N)*wav^3
})
m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))
Get fitted values (the same as m01$fitted
)
fit <- predict(m01)
Normally we could use something like predict(...,se.fit=TRUE)
to get the confidence intervals on the prediction, but gls
doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :
V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
Put together a "prediction frame":
predframe <- with(mp,data.frame(year,wav,
wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))
Now plot with geom_ribbon
(p1 <- ggplot(mp, aes(year, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It's easier to see that we got the right answer if we plot against wav
rather than year
:
(p2 <- ggplot(mp, aes(wav, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly()
fits -- see ?makepredictcall
.
Use below line of code in the case of Spring Boot Application Add in Spring Boot Main Class @EntityScan(basePackageClasses=YourClassName.class)
Extracted from here: http://git.661346.n2.nabble.com/Revert-a-single-commit-in-a-single-file-td6064050.html
git revert <commit>
git reset
git add <path>
git commit ...
git reset --hard # making sure you didn't have uncommited changes earlier
It worked very fine to me.
No. You have to use is null
and is not null
in HQL.
Read a file as a string full version (handling exceptions, using UTF-8, handling new line):
// Calling:
/*
Context context = getApplicationContext();
String filename = "log.txt";
String str = read_file(context, filename);
*/
public String read_file(Context context, String filename) {
try {
FileInputStream fis = context.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (FileNotFoundException e) {
return "";
} catch (UnsupportedEncodingException e) {
return "";
} catch (IOException e) {
return "";
}
}
Note: you don't need to bother about file path only with file name.
Git has two types of branches: local
and remote
. To use git pull
and git push
as you'd like, you have to tell your local branch (my_test
) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.
Commands
Make sure you're on your master
branch with
1)git checkout master
then create the new branch with
2)git branch --track my_test origin/my_test
and check it out with
3)git checkout my_test
.
You can then push
and pull
without specifying which local and remote.
However if you've already created the branch then you can use the -u
switch to tell git's push
and pull
you'd like to use the specified local and remote branches from now on, like so:
git pull -u my_test origin/my_test
git push -u my_test origin/my_test
Config
The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config
and add the following to the bottom.
[remote "origin"]
url = [email protected]:username/repo.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
remote = origin
merge = refs/heads/my_test
This specifies a remote called origin
, in this case a GitHub style one, and then tells the branch my_test
to use it as it's remote.
You can find something very similar to this in the config after running the commands above.
Some useful resources:
Just make a new Date
object with the stamp's getTime()
value as a parameter.
Here's an example (I use an example timestamp of the current time):
Timestamp stamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(stamp.getTime());
System.out.println(date);
Copy =VLOOKUP(M3,A$2:Q$47,13,FALSE)
to other sheets, then search for ! replace by !$, search for : replace by :$ one time for all sheets
One more very basic and simple solution. Run the related python version's installation file (setup file) and click repair mode. It hardly takes one-two minutes and everything works perfectly after that :)
For JavaScript use:
document.getElementsByClassName('select-holder')[0].placeholder = "This is my new text";
For jQuery use:
$('.select-holder')[0].placeholder = "This is my new text";
JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of object.
(Plain) Objects have the form
{key: value, key: value, ...}
Arrays have the form
[value, value, ...]
Both arrays and objects expose a key -> value
structure. Keys in an array must be numeric, whereas any string can be used as key in objects. The key-value pairs are also called the "properties".
Properties can be accessed either using dot notation
const value = obj.someProperty;
or bracket notation, if the property name would not be a valid JavaScript identifier name [spec], or the name is the value of a variable:
// the space is not a valid character in identifier names
const value = obj["some Property"];
// property name as variable
const name = "some Property";
const value = obj[name];
For that reason, array elements can only be accessed using bracket notation:
const value = arr[5]; // arr.5 would be a syntax error
// property name / index as variable
const x = 5;
const value = arr[x];
JSON is a textual representation of data, just like XML, YAML, CSV, and others. To work with such data, it first has to be converted to JavaScript data types, i.e. arrays and objects (and how to work with those was just explained). How to parse JSON is explained in the question Parse JSON in JavaScript? .
How to access arrays and objects is fundamental JavaScript knowledge and therefore it is advisable to read the MDN JavaScript Guide, especially the sections
A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.
Here is an example:
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
Let's assume we want to access the name
of the second item.
Here is how we can do it step-by-step:
As we can see data
is an object, hence we can access its properties using dot notation. The items
property is accessed as follows:
data.items
The value is an array, to access its second element, we have to use bracket notation:
data.items[1]
This value is an object and we use dot notation again to access the name
property. So we eventually get:
const item_name = data.items[1].name;
Alternatively, we could have used bracket notation for any of the properties, especially if the name contained characters that would have made it invalid for dot notation usage:
const item_name = data['items'][1]['name'];
undefined
back?Most of the time when you are getting undefined
, the object/array simply doesn't have a property with that name.
const foo = {bar: {baz: 42}};
console.log(foo.baz); // undefined
Use console.log
or console.dir
and inspect the structure of object / array. The property you are trying to access might be actually defined on a nested object / array.
console.log(foo.bar.baz); // 42
If the property names are unknown or we want to access all properties of an object / elements of an array, we can use the for...in
[MDN] loop for objects and the for
[MDN] loop for arrays to iterate over all properties / elements.
Objects
To iterate over all properties of data
, we can iterate over the object like so:
for (const prop in data) {
// `prop` contains the name of each property, i.e. `'code'` or `'items'`
// consequently, `data[prop]` refers to the value of each property, i.e.
// either `42` or the array
}
Depending on where the object comes from (and what you want to do), you might have to test in each iteration whether the property is really a property of the object, or it is an inherited property. You can do this with Object#hasOwnProperty
[MDN].
As alternative to for...in
with hasOwnProperty
, you can use Object.keys
[MDN] to get an array of property names:
Object.keys(data).forEach(function(prop) {
// `prop` is the property name
// `data[prop]` is the property value
});
Arrays
To iterate over all elements of the data.items
array, we use a for
loop:
for(let i = 0, l = data.items.length; i < l; i++) {
// `i` will take on the values `0`, `1`, `2`,..., i.e. in each iteration
// we can access the next element in the array with `data.items[i]`, example:
//
// var obj = data.items[i];
//
// Since each element is an object (in our example),
// we can now access the objects properties with `obj.id` and `obj.name`.
// We could also use `data.items[i].id`.
}
One could also use for...in
to iterate over arrays, but there are reasons why this should be avoided: Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?.
With the increasing browser support of ECMAScript 5, the array method forEach
[MDN] becomes an interesting alternative as well:
data.items.forEach(function(value, index, array) {
// The callback is executed for each element in the array.
// `value` is the element itself (equivalent to `array[index]`)
// `index` will be the index of the element in the array
// `array` is a reference to the array itself (i.e. `data.items` in this case)
});
In environments supporting ES2015 (ES6), you can also use the for...of
[MDN] loop, which not only works for arrays, but for any iterable:
for (const item of data.items) {
// `item` is the array element, **not** the index
}
In each iteration, for...of
directly gives us the next element of the iterable, there is no "index" to access or use.
In addition to unknown keys, the "depth" of the data structure (i.e. how many nested objects) it has, might be unknown as well. How to access deeply nested properties usually depends on the exact data structure.
But if the data structure contains repeating patterns, e.g. the representation of a binary tree, the solution typically includes to recursively [Wikipedia] access each level of the data structure.
Here is an example to get the first leaf node of a binary tree:
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild); // <- recursive call
}
else if (node.rightChild) {
return getLeaf(node.rightChild); // <- recursive call
}
else { // node must be a leaf node
return node;
}
}
const first_leaf = getLeaf(root);
const root = {_x000D_
leftChild: {_x000D_
leftChild: {_x000D_
leftChild: null,_x000D_
rightChild: null,_x000D_
data: 42_x000D_
},_x000D_
rightChild: {_x000D_
leftChild: null,_x000D_
rightChild: null,_x000D_
data: 5_x000D_
}_x000D_
},_x000D_
rightChild: {_x000D_
leftChild: {_x000D_
leftChild: null,_x000D_
rightChild: null,_x000D_
data: 6_x000D_
},_x000D_
rightChild: {_x000D_
leftChild: null,_x000D_
rightChild: null,_x000D_
data: 7_x000D_
}_x000D_
}_x000D_
};_x000D_
function getLeaf(node) {_x000D_
if (node.leftChild) {_x000D_
return getLeaf(node.leftChild);_x000D_
} else if (node.rightChild) {_x000D_
return getLeaf(node.rightChild);_x000D_
} else { // node must be a leaf node_x000D_
return node;_x000D_
}_x000D_
}_x000D_
_x000D_
console.log(getLeaf(root).data);
_x000D_
A more generic way to access a nested data structure with unknown keys and depth is to test the type of the value and act accordingly.
Here is an example which adds all primitive values inside a nested data structure into an array (assuming it does not contain any functions). If we encounter an object (or array) we simply call toArray
again on that value (recursive call).
function toArray(obj) {
const result = [];
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value)); // <- recursive call
}
else {
result.push(value);
}
}
return result;
}
const data = {_x000D_
code: 42,_x000D_
items: [{_x000D_
id: 1,_x000D_
name: 'foo'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'bar'_x000D_
}]_x000D_
};_x000D_
_x000D_
_x000D_
function toArray(obj) {_x000D_
const result = [];_x000D_
for (const prop in obj) {_x000D_
const value = obj[prop];_x000D_
if (typeof value === 'object') {_x000D_
result.push(toArray(value));_x000D_
} else {_x000D_
result.push(value);_x000D_
}_x000D_
}_x000D_
return result;_x000D_
}_x000D_
_x000D_
console.log(toArray(data));
_x000D_
Since the structure of a complex object or array is not necessarily obvious, we can inspect the value at each step to decide how to move further. console.log
[MDN] and console.dir
[MDN] help us doing this. For example (output of the Chrome console):
> console.log(data.items)
[ Object, Object ]
Here we see that that data.items
is an array with two elements which are both objects. In Chrome console the objects can even be expanded and inspected immediately.
> console.log(data.items[1])
Object
id: 2
name: "bar"
__proto__: Object
This tells us that data.items[1]
is an object, and after expanding it we see that it has three properties, id
, name
and __proto__
. The latter is an internal property used for the prototype chain of the object. The prototype chain and inheritance is out of scope for this answer, though.
As an alternate method, if you know that there are no spaces in your data, which it seems is the case, you can use split() (with no arguments). This splits on white space and uses a more efficient algorithm than the other version of split. It also strips whitespace from both ends.
line = line.split()
And that's it.
for (var key in data) {
alert("User " + data[key] + " is #" + key); // "User john is #234"
}
Branches are made of wood and grow from the trunk of the tree. Tags are made of paper (derivative of wood) and hang like Christmas Ornaments from various places in the tree.
Your project is the tree, and your feature that will be added to the project will grow on a branch. The answer is branch.
I made a annotation library that can do the cast for you. check this out. https://github.com/zeroarst/callbackfragment/
@CallbackFragment
public class MyFragment extends Fragment {
@Callback
interface FragmentCallback {
void onClickButton(MyFragment fragment);
}
private FragmentCallback mCallback;
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt1
mCallback.onClickButton(this);
break;
case R.id.bt2
// Because we give mandatory = false so this might be null if not implemented by the host.
if (mCallbackNotForce != null)
mCallbackNotForce.onClickButton(this);
break;
}
}
}
It then generates a subclass of your fragment. And just add it to FragmentManager.
public class MainActivity extends AppCompatActivity implements MyFragment.FragmentCallback {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.add(R.id.lo_fragm_container, MyFragmentCallbackable.create(), "MY_FRAGM")
.commit();
}
Toast mToast;
@Override
public void onClickButton(MyFragment fragment) {
if (mToast != null)
mToast.cancel();
mToast = Toast.makeText(this, "Callback from " + fragment.getTag(), Toast.LENGTH_SHORT);
mToast.show();
}
}
The selector criteria is now an attribute the DIV tag.
examples are ...
data-date-format="dd MM yyyy"
data-date-format="dd MM yyyy - HH:ii p
data-date-format="hh:ii"
so the bootstrap example for dd mm yyyy is:-
<div class="input-group date form_date col-md-5" data-date=""
data-date-format="dd MM yyyy" data-link-field="dtp_input2" data-link-format="yyyy-mm-dd">
..... etc ....
</div>
my Javascript settings are as follows:-
var picker_settings = {
language: 'en',
weekStart: 1,
todayBtn: 1,
autoclose: 1,
todayHighlight: 1,
startView: 2,
minView: 2,
forceParse: 0
};
$(datePickerId).datetimepicker(picker_settings);
You can see working examples of these if you download the bootstrap-datetimepicker-master file. There are sample folders each with an index.html.
If your div is an ASP.NET control with runat="server" then AviewAnew's answer should do it. If it's just an HTML div, then you'd probably want to use JavaScript. Can you add the actual div tag to your question?