It's possible to effectively define a variable that can be used in both the SELECT, WHERE and other clauses.
A subquery doesn't necessarily allow for appropriate binding to the referenced table columns, however OUTER APPLY does.
SELECT A.identifier
, A.name
, vars.MONTH_NO
, TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
FROM table_a A
, table_b B ON A.identifier = B.identifier
OUTER APPLY (
SELECT
-- variables
MONTH_NO = TO_NUMBER(DECODE( A.month_no
, 1, 200803
, 2, 200804
, 3, 200805
, 4, 200806
, 5, 200807
, 6, 200808
, 7, 200809
, 8, 200810
, 9, 200811
, 10, 200812
, 11, 200701
, 12, 200702
, NULL))
) vars
WHERE vars.MONTH_NO > UPD_DATE
Kudos to Syed Mehroz Alam.
Have you compared the table definitions in Prod and Dev?
And when you are running it in SQL Developer, are you running the query in Prod (same database as the application) and with the same user?
If there are some additional columns that you are adding (using an alter command) and these changes are not yet promoted to prod, this issue is possible.
Can you post the definition of the table and your actual Query?
Also make sure the user issuing the query has been granted the necessary permissions.
For queries on tables you need to grant SELECT permission.
For queries on other object types (e.g. stored procedures) you need to grant EXECUTE permission.
How about using an expression which evaluates to TRUE (or FALSE)?
select get_something('NAME', 1 = 1) from dual
It's actually:
Console.WriteLine(Encoding.Default.GetString(value));
or for UTF-8 specifically:
Console.WriteLine(Encoding.UTF8.GetString(value));
You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--'
as one of the values.
string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief, ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
// ... other parameters
myCommand.ExecuteNonQuery();
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
The expression df1$id %in% idNums1
produces a logical vector. To negate it, you need to negate the whole vector:
!(df1$id %in% idNums1)
Try this:
MessageBox.Show("Some text", "Some title",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Seba Illingworth's code, In case you need time in your file name (it gives 2014-02-21_1035)
echo off
cls
echo -- BACKUP DATABASE --
set /p DATABASENAME=Enter database name:
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
:: filename format Name-Date (eg MyDatabase-2009.5.19.bak)
set DATESTAMP=%mydate%_%mytime%
set BACKUPFILENAME=%CD%\%DATABASENAME%-%DATESTAMP%.bak
set SERVERNAME=.
echo.
sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
pause
<script type="text/javascript" src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}
</script>
Technically, your inner DIV (#container
) is centered horizontally. The reason you can't tell is because with the CSS width: auto
property the inner DIV is expanding to the same width as its parent.
See this fiddle: http://jsfiddle.net/UZ4AE/
#container {
width: 50px;
height: auto;
margin: 0 auto;
padding: 10px;
position: relative;
background-color: red;
}
In this example, I simply set the width of #container
to 50px
and set the background to red
so that you can see that it is centered.
I think the real question is "How do I center elements horizontally with CSS?" and the answer is (drum roll please): it depends!
I won't do a full rehash of the myriad ways to center things with CSS when W3Schools does it so nicely here: http://www.w3schools.com/css/css_align.asp but the basic idea is that for block level elements you simply specify the desired width and set the left and right margins to auto
.
.center {
margin-left: auto;
margin-right: auto;
width: 50px;
}
Please note: This answer only applies to block level elements! To position an inline element, you will need to use the text-align: center
property on the first block parent.
From the Wikipedia article on Java package naming:
In general, a package name begins with the top level domain name of the organization and then the organization's domain and then any subdomains, listed in reverse order. The organization can then choose a specific name for its package. Package names should be all lowercase characters whenever possible.
For example, if an organization in Canada called MySoft creates a package to deal with fractions, naming the package ca.mysoft.fractions distinguishes the fractions package from another similar package created by another company. If a US company named MySoft also creates a fractions package, but names it us.mysoft.fractions, then the classes in these two packages are defined in a unique and separate namespace.
$newstr = preg_replace('/[^a-zA-Z0-9\']/', '_', "There wouldn't be any");
$newstr = str_replace("'", '', $newstr);
I put them on two separate lines to make the code a little more clear.
Note: If you're looking for Unicode support, see Filip's answer below. It will match all characters that register as letters in addition to A-z
.
Ensure that all the libraries you're using in your project are not being referenced from other project int the workspace. That was my problem.
If you have a list of lists (tracked_output_sheet in my case), where you want to delete last element from each list, you can use the following code:
interim = []
for x in tracked_output_sheet:interim.append(x[:-1])
tracked_output_sheet= interim
Think of it as enforcing Eager-Loading in a scenario where you sub-items would otherwise be lazy-loading.
The Query EF is sending to the database will yield a larger result at first, but on access no follow-up queries will be made when accessing the included items.
On the other hand, without it, EF would execute separte queries later, when you first access the sub-items.
public static void openWebPage(String url) {
try {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
desktop.browse(new URI(url));
}
throw new NullPointerException();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, url, "", JOptionPane.PLAIN_MESSAGE);
}
}
There is a special variable inside all functions: arguments. You can pass your parameters as anonymous parameters and access them (by order) through the arguments variable.
Example:
var someVar = some_other_function();
someObj.addEventListener("click", function(someVar){
some_function(arguments[0]);
}, false);
You can use the CSS property max-width
and use it with ch
unit.
And, as this is a <span>
, use a display: inline-block;
(or block).
Here is an example:
<span style="
display:inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 13ch;">
Lorem ipsum dolor sit amet
</span>
Which outputs:
Lorem ipsum...
<span style="_x000D_
display:inline-block;_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
max-width: 13ch;">_x000D_
Lorem ipsum dolor sit amet_x000D_
</span>
_x000D_
I had this issue when i tried to connect to postgresql while i'm using microsoft sutdio for mssql :)
Check your URL's protocol.
You will also see this error if you host an encrypted page (https) and open it as plain text (http) in Firefox.
List<string> myCollection = new List<string>()
{
"Bob", "Bob","Alex", "Abdi", "Abdi", "Bob", "Alex", "Bob","Abdi"
};
myCollection.Sort();
foreach (var name in myCollection.Distinct())
{
Console.WriteLine(name + " " + myCollection.Count(x=> x == name));
}
output: Abdi 3 Alex 2 Bob 4
I met a similar error after adding jQuery-ui-tooltip component using bower. It downloads js + css files only, so I had to manually add images.
A good source to find all the images (for all standard themes) is this CDN.
You're missing a close paren in this line:
fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494
There are three ( and only two ).
I hope This will help you.
First represent the epoch of the millisecond time as a date (usually 1/1/1970), then add your millisecond time divided by the number of milliseconds in a day (86400000):
=DATE(1970,1,1)+(A1/86400000)
If your cell is properly formatted, you should see a human-readable date/time.
The BETWEEN operator is inclusive.
From Books Online:
BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.
DateTime Caveat
NB: With DateTimes you have to be careful; if only a date is given the value is taken as of midnight on that day; to avoid missing times within your end date, or repeating the capture of the following day's data at midnight in multiple ranges, your end date should be 3 milliseconds before midnight on of day following your to date. 3 milliseconds because any less than this and the value will be rounded up to midnight the next day.
e.g. to get all values within June 2016 you'd need to run:
where myDateTime between '20160601' and DATEADD(millisecond, -3, '20160701')
i.e.
where myDateTime between '20160601 00:00:00.000' and '20160630 23:59:59.997'
Subtracting 3 ms from a date will leave you vulnerable to missing rows from the 3 ms window. The correct solution is also the simplest one:
where myDateTime >= '20160601' AND myDateTime < '20160701'
Set height for modal-body
and not for the whole modal to get a perfect scroll on modal overlay. I get it work like this:
.MyModal {
height: 450px;
overflow-y: auto;
}
Here you can set height as per your requirements.
If you don't need a plot per say, and you're simply interested in adding color to represent the values in a table format, you can use the style.background_gradient()
method of the pandas data frame. This method colorizes the HTML table that is displayed when viewing pandas data frames in e.g. the JupyterLab Notebook and the result is similar to using "conditional formatting" in spreadsheet software:
import numpy as np
import pandas as pd
index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
cols = ['A', 'B', 'C', 'D']
df = pd.DataFrame(abs(np.random.randn(5, 4)), index=index, columns=cols)
df.style.background_gradient(cmap='Blues')
For detailed usage, please see the more elaborate answer I provided on the same topic previously and the styling section of the pandas documentation.
As described by the others, writing to /dev/null eliminates the output of a program. Usually cron sends an email for every output from the process started with a cronjob. So by writing the output to /dev/null you prevent being spammed if you have specified your adress in cron.
Latest Android Studio 1.4.
Click File->Project Structure->SDK Location->JDK Location.
You could also set individual module JDK Version compatibility by going to the Module (below the SDK Location), and edit the Source Compatibility accordingly. (note, this only applies to Android Module).
I haven't done this in a while, but I had to go through this same thing once.
<img src="about:blank" alt="" />
Is my favorite - the //:0
one implies that you'll try to make an HTTP/HTTPS connection to the origin server on port zero (the tcpmux port?) - which is probably harmless, but I'd rather not do anyways. Heck, the browser may see the port zero and not even send a request. But I'd still rather it not be specified that way when that's probably not what you mean.
Anyways, the rendering of about:blank
is actually very fast in all browsers that I tested. I just threw it into the W3C validator and it didn't complain, so it might even be valid.
Edit: Don't do that; it doesn't work on all browsers (it will show a 'broken image' icon as pointed out in the comments for this answer). Use the <img src='data:...
solution below. Or if you don't care about validity, but still want to avoid superfluous requests to your server, you can do <img alt="" />
with no src attribute. But that is INVALID HTML so pick that carefully.
Test Page showing a whole bunch of different methods: http://desk.nu/blank_image.php - served with all kinds of different doctypes and content-types. - as mentioned in the comments below, use Mark Ormston's new test page at: http://memso.com/Test/BlankImage.html
sed -n 's/^potato:[[:space:]]*//p' file.txt
One can think of Grep as a restricted Sed, or of Sed as a generalized Grep. In this case, Sed is one good, lightweight tool that does what you want -- though, of course, there exist several other reasonable ways to do it, too.
<>
is equal to !=
i.e, both are used to represent the NOT EQUAL operation. For instance, email <> ''
and email != ''
are same.
in case if your table has tbody
let tbl = document.getElementById("tbl").getElementsByTagName('tbody')[0];
console.log(tbl.rows[0].cells[0].innerHTML)
This will work fine with Linq to Objects. However, some LINQ providers have difficulty running CLR methods as part of the query. This is expecially true of some database providers.
The problem is that the DB providers try to move and compile the LINQ query as a database query, to prevent pulling all of the objects across the wire. This is a good thing, but does occasionally restrict the flexibility in your predicates.
Unfortunately, without checking the provider documentation, it's difficult to always know exactly what will or will not be supported directly in the provider. It looks like your provider allows comparisons, but not the string check. I'd guess that, in your case, this is probably about as good of an approach as you can get. (It's really not that different from the IsNullOrEmpty check, other than creating the "string.Empty" instance for comparison, but that's minor.)
What about adding an empty test method to these classes?
public void avoidAnnoyingErrorMessageWhenRunningTestsInAnt() {
assertTrue(true); // do nothing;
}
The following code works fine:
@using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
and generates as expected:
<form action="/Upload/Upload" enctype="multipart/form-data" method="post">
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
</form>
On the other hand if you are writing this code inside the context of other server side construct such as an if
or foreach
you should remove the @
before the using
. For example:
@if (SomeCondition)
{
using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
}
As far as your server side code is concerned, here's how to proceed:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Upload");
}
The syntax is
pid_t waitpid(pid_t pid, int *statusPtr, int options);
1.where pid is the process of the child it should wait.
2.statusPtr is a pointer to the location where status information for the terminating process is to be stored.
3.specifies optional actions for the waitpid function. Either of the following option flags may be specified, or they can be combined with a bitwise inclusive OR operator:
WNOHANG WUNTRACED WCONTINUED
If successful, waitpid returns the process ID of the terminated process whose status was reported. If unsuccessful, a -1 is returned.
benifits over wait
1.Waitpid can used when you have more than one child for the process and you want to wait for particular child to get its execution done before parent resumes
2.waitpid supports job control
3.it supports non blocking of the parent process
I'd like to add that of the three algoritms mentioned so far (mergesort, quicksort and heap sort) only mergesort is stable. That is, the order does not change for those values which have the same key. In some cases this is desirable.
But, truth be told, in practical situations most people need only good average performance and quicksort is... quick =)
All sort algorithms have their ups and downs. See Wikipedia article for sorting algorithms for a good overview.
According to facebooks best practices it is like this (2016)
Use images that are at least 1200 x 630 pixels for the best display on high resolution devices. At the minimum, you should use images that are 600 x 315 pixels to display link page posts with larger images. Images can be up to 8MB in size.
If your image is smaller than 600 x 315 px, it will still display in the link page post, but the size will be much smaller.
We've also redesigned link page posts so that the aspect ratio for images is the same across desktop and mobile News Feed. Try to keep your images as close to 1.91:1 aspect ratio as possible to display the full image in News Feed without any cropping.
The minimum image size is 200 x 200 pixels. If you try to use an image smaller than this you will see an error in the Sharing Debugger.
There are two different image sizes to use for game apps:
Open Graph Stories Images appear in a square format. Image ratios for these apps should be 600 x 600 px. Non-open Graph Stories Images appear in a rectangular format. You should use a 1.91:1 image ratio, such as 600 x 314 px.
How about something like this ...
var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };
var g = l1.GroupBy( i => i );
foreach( var grp in g )
{
Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
}
Edit per comment: I will try and do this justice. :)
In my example, it's a Func<int, TKey>
because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an IGrouping<int,int>
(a grouping of ints keyed by an int). If I changed it to (i => i.ToString()
) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ...
private string SampleMethod( int i )
{
// magically return "One" if i == 1, "Two" if i == 2, etc.
}
So, that's a Func that would take an int and return a string, just like ...
i => // magically return "One" if i == 1, "Two" if i == 2, etc.
But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.
I hope this will help you
public void countInPara(String str) {
Map<Integer,String> strMap = new HashMap<Integer,String>();
List<String> paraWords = Arrays.asList(str.split(" "));
Set<String> strSet = new LinkedHashSet<>(paraWords);
int count;
for(String word : strSet) {
count = Collections.frequency(paraWords, word);
strMap.put(count, strMap.get(count)==null ? word : strMap.get(count).concat(","+word));
}
for(Map.Entry<Integer,String> entry : strMap.entrySet())
System.out.println(entry.getKey() +" :: "+ entry.getValue());
}
According to Java Persistence with Hibernate
mapping collections of value types with annotations [...]. At the time of writing it isn't part of the Java Persistence standard
If you were using Hibernate, you could do something like:
@org.hibernate.annotations.CollectionOfElements(
targetElement = java.lang.String.class
)
@JoinTable(
name = "foo",
joinColumns = @JoinColumn(name = "foo_id")
)
@org.hibernate.annotations.IndexColumn(
name = "POSITION", base = 1
)
@Column(name = "baz", nullable = false)
private List<String> arguments = new ArrayList<String>();
Update: Note, this is now available in JPA2.
lets setup the same dictionary in each of the following and test the execution time.
The setup argument is basically setting up the dictionary
Number is to run the code 1000000 times. Not the setup but the stmt
When you run this you can see that index is way faster than get. You can run it multiple times to see.
The code basically tries to get the value of c in the dictionary.
import timeit
print('Getting value of C by index:', timeit.timeit(stmt="mydict['c']", setup="mydict={'a':5, 'b':6, 'c':7}", number=1000000))
print('Getting value of C by get:', timeit.timeit(stmt="mydict.get('c')", setup="mydict={'a':5, 'b':6, 'c':7}", number=1000000))
Here are my results, yours will differ.
by index: 0.20900007452246427
by get: 0.54841166886888
You can use Money and Currency API (JSR 354). You can use this API in, provided you add appropriate dependencies to your project.
For Java 8, add the following reference implementation as a dependency to your pom.xml
:
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>1.0</version>
</dependency>
This dependency will transitively add javax.money:money-api
as a dependency.
You can then use the API:
package com.example.money;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;
import java.util.Locale;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.MonetaryRounding;
import javax.money.format.MonetaryAmountFormat;
import javax.money.format.MonetaryFormats;
import org.junit.Test;
public class MoneyTest {
@Test
public void testMoneyApi() {
MonetaryAmount eurAmount1 = Monetary.getDefaultAmountFactory().setNumber(1.1111).setCurrency("EUR").create();
MonetaryAmount eurAmount2 = Monetary.getDefaultAmountFactory().setNumber(1.1141).setCurrency("EUR").create();
MonetaryAmount eurAmount3 = eurAmount1.add(eurAmount2);
assertThat(eurAmount3.toString(), is("EUR 2.2252"));
MonetaryRounding defaultRounding = Monetary.getDefaultRounding();
MonetaryAmount eurAmount4 = eurAmount3.with(defaultRounding);
assertThat(eurAmount4.toString(), is("EUR 2.23"));
MonetaryAmountFormat germanFormat = MonetaryFormats.getAmountFormat(Locale.GERMAN);
assertThat(germanFormat.format(eurAmount4), is("EUR 2,23") );
}
}
If you used maxLength = 6
, some times what you are entering those characters are added in top of the keyboard called suggestions. So when you deleting entered letters that time it will delete suggestions first and then actual text inside EditText
. For that you need to remove the suggestions.just add
android:inputType="textNoSuggestions"`
or
android:inputType="textFilter"
It will remove those suggestions.
If you still care a lot about support and performance in IE<10, it's best to ALWAYS make your script tags the last tags of your HTML body. That way, you're certain that the rest of the DOM has been loaded and you won't block and rendering.
If you don't care too much anymore about IE<10, you might want to put your scripts in the head of your document and use defer
to ensure they only run after your DOM has been loaded (<script type="text/javascript" src="path/to/script1.js" defer></script>
). If you still want your code to work in IE<10, don't forget to wrap your code in a window.onload
even, though!
You could just use the bound ng-model
(answers[item.questID]
) value itself in your ng-change method to detect if it has been checked or not.
Example:-
<input type="checkbox" ng-model="answers[item.questID]"
ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->
and
$scope.stateChanged = function (qId) {
if($scope.answers[qId]){ //If it is checked
alert('test');
}
}
You can introduce the lineterminator='\n' parameter in the csv writer command.
import csv
delimiter='\t'
with open('tmp.csv', '+w', encoding='utf-8') as stream:
writer = csv.writer(stream, delimiter=delimiter, quoting=csv.QUOTE_NONE, quotechar='', lineterminator='\n')
writer.writerow(['A1' , 'B1', 'C1'])
writer.writerow(['A2' , 'B2', 'C2'])
writer.writerow(['A3' , 'B3', 'C3'])
Just right click in your project go Manage NuGet Packages search for Microsoft.AspNet.WebApi.Client install it and you will have access to the extension method.
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');
Alternatively, to change all characters except numbers and letters, try:
string = string.replace(/[^a-zA-Z0-9]/g,'_');
mysql> CREATE USER 'name'@'%' IDENTIFIED BY 'passWord'; Query OK, 0 rows affected (0.00 sec)
mysql> GRANT ALL PRIVILEGES ON . TO 'name'@'%'; Query OK, 0 rows affected (0.00 sec)
mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec)
mysql>
hope this helps someone...
UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '[Replacement]')
In your instance it would be
UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '')
Because there is no replacement (you want to get rid of it).
This will run on every row of the specified table. No need for a WHERE clause unless you want to specify only certain rows.
Safari 7.0.5 still does not support notification for validation of input fields.
To overcome it is possible to write fallback script like this: http://codepen.io/ashblue/pen/KyvmA
To see what HTML5 / CSS3 features are supported by browsers check: http://caniuse.com/form-validation
function hasHtml5Validation () {
//Check if validation supported && not safari
return (typeof document.createElement('input').checkValidity === 'function') &&
!(navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0);
}
$('form').submit(function(){
if(!hasHtml5Validation())
{
var isValid = true;
var $inputs = $(this).find('[required]');
$inputs.each(function(){
var $input = $(this);
$input.removeClass('invalid');
if(!$.trim($input.val()).length)
{
isValid = false;
$input.addClass('invalid');
}
});
if(!isValid)
{
return false;
}
}
});
SASS / LESS:
input, select, textarea {
@include appearance(none);
border-radius: 0px;
&.invalid {
border-color: red !important;
}
}
You are missing at least one of the phpMyAdmin configuration storage tables, or the configured table name does not match the actual table name.
See http://docs.phpmyadmin.net/en/latest/setup.html#phpmyadmin-configuration-storage.
A quick summary of what to do can be:
locate create_tables.sql
./usr/share/doc/phpmyadmin/examples/create_tables.sql.gz
using phpMyAdmin./etc/phpmyadmin/config.inc.php
and edit lines 81-92: change pma_bookmark
to pma__bookmark
and so on.In Java, 2D arrays are really arrays of arrays with possibly different lengths (there are no guarantees that in 2D arrays that the 2nd dimension arrays all be the same length)
You can get the length of any 2nd dimension array as z[n].length
where 0 <= n < z.length
.
If you're treating your 2D array as a matrix, you can simply get z.length
and z[0].length
, but note that you might be making an assumption that for each array in the 2nd dimension that the length is the same (for some programs this might be a reasonable assumption).
This answer is late, but I'm posting anyway hoping it will help someone. Like you, I also had difficulty submitting a form that was outside my bootstrap modal, and I didn't want to use ajax because I wanted a whole new page to load, not just part of the current page. After much trial and error here's the jQuery that worked for me:
$(function () {
$('body').on('click', '.odom-submit', function (e) {
$(this.form).submit();
$('#myModal').modal('hide');
});
});
To make this work I did this in the modal footer
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary odom-submit">Save changes</button>
</div>
Notice the addition to class of odom-submit. You can, of course, name it whatever suits your particular situation.
Heres a tidy solution in TypeScript:
import { Readable } from 'stream'
class ReadableString extends Readable {
private sent = false
constructor(
private str: string
) {
super();
}
_read() {
if (!this.sent) {
this.push(Buffer.from(this.str));
this.sent = true
}
else {
this.push(null)
}
}
}
const stringStream = new ReadableString('string to be streamed...')
If you wish to use the try/catch mechanism to handle this problem.. then it can be used to act like if/else. I used the try/catch to add a new record when I didn't find an existing one.
try { //if part
record = query.getSingleResult();
//use the record from the fetched result.
}
catch(NoResultException e){ //else part
//create a new record.
record = new Record();
//.........
entityManager.persist(record);
}
There's a C implementation here:
http://www.cs.rit.edu/~ncs/color/t_convert.html
Should be very straightforward to convert to C#, as almost no functions are called - just calculations.
found via Google
There are some references and pointers in the comments on this page at PHP.net:
Torsten says
"Section C.8 of the XHTML spec's compatability guidelines apply to the use of the name attribute as a fragment identifier. If you check the DTD you'll find that the 'name' attribute is still defined as CDATA for form elements."
Jetboy says
"according to this: http://www.w3.org/TR/xhtml1/#C_8 the type of the name attribute has been changed in XHTML 1.0, meaning that square brackets in XHTML's name attribute are not valid.
Regardless, at the time of writing, the W3C's validator doesn't pick this up on a XHTML document."
I know this is old, but I recently faced the same issue and I managed to pick the element by accessing only the attribute like this: document.querySelector('[name="your-selector-name-here"]');
Just in case anyone would ever need this :)
First Import the package as :
import org.openqa.selenium.support.ui.Select;
then write in single line as:
new Select (driver.findElement(By.id("sampleid"))).selectByValue("SampleValue");
Do it in two steps.
rm -r bar/
cp -r foo/ bar/
There are two problems in your code:
visibility
and not visiblity
..style
property.It's easy to fix. Simple replace this:
document.getElementById("remember").visiblity
with this:
document.getElementById("remember").style.visibility
it is because you already defined the 'abuse_id' as auto increment, then there is no need to insert its value. it will be inserted automatically. the error comes because you are inserting 1 many times that is duplication of data. the primary key should be unique. should not be repeated.
the thing you have to do is to change your insertion query as below
INSERT INTO `abuses` ( `user_id` , `abuser_username` , `comment` , `reg_date` , `auction_id` )
VALUES ( 100020, 'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;
If you want to make a diff against current branch you can ommit it and use:
git diff $BRANCH -- path/to/file
this way it will diff from current branch to the referenced branch ($BRANCH
).
Some of the tutorials I found that are easy to understand are:
It makes way more sense to break up your list into page-sized chunks, and only query your database one chunk at a time. This drastically reduces server processing time and page load time, as well as gives your user smaller pieces of info to digest, so he doesn't choke on whatever crap you're trying to feed him. The act of doing this is called pagination.
A basic pagination routine seems long and scary at first, but once you close your eyes, take a deep breath, and look at each piece of the script individually, you will find it's actually pretty easy stuff
The script:
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM numbers";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
// number of rows to show per page
$rowsperpage = 10;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql = "SELECT id, number FROM numbers LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
// echo data
echo $list['id'] . " : " . $list['number'] . "<br />";
} // end while
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?>
This tutorial is intended for developers who wish to give their users the ability to step through a large number of database rows in manageable chunks instead of the whole lot in one go.
Try this, it works for me:
var storage = null;
setLocalStorage();
function setLocalStorage() {
storage = (localStorage ? localStorage : (window.content.localStorage ? window.content.localStorage : null));
try {
storage.setItem('test_key', 'test_value');//verify if posible saving in the current storage
}
catch (e) {
if (e.name == "NS_ERROR_FILE_CORRUPTED") {
storage = sessionStorage ? sessionStorage : null;//set the new storage if fails
}
}
}
Note that the TIMEDIFF()
solution only works when the datetimes
are less than 35 days apart!
TIMEDIFF()
returns a TIME
datatype, and the max value for TIME is 838:59:59 hours (=34,96 days)
From here I see the method setCompoundDrawablesWithIntrinsicBounds(int,int,int,int) can be used to do this.
You need to make the extension as .php to run a php code BUT if you can't change the extension you could use Ajax to run the php externally and get the result
For eg:
<html>
<head>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url:'php_File_with_php_code.php',
type:'GET',
data:"parameter=some_parameter",
success:function(data)
{
$("#thisdiv").html(data);
}
});
});
</script>
</head>
<body>
<div id="thisdiv"></div>
</body>
</html>
Here, the JQuery is loaded and as soon as the pages load, the ajax call a php file from where the data is taken, the data is then put in the div
Hope This Helps
I would have said:
select s.stname, s2.subname, highmarks.mark
from students s
join marks m on s.stid = m.stid
join Subject s2 on m.subid = s2.subid
join (select subid, max(mark) as mark
from marks group by subid) as highmarks
on highmarks.subid = m.subid and highmarks.mark = m.mark
order by subname, stname;
SQLFiddle here: http://sqlfiddle.com/#!2/5ef84/3
This is a:
Only the students that get maximum marks will meet all three join conditions. This lists all students who got that maximum mark, so if there are ties, both get listed.
Here is my solution
private static final int NOTIFICATION_ID = 200;
private static final String CHANNEL_ID = "myChannel";
private static final String CHANNEL_NAME = "myChannelName";
private void startForeground() {
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
getApplicationContext(), CHANNEL_ID);
Notification notification;
notification = mBuilder.setTicker(getString(R.string.app_name)).setWhen(0)
.setOngoing(true)
.setContentTitle(getString(R.string.app_name))
.setContentText("Send SMS gateway is running background")
.setSmallIcon(R.mipmap.ic_launcher)
.setShowWhen(true)
.build();
NotificationManager notificationManager = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE);
//All notifications should go through NotificationChannel on Android 26 & above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(NOTIFICATION_ID, notification);
}
Hope it will help :)
It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.
Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.
DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj
...
The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.
var DyObjectsList = new List<dynamic>;
if (condition1) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = true;
DyObj.Message = "Message 1";
DyObjectsList .Add(DyObj);
}
if (condition2) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = false;
DyObj.Message = "Message 2";
DyObjectsList .Add(DyObj);
}
your resulting List essentially looks like this
DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj
Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.
However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.
You may also do the following in Python 3.6.1
from Object import Object as Parent
and your class definition to:
class Visitor(Parent):
<?php
$first = reset($arr_nav); // Get the first element
$last = end($arr_nav); // Get the last element
// Ensure that we have a first element and that it's an array
if(is_array($first)) {
$first['class'] = 'first';
}
// Ensure we have a last element and that it differs from the first
if(is_array($last) && $last !== $first) {
$last['class'] = 'last';
}
Now you could just echo the class inside you html-generator. Would probably need some kind of check to ensure that the class is set, or provide a default empty class to the array.
In Net Beans GUI - go to jframe (right click on jFrame in Navigator) properties, under code, form size policy property select Generate Resize Code. In the same window, Untick Generate Position and tick Generate Size and Center.
Enjoy programming. Ramana
You can achieve this using the apache commons java library. Take a look at these two functions within it:
- getLevenshteinDistance
- getFuzzyDistance
The move_uploaded_file
will return false if the file was not successfully moved you can put something into your code to alert you in a log if that happens, that should help you figure out why your having trouble renaming the file
Project Files Services Tabls
go files tabs
drag drop file to libs files hover.
return project tabs and what are you see :)
You may do as follows. one line of code will be enough
let array = $('ul>li').toArray().map(item => $(item).html());
Get the interested element
get children
get the array from toArray() method
filter out the results you want
let array = $('ul>li').toArray().map(item => $(item).html());_x000D_
console.log(array);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul>_x000D_
<li>text1</li>_x000D_
<li>text2</li>_x000D_
<li>text3</li>_x000D_
</ul>
_x000D_
if application is hosted on IIS, make sure Static Content is installed. Control Panel > Programs > Turn Windows features on or off > Internet Information Services > World Wide Web Services > Common HTTP Features > Static Content.
I faced this problem when trying to run an existing application on a new IIS 10.0 installation
Here is the simple code snippet to upload a single file with additional parameters using requests:
url = 'https://<file_upload_url>'
fp = '/Users/jainik/Desktop/data.csv'
files = {'file': open(fp, 'rb')}
payload = {'file_id': '1234'}
response = requests.put(url, files=files, data=payload, verify=False)
Please note that you don't need to explicitly specify any content type.
NOTE: Wanted to comment on one of the above answers but could not because of low reputation so drafted a new response here.
GMTDate = new Date().toGMTString();
This is how you can nest multiple bool queries in one outer bool query this using Kibana,
GET my_inedx/my_type/_search
{
"query" : {
"bool": { //bool indicates we are using boolean operator
"must" : [ //must is for **AND**
{
"match" : {
"description" : "some text"
}
},
{
"match" :{
"type" : "some Type"
}
},
{
"bool" : { //here its a nested boolean query
"should" : [ //should is for **OR**
{
"match" : {
//ur query
}
},
{
"match" : {}
}
]
}
}
]
}
}
}
This is how you can nest a query in ES
There are more types in "bool" like,
Try this:
If [ $a -lt 4 ] || [ $a -gt 64 ] ; then \n
Something something \n
elif [ $a -gt 4 ] || [ $a -lt 64 ] ; then \n
Something something \n
else \n
Yes it works for me :) \n
Great question. This is really something missing from the Javascript browser API. I'm also working on a WebGL game with my team, and we need this feature. I opened an issue on Firefox's bugzilla so that we can start talking about the possibility of having an API to allow for mouse locking. This is going to be useful for all HTML5/WebGL game developers out there.
If you like, come over and leave a comment with your feedback, and upvote the issue:
https://bugzilla.mozilla.org/show_bug.cgi?id=630979
Thanks!
for people new to this you can also use a callback for example:
In your service:
.factory('DataHandler',function ($http){
var GetRandomArtists = function(data, callback){
$http.post(URL, data).success(function (response) {
callback(response);
});
}
})
In your controller:
DataHandler.GetRandomArtists(3, function(response){
$scope.data.random_artists = response;
});
My users are allowed to upload CSV files and text/csv
and application/csv
did not appear by now. These are the ones identified through finfo():
text/plain
text/x-csv
And these are the ones transmitted through the browser:
text/plain
application/vnd.ms-excel
text/x-csv
The following types did not appear, but could:
application/csv
application/x-csv
text/csv
text/comma-separated-values
text/x-comma-separated-values
text/tab-separated-values
To be honest I think that it's really shame that there is no simple checkbox in storyboard to say that you want to resize buttons to accommodate the text. Well... whatever.
Here is the simplest solution using storyboard.
Place UILabel inside UIView. Set constraints to attach it to edges of UIView.
Place your UIButton inside UIView. Set the same constraints to attach it to the edges of UIView.
Set up the outlets.
@IBOutlet var button: UIButton!
@IBOutlet var textOnTheButton: UILabel!
let someTitle = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
override func viewDidLoad() {
super.viewDidLoad()
textOnTheButton.text = someTitle
button.setTitle(someTitle, for: .normal)
button.titleLabel?.numberOfLines = 0
}
NOTE: HSSFDateUtil is deprecated
If you know which cell i.e. column position say 0 in each row is going to be a date, you can go for
row.getCell(0).getDateCellValue()
directly.
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFCell.html#getDateCellValue()
UPDATE: Here is an example - you can apply this in your switch case code above. I am checking and printing the Numeric as well as Date value. In this case the first column in my sheet has dates, hence I use row.getCell(0).
You can use the if (HSSFDateUtil.isCellDateFormatted ..
code block directly in your switch case.
if (row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
System.out.println ("Row No.: " + row.getRowNum ()+ " " +
row.getCell(0).getNumericCellValue());
if (HSSFDateUtil.isCellDateFormatted(row.getCell(0))) {
System.out.println ("Row No.: " + row.getRowNum ()+ " " +
row.getCell(0).getDateCellValue());
}
}
The output is
Row No.: 0 39281.0
Row No.: 0 Wed Jul 18 00:00:00 IST 2007
Row No.: 1 39491.0
Row No.: 1 Wed Feb 13 00:00:00 IST 2008
Row No.: 2 39311.0
Row No.: 2 Fri Aug 17 00:00:00 IST 2007
if kwarg.__len__() != 0:
print(kwarg)
I don't think it provides a multi-hop wireless packet routing environment. However you can try to integrate a simple routing mechanism. Just check out Wi-Share to get an idea how it can be done.
When i need to copy data from filtered table i use range.SpecialCells(xlCellTypeVisible).copy. Where the range is range of all data (without a filter).
Example:
Sub copy()
'source worksheet
dim ws as Worksheet
set ws = Application.Worksheets("Data")' set you source worksheet here
dim data_end_row_number as Integer
data_end_row_number = ws.Range("B3").End(XlDown).Row.Number
'enable filter
ws.Range("B2:F2").AutoFilter Field:=2, Criteria1:="hockey", VisibleDropDown:=True
ws.Range("B3:F" & data_end_row_number).SpecialCells(xlCellTypeVisible).Copy
Application.Worksheets("Hoky").Range("B3").Paste
'You have to add headers to Hoky worksheet
end sub
cd /usr/local
git status
git status
til it's cleanbrew update
You don't need CSS for this.
<img src="abc"/>
now with link:
<a href="#myLink"><img src="abc"/></a>
Or with jquery, later on, you can use the wrap property, see these questions answer:
Go to Eclipse folder, locate eclipse.ini file, add following entry (before -vmargs
if present):
-vm
C:\Program Files\Java\jdk1.7.0_10\bin\javaw.exe
Save file and execute eclipse.exe.
I saw something in the new C# 6.0, this is by using '?' instead of checking
for example instead of using
if (Person != null && Person.Contact!=null && Person.Contact.Address!= null && Person.Contact.Address.City != null)
{
var city = person.contact.address.city;
}
you simply use
var city = person?.contact?.address?.city;
I hope it helped somebody.
UPDATE:
You could do like this now
var city = (Person != null)?
((Person.Contact!=null)?
((Person.Contact.Address!= null)?
((Person.Contact.Address.City!=null)?
Person.Contact.Address.City : null )
:null)
:null)
: null;
@Before
(JUnit4) -> @BeforeEach
(JUnit5) - method is called before every test
@After
(JUnit4) -> @AfterEach
(JUnit5) - method is called after every test
@BeforeClass
(JUnit4) -> @BeforeAll
(JUnit5) - static method is called before executing all tests in this class. It can be a large task as starting server, read file, making db connection...
@AfterClass
(JUnit4) -> @AfterAll
(JUnit5) - static method is called after executing all tests in this class.
Cast works where the actual instance of the list is an ArrayList
. If it is, say, a Vector
(which is another extension of List
) it will throw a ClassCastException.
The error when changing the definition of your HashMap is due to the elements later being processed, and that process expects a method that is defined only in ArrayList
. The exception tells you that it did not found the method it was looking for.
Create a new ArrayList
with the contents of the old one.
new ArrayList<String>(myList);
var postdata = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};
var data = [];
data.push(postdata);
console.log(data);
UPDATE: Plunkr added
I was looking for a solution on all forums but found none, so found a solution with Old School Javascript Callback function.
This is a really simple and clean way to create a confirmation dialog and set Callback functions for both YES and NO click events.
I have used Bootstrap CSS for Modal and An Alert Service with rxjs Subject.
alert.component.html
<div *ngIf="message.type == 'confirm'" class="modal-body">
<div class="row">
<div class="col-md-12">
<h3 class="text-center">{{message.text}}</h3>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="text-center">
<a (click)="message.noFn()">
<button class="btn btn-pm">No</button>
</a>
<a (click)="message.siFn()">
<button class="btn btn-sc" >Yes</button>
</a>
</p>
</div>
</div>
</div>
alert.component.ts
export class AlertComponent {
message: any;
constructor(
public router: Router,
private route: ActivatedRoute,
private alertService: AlertService,
) { }
ngOnInit() {
//this function waits for a message from alert service, it gets
//triggered when we call this from any other component
this.alertService.getMessage().subscribe(message => {
this.message = message;
});
}
The most important part is here alert.service.ts
import { Injectable } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
@Injectable() export class AlertService {
private subject = new Subject<any>();
constructor(){}
confirm(message: string,siFn:()=>void,noFn:()=>void){
this.setConfirmation(message,siFn,noFn);
}
setConfirmation(message: string,siFn:()=>void,noFn:()=>void) {
let that = this;
this.subject.next({ type: "confirm",
text: message,
siFn:
function(){
that.subject.next(); //this will close the modal
siFn();
},
noFn:function(){
that.subject.next();
noFn();
}
});
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
Call the function from any component
this.alertService.confirm("You sure Bro?",function(){
//ACTION: Do this If user says YES
},function(){
//ACTION: Do this if user says NO
})
db.find({ pictures: { $elemMatch: { $exists: true } } })
$elemMatch
matches documents that contain an array field with at least one element that matches the specified query.
So you're matching all arrays with at least an element.
One way to do it will be to move all the php code above the HTML, copy the result to a variable and then add the result in the <input>
tag.
Try this -
<?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
...
//Adding to $result variable
if($sign=='-') {
$result = $value1-$value2;
}
//Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">
This is a favorite Java interview question.
Thread t1 = new Thread(new EventThread("e1"));
t1.start();
Thread e2 = new Thread(new EventThread("e2"));
t2.start();
while (true) {
try {
t1.join(); // 1
t2.join(); // 2 These lines (1,2) are in in public static void main
break;
}
}
t1.join()
means, t1 says something like "I want to finish first". Same is the case with t2
. No matter who started t1
or t2
thread (in this case the main
method), main will wait until t1
and t2
finish their task.
However, an important point to note down, t1
and t2
themselves can run in parallel irrespective of the join call sequence on t1
and t2
. It is the main/daemon
thread that has to wait.
serialize it with System.Web.Script.Serialization.JavaScriptSerializer
class and assign to javascript var
dummy sample:
<% var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); %>
var jsVariable = <%= serializer.Serialize(array) %>;
this can solve the problem:
private List<SomeClass> clearListFromDuplicateFirstName(List<SomeClass> list1) {
Map<String, SomeClass> cleanMap = new LinkedHashMap<String, SomeClass>();
for (int i = 0; i < list1.size(); i++) {
cleanMap.put(list1.get(i).getFirstName(), list1.get(i));
}
List<SomeClass> list = new ArrayList<SomeClass>(cleanMap.values());
return list;
}
Hint: To convert an NSArray containing JSON compatible objects to an NSData object containing a JSON document, use the appropriate method of NSJSONSerialization. JSONObjectWithData is not it.
Hint 2: You rarely want that data as a string; only for debugging purposes.
I decided to write a class from this thread that may be helpful to others. Note that this is currently intended to write in the "files" directory only (e.g. does not write to "sdcard" paths).
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.content.Context;
public class AndroidFileFunctions {
public static String getFileValue(String fileName, Context context) {
try {
StringBuffer outStringBuf = new StringBuffer();
String inputLine = "";
/*
* We have to use the openFileInput()-method the ActivityContext
* provides. Again for security reasons with openFileInput(...)
*/
FileInputStream fIn = context.openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader inBuff = new BufferedReader(isr);
while ((inputLine = inBuff.readLine()) != null) {
outStringBuf.append(inputLine);
outStringBuf.append("\n");
}
inBuff.close();
return outStringBuf.toString();
} catch (IOException e) {
return null;
}
}
public static boolean appendFileValue(String fileName, String value,
Context context) {
return writeToFile(fileName, value, context, Context.MODE_APPEND);
}
public static boolean setFileValue(String fileName, String value,
Context context) {
return writeToFile(fileName, value, context,
Context.MODE_WORLD_READABLE);
}
public static boolean writeToFile(String fileName, String value,
Context context, int writeOrAppendMode) {
// just make sure it's one of the modes we support
if (writeOrAppendMode != Context.MODE_WORLD_READABLE
&& writeOrAppendMode != Context.MODE_WORLD_WRITEABLE
&& writeOrAppendMode != Context.MODE_APPEND) {
return false;
}
try {
/*
* We have to use the openFileOutput()-method the ActivityContext
* provides, to protect your file from others and This is done for
* security-reasons. We chose MODE_WORLD_READABLE, because we have
* nothing to hide in our file
*/
FileOutputStream fOut = context.openFileOutput(fileName,
writeOrAppendMode);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(value);
// save and close
osw.flush();
osw.close();
} catch (IOException e) {
return false;
}
return true;
}
public static void deleteFile(String fileName, Context context) {
context.deleteFile(fileName);
}
}
Was surprised to not see around
method mentioned - means no messing with print options.
import numpy as np
x = np.random.random([5,5])
print(np.around(x,decimals=3))
Output:
[[0.475 0.239 0.183 0.991 0.171]
[0.231 0.188 0.235 0.335 0.049]
[0.87 0.212 0.219 0.9 0.3 ]
[0.628 0.791 0.409 0.5 0.319]
[0.614 0.84 0.812 0.4 0.307]]
You can't. It's a browser feature there to prevent sites from showing hundreds of alerts to prevent you from leaving.
You can, however, look into modal popups like jQuery UI Dialog. These are javascript alert boxes that show a custom dialog. They don't use the default alert()
function and therefore, bypass the issue you're running into completely.
I've found that an apps that has a lot of message boxes and confirms has a much better user experience if you use custom dialogs instead of the default alerts and confirms.
StartsWith
a) left(@edition, 15) = 'Express Edition'
b) charindex('Express Edition', @edition) = 1
Contains
charindex('Express Edition', @edition) >= 1
Examples
left
function
set @isExpress = case when left(@edition, 15) = 'Express Edition' then 1 else 0 end
iif
function (starting with SQL Server 2012)
set @isExpress = iif(left(@edition, 15) = 'Express Edition', 1, 0);
charindex
function
set @isExpress = iif(charindex('Express Edition', @edition) = 1, 1, 0);
You need add parameter errors='coerce'
to function to_numeric
:
ID = pd.to_numeric(ID, errors='coerce')
If ID
is column:
df.ID = pd.to_numeric(df.ID, errors='coerce')
but non numeric are converted to NaN
, so all values are float
.
For int
need convert NaN
to some value e.g. 0
and then cast to int
:
df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
Sample:
df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
ID
0 4806105017087
1 4806105017087
2 CN414149
print (pd.to_numeric(df.ID, errors='coerce'))
0 4.806105e+12
1 4.806105e+12
2 NaN
Name: ID, dtype: float64
df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
ID
0 4806105017087
1 4806105017087
2 0
EDIT: If use pandas 0.25+ then is possible use integer_na
:
df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
ID
0 4806105017087
1 4806105017087
2 NaN
Angular 7 Service:
this.http.post(environment.urlRest + '/my-operation',body, { headers: headers, observe: 'response'});Component:
this.myService.myfunction().subscribe( (res: HttpResponse) => { console.log(res.headers.get('x-token')); } , error =>{ })
If you load you table file with dtype=str
or convert column type to string df['a'] = df['a'].astype(str)
then you can use such approach:
df['a']= 'col' + df['a'].str[:]
This approach allows prepend, append, and subset string of df
.
Works on Pandas v0.23.4, v0.24.1. Don't know about earlier versions.
See http://wiki.apache.org/httpd/DistrosDefaultLayout for discussion of where you might find Apache httpd configuration files on various platforms, since this can vary from release to release and platform to platform. The most common answer, however, is either /etc/apache/conf or /etc/httpd/conf
Generically, you can determine the answer by running the command:
httpd -V
(That's a capital V). Or, on systems where httpd is renamed, perhaps apache2ctl -V
This will return various details about how httpd is built and configured, including the default location of the main configuration file.
One of the lines of output should look like:
-D SERVER_CONFIG_FILE="conf/httpd.conf"
which, combined with the line:
-D HTTPD_ROOT="/etc/httpd"
will give you a full path to the default location of the configuration file
Just a note that using process.exit([number])
is not recommended practice.
Calling
process.exit()
will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations toprocess.stdout
andprocess.stderr
.In most situations, it is not actually necessary to call
process.exit()
explicitly. The Node.js process will exit on its own if there is no additional work pending in the event loop. Theprocess.exitCode
property can be set to tell the process which exit code to use when the process exits gracefully.For instance, the following example illustrates a misuse of the
process.exit()
method that could lead to data printed tostdout
being truncated and lost:// This is an example of what *not* to do: if (someConditionNotMet()) { printUsageToStdout(); process.exit(1); }
The reason this is problematic is because writes to
process.stdout
in Node.js are sometimes asynchronous and may occur over multiple ticks of the Node.js event loop. Callingprocess.exit()
, however, forces the process to exit before those additional writes tostdout
can be performed.Rather than calling
process.exit()
directly, the code should set theprocess.exitCode
and allow the process to exit naturally by avoiding scheduling any additional work for the event loop:// How to properly set the exit code while letting // the process exit gracefully. if (someConditionNotMet()) { printUsageToStdout(); process.exitCode = 1; }
String path = Server.MapPath("~/MP_Upload/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Of course. The whole idea of abstract classes is that they can contain some behaviour or data which you require all sub-classes to contain. Think of the simple example of WheeledVehicle - it should have a numWheels member variable. You want all sub classes to have this variable. Remember that abstract classes are a very useful feature when developing APIs, as they can ensure that people who extend your API won't break it.
I got the solution by using comm
comm -23 file1 file2
will give you the desired output.
The files need to be sorted first anyway.
long int n;
scanf("%ld", &n);
printf("%ld", n);
long long int n;
scanf("%lld", &n);
printf("%lld", n);
Hope you've cleared..
I know its a very old post but thought of sharing few more details on Parse vs TryParse.
I had a scenario where DateTime needs to be converted to String and if datevalue null or string.empty we were facing an exception. In order to overcome this, we have replaced Parse with TryParse and will get default date.
Old Code:
dTest[i].StartDate = DateTime.Parse(StartDate).ToString("MM/dd/yyyy");
dTest[i].EndDate = DateTime.Parse(EndDate).ToString("MM/dd/yyyy");
New Code:
DateTime startDate = default(DateTime);
DateTime endDate=default(DateTime);
DateTime.TryParse(dPolicyPaidHistories[i].StartDate, out startDate);
DateTime.TryParse(dPolicyPaidHistories[i].EndDate, out endDate);
Have to declare another variable and used as Out for TryParse.
str.replaceAll("\\^([0-9]+)", "<sup>$1</sup>");
Long count = (Long) session.createQuery("select count(*) from Book").uniqueResult();
Some people don't like this, and it's more of a .NET convention than Java, but you can name your interfaces with a capital I prefix, for example:
IProductRepository - interface
ProductRepository, SqlProductRepository, etc. - implementations
The people opposed to this naming convention might argue that you shouldn't care whether you're working with an interface or an object in your code, but I find it easier to read and understand on-the-fly.
I wouldn't name the implementation class with a "Class" suffix. That may lead to confusion, because you can actually work with "class" (i.e. Type) objects in your code, but in your case, you're not working with the class object, you're just working with a plain-old object.
It will work.
long yourmilliseconds = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));
1.Go to "/Users/****/.gradle/wrapper/dists/gradle-.-all/*****".
2.Delete the "gradle-.-all.zip.lck" file.
3.Invalidate Cache and Restart.
Why do you want to generate all the sql by hand? Have you looked at an ORM like Hibernate Depending on your project it will probably do at least 95% of what you need, do it in a cleaner way then raw SQL, and if you need to get the last bit of performance you can create the SQL queries that need to be hand tuned.
According to Hanselman - Using Directive and Assembly Loading... and other such articles there is technically no difference.
My preference is to put them outside of namespaces.
When you compare those two arrays, you're comparing the objects that represent the arrays, not the contents.
You'll have to use a function to compare the two. You could write your own that simply loops though one and compares it to the other after you check that the lengths are the same.
Since printArea is a jQuery plugin it is not included in jquery.d.ts.
You need to create a jquery.printArea.ts definition file.
If you create a complete definition file for the plugin you may want to submit it to DefinitelyTyped.
Try this :
$obj = @{
SomeProp = "Hello"
}
Write-Host "Property Value is $($obj."SomeProp")"
I have tomcat 8 Update 25 and tomcat 7 but facing the same issue it shows the message Server Tomcat v7.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.
Bootstrap is the world’s most popular and widely used open-source framework for developing with HTML, CSS, and JS. It is a front end framework of HTML. Bootstrap helps in building responsive websites or web applications and a 12-column grid system that helps dynamically adjust the website to a suitable screen resolution. The current version of bootstrap is 4.3.1 and the bootstrap team has also officially announced Bootstrap 5 version and changes like removing jquery from bootstrap. Some of the crucial reasons why bootstrap framework is most preferable are
It is easy to use
Bootstrap has a big community support
Customizations can be done easily
It increases development speed
Responsiveness
For more details, you can check the official website: https://getbootstrap.com/
You can use the Below codes for shifting not rotating:
int []arr = {1,2,3,4,5,6,7,8,9,10,11,12};
int n = arr.length;
int d = 3;
Programm for shifting array of size n
by d
elements towards left:
Input : {1,2,3,4,5,6,7,8,9,10,11,12}
Output: {4,5,6,7,8,9,10,11,12,10,11,12}
public void shiftLeft(int []arr,int d,int n) {
for(int i=0;i<n-d;i++) {
arr[i] = arr[i+d];
}
}
Programm for shifting array of size n
by d
elements towards right:
Input : {1,2,3,4,5,6,7,8,9,10,11,12}
Output: {1,2,3,1,2,3,4,5,6,7,8,9}
public void shiftRight(int []arr,int d,int n) {
for(int i=n-1;i>=d;i--) {
arr[i] = arr[i-d];
}
}
If you want to generate a random float in a range, try a next solution.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float
random_float(const float min, const float max)
{
if (max == min) return min;
else if (min < max) return (max - min) * ((float)rand() / RAND_MAX) + min;
// return 0 if min > max
return 0;
}
int
main (const int argc, const char *argv[])
{
srand(time(NULL));
char line[] = "-------------------------------------------";
float data[10][2] = {
{-10, 10},
{-5., 5},
{-1, 1},
{-0.25, -0.15},
{1.5, 1.52},
{-1700, 8000},
{-0.1, 0.1},
{-1, 0},
{-1, -2},
{1.2, 1.1}
};
puts(line);
puts(" From | Result | To");
puts(line);
int i;
for (i = 0; i < 10; ++i) {
printf("%12f | %12f | %12f\n", data[i][0], random_float(data[i][0], data[i][1]), data[i][1]);
}
puts(line);
return 0;
}
A result (values is fickle)
-------------------------------------------
From | Result | To
-------------------------------------------
-10.000000 | 2.330828 | 10.000000
-5.000000 | -4.945523 | 5.000000
-1.000000 | 0.004242 | 1.000000
-0.250000 | -0.203197 | -0.150000
1.500000 | 1.513431 | 1.520000
-1700.000000 | 3292.941895 | 8000.000000
-0.100000 | -0.021541 | 0.100000
-1.000000 | -0.148299 | 0.000000
-1.000000 | 0.000000 | -2.000000
1.200000 | 0.000000 | 1.100000
-------------------------------------------
Agreed completely that this is a path issue but fwiw, I had this same error. It was due to the mistake of using a relative path for my Python executable when setting up my virtual environment. I had done this:
virtualenv -p ~/python_runtimes/2.7.3/bin/python venv2.7.3 --distribute
Instead I had to give the full path to the Python executable.
HTH, Harlin
Assigning a class name and applying a CSS style are two different things.
If you mean <img class="someclass">
, and
.someclass {
[cssrule]
}
, then there is no real performance difference between applying the css to the class, or to .column img
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com/SpecificAction.php");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com/SpecificAction.php";
FYI, sender
and e
are not specific to ASP.NET or to C#. See Events (C# Programming Guide) and Events in Visual Basic.
The utf8mb4
character set is useful because nowadays we need support for storing not only language characters but also symbols, newly introduced emojis, and so on.
A nice read on How to support full Unicode in MySQL databases by Mathias Bynens can also shed some light on this.
printf("format", args) is used to print the data onto the standard output which is often a computer monitor.
sprintf(char *, "format", args) is like printf. Instead of displaying the formated string on the standard output i.e. a monitor, it stores the formated data in a string pointed to by the char pointer (the very first parameter). The string location is the only difference between printf and sprint syntax.
fprintf(FILE *fp, "format", args) is like printf again. Here, instead of displaying the data on the monitor, or saving it in some string, the formatted data is saved on a file which is pointed to by the file pointer which is used as the first parameter to fprintf. The file pointer is the only addition to the syntax of printf.
If stdout file is used as the first parameter in fprintf, its working is then considered equivalent to that of printf.
In short:
someValues.forEach((element) => {
console.log(element);
});
If you care about index, then second parameter can be passed to receive the index of current element:
someValues.forEach((element, index) => {
console.log(`Current index: ${index}`);
console.log(element);
});
Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful
library(dplyr)
iris %>%
mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))
LIBS += C:\Program Files\OpenCV\lib
won't work because you're using white-spaces in Program Files. In this case you have to add quotes, so the result will look like this: LIBS += "C:\Program Files\OpenCV\lib". I recommend placing libraries in non white-space locations ;-)
I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).
Solution is: First Update ADT to 22.0.4 and then Update SDK Tool to 22.0.4
The above link says,
ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so
What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).
How to Update your ADT to Latest Version
In Eclipse go to Help
Install New Software
---> Add
inside Add Repository write the Name: ADT
(or whatever you want)
Location: https://dl-ssl.google.com/android/eclipse/
after loading you should get Developer Tools and NDK Plugins
check both if you want to use the Native Developer Kit (NDK) in the future or check
Developer Tool only
click Next
Finish
As of Firefox 12 they now support line breaks using the line feed HTML entity:
<span title="First line Second line">Test</span>
This works in IE and is the correct according to the HTML5 spec for the title attribute.
I found this method on http://www.mrexcel.com/
This computes the number of non-blank cells in column A of worksheet named "Data"
With Worksheets("Data")
Ndt =Application.Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
debug.print Ndt
End With
The result is printed to the immediate window. You need to subtract 1 (or more) if column A has a header line (or lines) you do not wish to count.
From my (albeit limited) exposure to Jest, I have found that expect().toThrow()
is suitable if you want to only test an error is thrown of a specific type:
expect(() => functionUnderTest()).toThrow(TypeError);
Or an error is thrown with a specific message:
expect(() => functionUnderTest()).toThrow('Something bad happened!');
If you try to do both, you will get a false positive. For example, if your code throws RangeError('Something bad happened!')
, this test will pass:
expect(() => functionUnderTest()).toThrow(new TypeError('Something bad happened!'));
The answer by bodolsog which suggests using a try/catch is close, but rather than expecting true to be false to ensure the expect assertions in the catch are hit, you can instead use expect.assertions(2)
at the start of your test where 2
is the number of expected assertions. I feel this more accurately describes the intention of the test.
A full example of testing the type and message of an error:
describe('functionUnderTest', () => {
it('should throw a specific type of error.', () => {
expect.assertions(2);
try {
functionUnderTest();
} catch (error) {
expect(error).toBeInstanceOf(TypeError);
expect(error).toHaveProperty('message', 'Something bad happened!');
}
});
});
If functionUnderTest()
does not throw an error, the assertions will be be hit, but the expect.assertions(2)
will fail and the test will fail.
It's pretty much the same as in Objective-C
let del = UIApplication.sharedApplication().delegate
Not sure if this is the best way, but you could always do this:
Foo.instance_methods.include? 'bar'
A probably convenient way to enter multi-line strings is by using macro's. This only works if quotes and parentheses are balanced and it does not contain 'top level' comma's:
#define MULTI_LINE_STRING(a) #a
const char *text = MULTI_LINE_STRING(
Using this trick(,) you don't need to use quotes.
Though newlines and multiple white spaces
will be replaced by a single whitespace.
);
printf("[[%s]]\n",text);
Compiled with gcc 4.6 or g++ 4.6, this produces: [[Using this trick(,) you don't need to use quotes. Though newlines and multiple white spaces will be replaced by a single whitespace.]]
Note that the ,
cannot be in the string, unless it is contained within parenthesis or quotes. Single quotes is possible, but creates compiler warnings.
Edit: As mentioned in the comments, #define MULTI_LINE_STRING(...) #__VA_ARGS__
allows the use of ,
.
If you attempting to do this on a server on different domain you will need to a little bit more than what has been suggested by most answers so far, this is what I use to accomplish this:
#Configuration
$servername = "ABC",
$serviceAccountUsername = "XYZ",
$serviceAccountPassword = "XXX"
#Establish connection
try {
if (-not ([System.IO.Directory]::Exists('\\' + $servername))) {
net use \\$servername /user:$serviceAccountUsername $serviceAccountPassword
}
}
catch {
#May already exists, if so just continue
Write-Output $_.Exception.Message
}
#Restart Service
sc.exe \\$servername stop "ServiceNameHere"
sc.exe \\$servername start "ServiceNameHere"
Another common technique is to place the function name in the first column. This allows the definition to be found with a simple search.
int
main(int argc, char *argv[])
{
...
}
The above function could then be found with /^main
inside the file or with :grep -r '^main' *.c
in a directory. As long as code is properly indented the only time the identifier will occur at the beginning of a line is at the function definition.
Of course, if you aren't using ctags from this point on you should be ashamed of yourself! However, I find this coding standard a helpful addition as well.
Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.
SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean,
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)
Try using the os
module.
import os
os.environ['DEBUSSY'] = '1'
os.environ['FSDB'] = '1'
# Open child processes via os.system(), popen() or fork() and execv()
someVariable = int(os.environ['DEBUSSY'])
See the Python docs on os.environ
. Also, for spawning child processes, see Python's subprocess docs.
Yes. In fact you should. If you're wondering if it creates a segmentation fault, it doesn't.
The simplest solution which worked for me (Windows 10, Jupyter Notebook) for this problem is to do the following:
import sys sys.path.append('C:/Users/usrname/AppData/Local/Continuum/anaconda3/Library/bin/graphviz/')
Are you ssh'ing to a directory that's inside your work tree? If the root of your ssh mount point doesn't include the .git dir, then zsh won't be able to find git info. Make sure you're mounting something that includes the root of the repo.
As for GIT_DISCOVERY_ACROSS_FILESYSTEM, it doesn't do what you want. Git by default will stop at a filesystem boundary. If you turn that on (and it's just an env var), then git will cross the filesystem boundary and keep looking. However, that's almost never useful, because you'd be implying that you have a .git directory on your local machine that's somehow meant to manage a work tree that's comprised partially of an sshfs mount. That doesn't make much sense.
If you don't have a company, leave your name, it doesn't matter as long as both bundle id in info.plist file and the one you've submitted in iTunes Connect match.
In Bundle ID Suffix you should write full name of bundle ID.
Example:
Bundle ID suffix = thebestapp (NOT CORRECT!!!!)
Bundle ID suffix = com.awesomeapps.thebestapp (CORRECT!!)
The reason for this is explained in the Developer Portal:
The App ID string contains two parts separated by a period (.) — an App ID Prefix (your Team ID by default, e.g.
ABCDE12345
), and an App ID Suffix (a Bundle ID search string, e.g.com.mycompany.appname
). [emphasis added]
So in this case the suffix is the full string com.awesomeapps.thebestapp
.
The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):
Mikhail,
The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.
Good luck with your implementation.
Try this code.
For showing Softkeyboard:
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
}
For Hiding SoftKeyboard -
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
Am I missing the point here, or is it just the following:
string = "ab1cd1ef"
string = string.replace("1","")
print string
# result: "abcdef"
Put it in a loop:
a = "a!b@c#d$"
b = "!@#$"
for char in b:
a = a.replace(char,"")
print a
# result: "abcd"
"react-router-dom": "^5.0.0",
you do not need to add any additional module, just in your component that has a url address like this:
http://localhost:3000/#/?authority'
you can try the following simple code:
const search =this.props.location.search;
const params = new URLSearchParams(search);
const authority = params.get('authority'); //
I've got this exact error, but in my case I was binding values for the LIMIT
clause without specifying the type. I'm just dropping this here in case somebody gets this error for the same reason. Without specifying the type LIMIT :limit OFFSET :offset;
resulted in LIMIT '10' OFFSET '1';
instead of LIMIT 10 OFFSET 1;
. What helps to correct that is the following:
$stmt->bindParam(':limit', intval($limit, 10), \PDO::PARAM_INT);
$stmt->bindParam(':offset', intval($offset, 10), \PDO::PARAM_INT);
As said earlier "Representing money as a double or float will probably look good at first as the software rounds off the tiny errors, but as you perform more additions, subtractions, multiplications and divisions on inexact numbers, you’ll lose more and more precision as the errors add up. This makes floats and doubles inadequate for dealing with money, where perfect accuracy for multiples of base 10 powers is required."
Finally Java has a standard way to work with Currency And Money!
JSR 354: Money and Currency API
JSR 354 provides an API for representing, transporting, and performing comprehensive calculations with Money and Currency. You can download it from this link:
JSR 354: Money and Currency API Download
The specification consists of the following things:
- An API for handling e. g. monetary amounts and currencies
- APIs to support interchangeable implementations
- Factories for creating instances of the implementation classes
- Functionality for calculations, conversion and formatting of monetary amounts
- Java API for working with Money and Currencies, which is planned to be included in Java 9.
- All specification classes and interfaces are located in the javax.money.* package.
Sample Examples of JSR 354: Money and Currency API:
An example of creating a MonetaryAmount and printing it to the console looks like this:
MonetaryAmountFactory<?> amountFactory = Monetary.getDefaultAmountFactory();
MonetaryAmount monetaryAmount = amountFactory.setCurrency(Monetary.getCurrency("EUR")).setNumber(12345.67).create();
MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(Locale.getDefault());
System.out.println(format.format(monetaryAmount));
When using the reference implementation API, the necessary code is much simpler:
MonetaryAmount monetaryAmount = Money.of(12345.67, "EUR");
MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(Locale.getDefault());
System.out.println(format.format(monetaryAmount));
The API also supports calculations with MonetaryAmounts:
MonetaryAmount monetaryAmount = Money.of(12345.67, "EUR");
MonetaryAmount otherMonetaryAmount = monetaryAmount.divide(2).add(Money.of(5, "EUR"));
CurrencyUnit and MonetaryAmount
// getting CurrencyUnits by locale
CurrencyUnit yen = MonetaryCurrencies.getCurrency(Locale.JAPAN);
CurrencyUnit canadianDollar = MonetaryCurrencies.getCurrency(Locale.CANADA);
MonetaryAmount has various methods that allow accessing the assigned currency, the numeric amount, its precision and more:
MonetaryAmount monetaryAmount = Money.of(123.45, euro);
CurrencyUnit currency = monetaryAmount.getCurrency();
NumberValue numberValue = monetaryAmount.getNumber();
int intValue = numberValue.intValue(); // 123
double doubleValue = numberValue.doubleValue(); // 123.45
long fractionDenominator = numberValue.getAmountFractionDenominator(); // 100
long fractionNumerator = numberValue.getAmountFractionNumerator(); // 45
int precision = numberValue.getPrecision(); // 5
// NumberValue extends java.lang.Number.
// So we assign numberValue to a variable of type Number
Number number = numberValue;
MonetaryAmounts can be rounded using a rounding operator:
CurrencyUnit usd = MonetaryCurrencies.getCurrency("USD");
MonetaryAmount dollars = Money.of(12.34567, usd);
MonetaryOperator roundingOperator = MonetaryRoundings.getRounding(usd);
MonetaryAmount roundedDollars = dollars.with(roundingOperator); // USD 12.35
When working with collections of MonetaryAmounts, some nice utility methods for filtering, sorting and grouping are available.
List<MonetaryAmount> amounts = new ArrayList<>();
amounts.add(Money.of(2, "EUR"));
amounts.add(Money.of(42, "USD"));
amounts.add(Money.of(7, "USD"));
amounts.add(Money.of(13.37, "JPY"));
amounts.add(Money.of(18, "USD"));
Custom MonetaryAmount operations
// A monetary operator that returns 10% of the input MonetaryAmount
// Implemented using Java 8 Lambdas
MonetaryOperator tenPercentOperator = (MonetaryAmount amount) -> {
BigDecimal baseAmount = amount.getNumber().numberValue(BigDecimal.class);
BigDecimal tenPercent = baseAmount.multiply(new BigDecimal("0.1"));
return Money.of(tenPercent, amount.getCurrency());
};
MonetaryAmount dollars = Money.of(12.34567, "USD");
// apply tenPercentOperator to MonetaryAmount
MonetaryAmount tenPercentDollars = dollars.with(tenPercentOperator); // USD 1.234567
Resources:
Handling money and currencies in Java with JSR 354
Looking into the Java 9 Money and Currency API (JSR 354)
See Also: JSR 354 - Currency and Money
Using $('[data-whatever="myvalue"]')
will select anything with html attributes, but in newer jQueries it seems that if you use $(...).data(...)
to attach data, it uses some magic browser thingy and does not affect the html, therefore is not discovered by .find
as indicated in the previous answer.
Verify (tested with 1.7.2+) (also see fiddle): (updated to be more complete)
var $container = $('<div><div id="item1"/><div id="item2"/></div>');
// add html attribute
var $item1 = $('#item1').attr('data-generated', true);
// add as data
var $item2 = $('#item2').data('generated', true);
// create item, add data attribute via jquery
var $item3 = $('<div />', {id: 'item3', data: { generated: 'true' }, text: 'Item 3' });
$container.append($item3);
// create item, "manually" add data attribute
var $item4 = $('<div id="item4" data-generated="true">Item 4</div>');
$container.append($item4);
// only returns $item1 and $item4
var $result = $container.find('[data-generated="true"]');
update:
I found the terms of use from Google Map:
Section 10.5
No caching or storage. You will not pre-fetch, cache, index, or store any Content to be used outside the Service, except that you may store limited amounts of Content solely for the purpose of improving the performance of your Maps API Implementation due to network latency (and not for the purpose of preventing Google from accurately tracking usage), and only if such storage: is temporary (and in no event more than 30 calendar days); is secure; does not manipulate or aggregate any part of the Content or Service; and does not modify attribution in any way.
It means we can cache for limited time actually
Might be a late response but here is a way to do it in one line without using any libraries:
new SimpleDateFormat("yyyy-MM-dd").parse(new SimpleDateFormat("yyyy-MM-dd").format(YOUR_TIMESTAMP))
I published one here: FullParam SQL Blog
/* Reto Egeter, fullparam.wordpress.com */
DECLARE @SearchStrTableName nvarchar(255), @SearchStrColumnName nvarchar(255), @SearchStrColumnValue nvarchar(255), @SearchStrInXML bit, @FullRowResult bit, @FullRowResultRows int
SET @SearchStrColumnValue = '%searchthis%' /* use LIKE syntax */
SET @FullRowResult = 1
SET @FullRowResultRows = 3
SET @SearchStrTableName = NULL /* NULL for all tables, uses LIKE syntax */
SET @SearchStrColumnName = NULL /* NULL for all columns, uses LIKE syntax */
SET @SearchStrInXML = 0 /* Searching XML data may be slow */
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (TableName nvarchar(128), ColumnName nvarchar(128), ColumnValue nvarchar(max),ColumnType nvarchar(20))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256) = '',@ColumnName nvarchar(128),@ColumnType nvarchar(20), @QuotedSearchStrColumnValue nvarchar(110), @QuotedSearchStrColumnName nvarchar(110)
SET @QuotedSearchStrColumnValue = QUOTENAME(@SearchStrColumnValue,'''')
DECLARE @ColumnNameTable TABLE (COLUMN_NAME nvarchar(128),DATA_TYPE nvarchar(20))
WHILE @TableName IS NOT NULL
BEGIN
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME LIKE COALESCE(@SearchStrTableName,TABLE_NAME)
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
)
IF @TableName IS NOT NULL
BEGIN
DECLARE @sql VARCHAR(MAX)
SET @sql = 'SELECT QUOTENAME(COLUMN_NAME),DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(''' + @TableName + ''', 2)
AND TABLE_NAME = PARSENAME(''' + @TableName + ''', 1)
AND DATA_TYPE IN (' + CASE WHEN ISNUMERIC(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@SearchStrColumnValue,'%',''),'_',''),'[',''),']',''),'-','')) = 1 THEN '''tinyint'',''int'',''smallint'',''bigint'',''numeric'',''decimal'',''smallmoney'',''money'',' ELSE '' END + '''char'',''varchar'',''nchar'',''nvarchar'',''timestamp'',''uniqueidentifier''' + CASE @SearchStrInXML WHEN 1 THEN ',''xml''' ELSE '' END + ')
AND COLUMN_NAME LIKE COALESCE(' + CASE WHEN @SearchStrColumnName IS NULL THEN 'NULL' ELSE '''' + @SearchStrColumnName + '''' END + ',COLUMN_NAME)'
INSERT INTO @ColumnNameTable
EXEC (@sql)
WHILE EXISTS (SELECT TOP 1 COLUMN_NAME FROM @ColumnNameTable)
BEGIN
PRINT @ColumnName
SELECT TOP 1 @ColumnName = COLUMN_NAME,@ColumnType = DATA_TYPE FROM @ColumnNameTable
SET @sql = 'SELECT ''' + @TableName + ''',''' + @ColumnName + ''',' + CASE @ColumnType WHEN 'xml' THEN 'LEFT(CAST(' + @ColumnName + ' AS nvarchar(MAX)), 4096),'''
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + '),'''
ELSE 'LEFT(' + @ColumnName + ', 4096),''' END + @ColumnType + '''
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
INSERT INTO #Results
EXEC(@sql)
IF @@ROWCOUNT > 0 IF @FullRowResult = 1
BEGIN
SET @sql = 'SELECT TOP ' + CAST(@FullRowResultRows AS VARCHAR(3)) + ' ''' + @TableName + ''' AS [TableFound],''' + @ColumnName + ''' AS [ColumnFound],''FullRow>'' AS [FullRow>],*' +
' FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
EXEC(@sql)
END
DELETE FROM @ColumnNameTable WHERE COLUMN_NAME = @ColumnName
END
END
END
SET NOCOUNT OFF
SELECT TableName, ColumnName, ColumnValue, ColumnType, COUNT(*) AS Count FROM #Results
GROUP BY TableName, ColumnName, ColumnValue, ColumnType
I am amazed at how complex this question has become.
These are all identical, and their integer values all === EPOCH time :D
console.log((new Date()).getTime() / 1000, new Date().valueOf() / 1000, (new Date() - new Date().getTimezoneOffset() * 60 * 1000) / 1000);
Do not believe me, checkout: http://www.epochconverter.com/
var results = from p in persons
group p by p.PersonID into g
select new { PersonID = g.Key,
/**/car = g.Select(g=>g.car).FirstOrDefault()/**/}
ES6 (template literal) helper functions:
function rgba(r, g, b, a=1){
return `rgba(${r}, ${g}, ${b}, ${a})`
}
function rgb(r, g, b){
return `rgb(${r}, ${g}, ${b})`
}
You have to verify than the size allocated while doing HAX installation is the same than the size in the AVD emulator configuration.
You can see in French here : http://blerow.blogspot.fr/2015/01/android-studio.html
You can't - globally, i.e. for every python program. And this is a good thing - Python is great for scripting (automating stuff), and scripts should be able to run without any user interaction at all.
However, you can always ask for input at the end of your program, effectively keeping the program alive until you press return. Use input("prompt: ")
in Python 3 (or raw_input("promt: ")
in Python 2). Or get used to running your programs from the command line (i.e. python mine.py
), the program will exit but its output remains visible.
What ever data you have inserted into one text file or log file that can put on one path in hdfs and then write a query as follows in hive
hive>load data inpath<<specify inputpath>> into table <<tablename>>;
EXAMPLE:
hive>create table foo (id int, name string)
row format delimited
fields terminated by '\t' or '|'or ','
stored as text file;
table created..
DATA INSERTION::
hive>load data inpath '/home/hive/foodata.log' into table foo;
While this question is rather old, and has been answered, I thought I'd take the time to offer a couple of options that are, as yet, not addressed in other answers.
Given the corrected HTML (camelCasing the id
attribute-value) of:
<label year="2010" month="6" id="currentMonth"> June 2010</label>
You could use regular expressions to extract the month-name, and year:
// gets the eleent with an id equal to 'currentMonth',
// retrieves its text-content,
// uses String.prototype.trim() to remove leading and trailing white-space:
var labelText = $('#currentMonth').text().trim(),
// finds the sequence of one, or more, letters (a-z, inclusive)
// at the start (^) of the string, and retrieves the first match from
// the array returned by the match() method:
month = labelText.match(/^[a-z]+/i)[0],
// finds the sequence of numbers (\d) of length 2-4 ({2,4}) characters,
// at the end ($) of the string:
year = labelText.match(/\d{2,4}$/)[0];
var labelText = $('#currentMonth').text().trim(),_x000D_
month = labelText.match(/^[a-z]+/i)[0],_x000D_
year = labelText.match(/\d{2,4}$/)[0];_x000D_
_x000D_
console.log(month, year);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label year="2010" month="6" id="currentMonth"> June 2010</label>
_x000D_
Rather than regular expressions, though, you could instead use custom data-*
attributes (which work in HTML 4.x, despite being invalid under the doctype, but are valid under HTML 5):
var label = $('#currentMonth'),_x000D_
month = label.data('month'),_x000D_
year = label.data('year');_x000D_
_x000D_
console.log(month, year);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label data-year="2010" data-month="6" id="currentMonth"> June 2010</label>
_x000D_
Note that this will output 6
(for the data-month
), rather than 'June'
as in the previous example, though if you use an array to tie numbers to month-names, that can be solved easily:
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],_x000D_
label = $('#currentMonth'),_x000D_
month = monthNames[+label.data('month') - 1],_x000D_
year = label.data('year');_x000D_
_x000D_
console.log(month, year);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label data-year="2010" data-month="6" id="currentMonth"> June 2010</label>
_x000D_
Similarly, the above could be easily transcribed to the native DOM (in compliant browsers):
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],_x000D_
label = document.getElementById('currentMonth'),_x000D_
month = monthNames[+label.dataset.month - 1],_x000D_
year = label.dataset.year;_x000D_
_x000D_
console.log(month, year);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label data-year="2010" data-month="6" id="currentMonth"> June 2010</label>
_x000D_
References:
I made a lexer/tokenizer before with the use of only standard libraries. Here's the code:
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
string seps(string& s) {
if (!s.size()) return "";
stringstream ss;
ss << s[0];
for (int i = 1; i < s.size(); i++) {
ss << '|' << s[i];
}
return ss.str();
}
void Tokenize(string& str, vector<string>& tokens, const string& delimiters = " ")
{
seps(str);
// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
}
int main(int argc, char *argv[])
{
vector<string> t;
string s = "Tokens for everyone!";
Tokenize(s, t, "|");
for (auto c : t)
cout << c << endl;
system("pause");
return 0;
}
ERROR 2005 (HY000): Unknown MySQL server host 'localhost' (0)
modify list of host names for your system:
C:\Windows\System32\drivers\etc\hosts
Make sure that you have the following entry:
127.0.0.1 localhost
In my case that entry was 0.0.0.0 localhost which caussed all problem
(you may need to change modify permission to modify this file)
This performs DNS resolution of host “localhost” to the IP address 127.0.0.1.
Instructions as of Dec 2018:
Now when you open the shortcut it will open in a window without toolbar.
CAST to a float or decimal instead of an int/bigint.
The integer portion (before the decimal point) represents the number of whole days. After the decimal are the fractional days (i.e., time).
ARM
is a RISC (Reduced Instruction Set Computing) architecture while x86
is a CISC (Complex Instruction Set Computing) one.
The core difference between those in this aspect is that ARM instructions operate only on registers with a few instructions for loading and saving data from / to memory while x86 can operate directly on memory as well. Up until v8 ARM was a native 32 bit architecture, favoring four byte operations over others.
So ARM is a simpler architecture, leading to small silicon area and lots of power save features while x86 becoming a power beast in terms of both power consumption and production.
About question on "Is the x86 Architecture specially designed to work with a keyboard while ARM expects to be mobile?". x86
isn't specially designed to work with a keyboard neither ARM
for mobile. However again because of the core architectural choices actually x86 also has instructions to work directly with IO
while ARM has not. However with specialized IO buses like USBs, need for such features are also disappearing.
If you need a document to quote, this is what Cortex-A Series Programmers Guide (4.0) tells about differences between RISC and CISC architectures:
An ARM processor is a Reduced Instruction Set Computer (RISC) processor.
Complex Instruction Set Computer (CISC) processors, like the x86, have a rich instruction set capable of doing complex things with a single instruction. Such processors often have significant amounts of internal logic that decode machine instructions to sequences of internal operations (microcode).
RISC architectures, in contrast, have a smaller number of more general purpose instructions, that might be executed with significantly fewer transistors, making the silicon cheaper and more power efficient. Like other RISC architectures, ARM cores have a large number of general-purpose registers and many instructions execute in a single cycle. It has simple addressing modes, where all load/store addresses can be determined from register contents and instruction fields.
ARM company also provides a paper titled Architectures, Processors, and Devices Development Article describing how those terms apply to their bussiness.
An example comparing instruction set architecture:
For example if you would need some sort of bytewise memory comparison block in your application (generated by compiler, skipping details), this is how it might look like on x86
repe cmpsb /* repeat while equal compare string bytewise */
while on ARM
shortest form might look like (without error checking etc.)
top:
ldrb r2, [r0, #1]! /* load a byte from address in r0 into r2, increment r0 after */
ldrb r3, [r1, #1]! /* load a byte from address in r1 into r3, increment r1 after */
subs r2, r3, r2 /* subtract r2 from r3 and put result into r2 */
beq top /* branch(/jump) if result is zero */
which should give you a hint on how RISC and CISC instruction sets differ in complexity.
Here is something I learnt after a long time of having issues with pip when I had several versions of Python installed (valid especially for OS X users which are probably using brew to install python blends.)
I assume that most python developers do have at the beginning of their scripts:
#!/bin/env python
You may be surprised to find out that this is not necessarily the same python as the one you run from the command line >python
To be sure you install the package using the correct pip instance for your python interpreter you need to run something like:
>/bin/env python -m pip install --upgrade mymodule
Add the following text to your xml file.
<!--Dummy layout that gain focus -->
<LinearLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical" >
</LinearLayout>
There is an Open GAPPS button in the top right corner of the genymotion. Click on it you can directly install Gapps from genymotion.
wrap a <span>
around those words and style with the appropriate color
now is the time for <span style='color:orange'>all good men</span> to come to the
If you want to change the user at git Bash .You just need to configure particular user and email(globally) at the git bash.
$ git config --global user.name "abhi"
$ git config --global user.email "[email protected]"
Note: No need to delete the user from Keychain .
How about either of:
>>> df
date duration user_id
0 2013-04-01 30 0001
1 2013-04-01 15 0001
2 2013-04-01 20 0002
3 2013-04-02 15 0002
4 2013-04-02 30 0002
>>> df.groupby("date").agg({"duration": np.sum, "user_id": pd.Series.nunique})
duration user_id
date
2013-04-01 65 2
2013-04-02 45 1
>>> df.groupby("date").agg({"duration": np.sum, "user_id": lambda x: x.nunique()})
duration user_id
date
2013-04-01 65 2
2013-04-02 45 1
You can get where you are through
new File(".").getAbsolutePath()
then you can derive path to src/test/resources
usually it is just
new File("src/test/resources")
brbcoding have been able to help me with the appropriate coding i needed, here is it
HTML
<input type="checkbox" id="checkme"/>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Javascript
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
Simple solution for HTML5 ready browsers...
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
}
else {
pom.click();
}
}
Usage
download('test.txt', 'Hello world!');
There are four ways to do this as I know
const array = [{id:1,name:'Jim'},{id:2,name:'Parker'}];
const toDelete = 1;
The first:
_.reject(array, {id:toDelete})
The second one is :
_.remove(array, {id:toDelete})
In this way the array will be mutated.
The third one is :
_.differenceBy(array,[{id:toDelete}],'id')
// If you can get remove item
// _.differenceWith(array,[removeItem])
The last one is:
_.filter(array,({id})=>id!==toDelete)
I am learning lodash
Answer to make a record, so that I can find it later.
You can use String.split
with a limit of 2.
String s = "Hello World, I'm the rest.";
String[] result = s.split(" ", 2);
String first = result[0];
String rest = result[1];
System.out.println("First: " + first);
System.out.println("Rest: " + rest);
// prints =>
// First: Hello
// Rest: World, I'm the rest.
split
Create a file called "SetFile.bat" that contains the following line with no carriage return at the end of it...
set FileContents=
Then in your batch file do something like this...
@echo off
copy SetFile.bat + %1 $tmp$.bat > nul
call $tmp$.bat
del $tmp$.bat
%1 is the name of your input file and %FileContents% will contain the contents of the input file after the call. This will only work on a one line file though (i.e. a file containing no carriage returns). You could strip out/replace carriage returns from the file before calling the %tmp%.bat if needed.
Should work fine.
$data = array('name' => 'Ross', 'php_master' => true);
// You can POST a file by prefixing with an @ (for <input type="file"> fields)
$data['file'] = '@/home/user/world.jpg';
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_exec($handle);
curl_close($handle)
We have two options here, CURLOPT_POST
which turns HTTP POST on, and CURLOPT_POSTFIELDS
which contains an array of our post data to submit. This can be used to submit data to POST
<form>
s.
It is important to note that curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
takes the $data in two formats, and that this determines how the post data will be encoded.
$data
as an array()
: The data will be sent as multipart/form-data
which is not always accepted by the server.
$data = array('name' => 'Ross', 'php_master' => true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
$data
as url encoded string: The data will be sent as application/x-www-form-urlencoded
, which is the default encoding for submitted html form data.
$data = array('name' => 'Ross', 'php_master' => true);
curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));
I hope this will help others save their time.
See:
If you want something more similar to your example try _itot_s. On Microsoft compilers _itot_s points to _itoa_s or _itow_s depending on your Unicode setting:
CString str;
_itot_s( 15, str.GetBufferSetLength( 40 ), 40, 10 );
str.ReleaseBuffer();
it should be slightly faster since it doesn't need to parse an input format.
I tried a lot to get the shortest code to get the weeknumber ISO-conform.
Date.prototype.getWeek=function(){
var date=new Date(this);
date.setHours(0,0,0,0);
return Math.round(((date.setDate(this.getDate()+2-(this.getDay()||7))-date.setMonth(0,4))/8.64e7+3+(date.getDay()||7))/7)+"/"+date.getFullYear();}
The variable date
is necessary to avoid to alter the original this
. I used the return values of setDate()
and setMonth()
to dispense with getTime()
to save code length and I used an expontial number for milliseconds of a day instead of a multiplication of single elements or a number with five zeros. this
is Date or Number of milliseconds, return value is String
e.g. "49/2017".
The problem with all these solutions is that the height of the iframe
never really changes.
This means you won't be able to center elements inside the iframe
using Javascript, position:fixed;
, or position:absolute;
since the iframe
itself never scrolls.
My solution detailed here is to wrap all the content of the iframe inside a div
using this CSS:
#wrap {
position: fixed;
top: 0;
right:0;
bottom:0;
left: 0;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
}
This way Safari believes the content has no height and lets you assign the height of the iframe
properly. This also allows you to position elements in any way you wish.