I think this will work even though this was forever ago.
SELECT employee_number, Row_Number()
OVER (PARTITION BY course_code ORDER BY course_completion_date DESC ) as rownum
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
AND rownum = 1
If you want to get the last Id if the date is the same then you can use this assuming your primary key is Id.
SELECT employee_number, Row_Number()
OVER (PARTITION BY course_code ORDER BY course_completion_date DESC, Id Desc) as rownum FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
AND rownum = 1
select partition_name,column_name,high_value,partition_position
from ALL_TAB_PARTITIONS a , ALL_PART_KEY_COLUMNS b
where table_name='YOUR_TABLE' and a.table_name = b.name;
This query lists the column name used as key and the allowed values. make sure, you insert the allowed values(high_value
). Else, if default partition is defined, it would go there.
EDIT:
I presume, your TABLE DDL would be like this.
CREATE TABLE HE0_DT_INF_INTERFAZ_MES
(
COD_PAIS NUMBER,
FEC_DATA NUMBER,
INTERFAZ VARCHAR2(100)
)
partition BY RANGE(COD_PAIS, FEC_DATA)
(
PARTITION PDIA_98_20091023 VALUES LESS THAN (98,20091024)
);
Which means I had created a partition with multiple columns which holds value less than the composite range (98,20091024);
That is first COD_PAIS <= 98
and Also FEC_DATA < 20091024
Combinations And Result:
98, 20091024 FAIL
98, 20091023 PASS
99, ******** FAIL
97, ******** PASS
< 98, ******** PASS
So the below INSERT
fails with ORA-14400; because (98,20091024)
in INSERT
is EQUAL to the one in DDL
but NOT less than it.
SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
VALUES(98, 20091024, 'CTA'); 2
INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
*
ERROR at line 1:
ORA-14400: inserted partition key does not map to any partition
But, we I attempt (97,20091024), it goes through
SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
2 VALUES(97, 20091024, 'CTA');
1 row created.
You need to define a Theme for your AlertDialog and reference it in your Activity's theme. The attribute is alertDialogTheme
and not alertDialogStyle
. Like this:
<style name="Theme.YourTheme" parent="@android:style/Theme.Holo">
...
<item name="android:alertDialogTheme">@style/YourAlertDialogTheme</item>
</style>
<style name="YourAlertDialogTheme">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:windowMinWidthMajor">@android:dimen/dialog_min_width_major</item>
<item name="android:windowMinWidthMinor">@android:dimen/dialog_min_width_minor</item>
<item name="android:windowTitleStyle">...</item>
<item name="android:textAppearanceMedium">...</item>
<item name="android:borderlessButtonStyle">...</item>
<item name="android:buttonBarStyle">...</item>
</style>
You'll be able to change color and text appearance for the title, the message and you'll have some control on the background of each area. I wrote a blog post detailing the steps to style an AlertDialog.
agree to most answers except that in jupyter_notebook_config.py
, you have to put
#c.NotebookApp.notebook_dir='c:\\test\\your_root'
double \\
is the key answer
If you want to do this in RegexBuddy, there are two ways to get a list of all lines not matching a regex.
On the toolbar on the Test panel, set the test scope to "Line by line". When you do that, an item List All Lines without Matches will appear under the List All button on the same toolbar. (If you don't see the List All button, click the Match button in the main toolbar.)
On the GREP panel, you can turn on the "line-based" and the "invert results" checkboxes to get a list of non-matching lines in the files you're grepping through.
Here's the signature.
public static string ActionLink(this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
object values,
object htmlAttributes)
What you are doing is mixing the values
and the htmlAttributes
together. values
are for URL routing.
You might want to do this.
@Html.ActionLink(Context.User.Identity.Name, "Index", "Account", null,
new { @style="text-transform:capitalize;" });
Try:
SELECT MEMBSHIP_ID
FROM user_payment
WHERE user_id=1
ORDER BY paym_date = (select MAX(paym_date) from user_payment and user_id=1);
Or:
SELECT MEMBSHIP_ID
FROM (
SELECT MEMBSHIP_ID, row_number() over (order by paym_date desc) rn
FROM user_payment
WHERE user_id=1 )
WHERE rn = 1
This is a much easier way to do it within Hive's SQL:
set hive.execution.engine=tez;
set hive.merge.tezfiles=true;
set hive.exec.compress.output=false;
INSERT OVERWRITE DIRECTORY '/tmp/job/'
ROW FORMAT DELIMITED
FIELDS TERMINATED by ','
NULL DEFINED AS ''
STORED AS TEXTFILE
SELECT * from table;
As MadScientist pointed out, you can export individual variables with:
export MY_VAR = foo # Available for all targets
Or export variables for a specific target (target-specific variables):
my-target: export MY_VAR_1 = foo
my-target: export MY_VAR_2 = bar
my-target: export MY_VAR_3 = baz
my-target: dependency_1 dependency_2
echo do something
You can also specify the .EXPORT_ALL_VARIABLES
target to—you guessed it!—EXPORT ALL THE THINGS!!!:
.EXPORT_ALL_VARIABLES:
MY_VAR_1 = foo
MY_VAR_2 = bar
MY_VAR_3 = baz
test:
@echo $$MY_VAR_1 $$MY_VAR_2 $$MY_VAR_3
With bash you may use read
like tis:
#!/usr/bin/env bash
{ IFS= read -rd '' value <config.txt;} 2>/dev/null
printf '%s' "$value"
Notice that:
The last newline is preserved.
The stderr
is silenced to /dev/null
by redirecting the whole commands block, but the return status of the read command is preserved, if one needed to handle read error conditions.
The next()
moves the cursor froward one row from its current position in the resultset
. so its evident that if(rs.next())
means that if the next row is not null
(means if it exist), Go Ahead.
Now w.r.t your problem,
ResultSet rs = stmt.executeQuery(sql); //This is wrong
^
note that executeQuery(String) is used in case you use a sql-query as string.
Whereas when you use a PreparedStatement, use executeQuery() which executes the SQL query in this PreparedStatement
object and returns the ResultSet
object generated by the query.
Solution :
Use : ResultSet rs = stmt.executeQuery();
You'll want to use the GetExtensionName method on the FileSystemObject object.
Set x = CreateObject("scripting.filesystemobject")
WScript.Echo x.GetExtensionName("foo.pdf")
In your example, try using this
For Each objFile in colFiles
If UCase(objFSO.GetExtensionName(objFile.name)) = "PDF" Then
Wscript.Echo objFile.Name
End If
Next
The best way I've seen is to utilize the stalenessOf
ExpectedCondition, to wait for the old page to become stale.
Example:
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement oldHtml = driver.findElement(By.tagName("html"));
wait.until(ExpectedConditions.stalenessOf(oldHtml));
It'll wait for ten seconds for the old HTML tag to become stale, and then throw an exception if it doesn't happen.
Try the maven-exec-plugin. From there:
mvn exec:java -Dexec.mainClass="com.example.Main"
This will run your class in the JVM. You can use -Dexec.args="arg0 arg1"
to pass arguments.
If you're on Windows, apply quotes for
exec.mainClass
andexec.args
:mvn exec:java -D"exec.mainClass"="com.example.Main"
If you're doing this regularly, you can add the parameters into the pom.xml as well:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.example.Main</mainClass>
<arguments>
<argument>foo</argument>
<argument>bar</argument>
</arguments>
</configuration>
</plugin>
I got it
Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"
Basically, I need to set the cell format, instead of setting the date.
I think you want this:
select *
from dbo.table
where DATALENGTH(column_name) = 3
I found on the sqlite documentation (https://www.sqlite.org/lang_datefunc.html) this text:
Compute the date and time given a unix timestamp 1092941466, and compensate for your local timezone.
SELECT datetime(1092941466, 'unixepoch', 'localtime');
That didn't look like it fit my needs, so I tried changing the "datetime" function around a bit, and wound up with this:
select datetime(timestamp, 'localtime')
That seems to work - is that the correct way to convert for your timezone, or is there a better way to do this?
I did it in the following way.
form
element (which is placed inside the modal) anID
.data-dimiss
an ID
.onclick
method when data-dimiss
is being clicked.Use the trigger()
function on the form
element.
I am adding the code example with it.
$(document).ready(function()
{
$('#mod_cls').on('click', function () {
$('#Q_A').trigger("reset");
console.log($('#Q_A'));
})
});
<div class="modal fade " id="myModal2" role="dialog" >
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" ID="mod_cls" data-dismiss="modal">×</button>
<h4 class="modal-title" >Ask a Question</h4>
</div>
<div class="modal-body">
<form role="form" action="" id="Q_A" method="POST">
<div class="form-group">
<label for="Question"></label>
<input type="text" class="form-control" id="question" name="question">
</div>
<div class="form-group">
<label for="sub_name">Subject*</label>
<input type="text" class="form-control" id="sub_name" NAME="sub_name">
</div>
<div class="form-group">
<label for="chapter_name">Chapter*</label>
<input type="text" class="form-control" id="chapter_name" NAME="chapter_name">
</div>
<button type="submit" class="btn btn-default btn-success btn-block"> Post</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button><!--initially the visibility of "upload another note" is hidden ,but it becomes visible as soon as one note is uploaded-->
</div>
</div>
</div>
</div>
Hope this will help others as I was struggling with it since a long time.
compare()
will return false
(well, 0
) if the strings are equal.
So don't take exchanging one for the other lightly.
Use whichever makes the code more readable.
1.
first of all Port 80(or what ever you are using) and 443 must be allow for both TCP and UDP packets. To do this, create 2 inbound rules for TPC and UDP on Windows Firewall for port 80 and 443. (or you can disable your whole firewall for testing but permanent solution if allow inbound rule)
2.
You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf
file.
Change this section from :
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
To :
# onlineoffline tag - don't remove
Order Allow,Deny
Allow from all
if "Allow from all" line not work for your then use "Require all granted" then it will work for you.
In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost
so dont amend the httpd.conf
file at all, leave it as you found it.
Using the menus, edit the httpd-vhosts.conf
file.
It should look like this :
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
Amend it to
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Note:if you are running wamp for other than port 80 then VirtualHost will be like VirtualHost *:86.(86 or port whatever you are using) instead of VirtualHost *:80
3. Dont forget to restart All Services of Wamp or Apache after making this change
The case is like :
mysql connects will localhost when network is not up.
mysql cannot connect when network is up.
You can try the following steps to diagnose and resolve the issue (my guess is that some other service is blocking port on which mysql is hosted):
This should ideally resolve the issue you are facing.
For percent increase and decrease, using 2 different methods:
const a = 541
const b = 394
// Percent increase
console.log(
`Increase (from ${b} to ${a}) => `,
(((a/b)-1) * 100).toFixed(2) + "%",
)
// Percent decrease
console.log(
`Decrease (from ${a} to ${b}) => `,
(((b/a)-1) * 100).toFixed(2) + "%",
)
// Alternatives, using .toLocaleString()
console.log(
`Increase (from ${b} to ${a}) => `,
((a/b)-1).toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'}),
)
console.log(
`Decrease (from ${a} to ${b}) => `,
((b/a)-1).toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'}),
)
_x000D_
std::string
has a constructor for this:
const char *s = "Hello, World!";
std::string str(s);
Note that this construct deep copies the character list at s
and s
should not be nullptr
, or else behavior is undefined.
I found this really nifty open source ECMAScript compliant JS Engine completely written in C called duktape
Duktape is an embeddable Javascript engine, with a focus on portability and compact footprint.
Good luck!
two nested for loops?
for a in x:
print "--------------"
for b in a:
print b
It would help if you gave an example of what you want to do with the lists
There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.
Option Explicit
Public Numbers As Variant, Tens As Variant
Sub SetNums()
Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub
Function WordNum(MyNumber As Double) As String
Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
' This macro was written by Chris Mead - www.MeadInKent.co.uk
If Abs(MyNumber) > 999999999 Then
WordNum = "Value too large"
Exit Function
End If
SetNums
' String representation of amount (excl decimals)
NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
For n = 3 To 1 Step -1 'analyse the absolute number as 3 sets of 3 digits
StrNo = Format(ValNo(n), "000")
If ValNo(n) > 0 Then
Temp1 = GetTens(Val(Right(StrNo, 2)))
If Left(StrNo, 1) <> "0" Then
Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
If Temp1 <> "" Then Temp2 = Temp2 & " and "
Else
Temp2 = ""
End If
If n = 3 Then
If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
WordNum = Trim(Temp2 & Temp1)
End If
If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
End If
Next n
NumStr = Trim(Str(Abs(MyNumber)))
' Values after the decimal place
DecimalPosition = InStr(NumStr, ".")
Numbers(0) = "Zero"
If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
Temp1 = " point"
For n = DecimalPosition + 1 To Len(NumStr)
Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
Next n
WordNum = WordNum & Temp1
End If
If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
WordNum = "Zero" & WordNum
End If
End Function
Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
If TensNum <= 19 Then
GetTens = Numbers(TensNum)
Else
Dim MyNo As String
MyNo = Format(TensNum, "00")
GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
End If
End Function
After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)
It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.
Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)
you will see a Words equivalent of the numeric value.
This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel
I don't have MySQL, but there are RDBMS (Postgres, among others) in which you can use the hack
SELECT id || '' FROM some_table;
The concatenate does an implicit conversion.
I’m tired of looking for free translators and the best option for me was Selenium (more precisely selenide and webdrivermanager) and https://translate.google.com
import io.github.bonigarcia.wdm.ChromeDriverManager;
import com.codeborne.selenide.Configuration;
import io.github.bonigarcia.wdm.DriverManagerType;
import static com.codeborne.selenide.Selenide.*;
public class Main {
public static void main(String[] args) throws IOException, ParseException {
ChromeDriverManager.getInstance(DriverManagerType.CHROME).version("76.0.3809.126").setup();
Configuration.startMaximized = true;
open("https://translate.google.com/?hl=ru#view=home&op=translate&sl=en&tl=ru");
String[] strings = /some strings to translate
for (String data: strings) {
$x("//textarea[@id='source']").clear();
$x("//textarea[@id='source']").sendKeys(data);
String translation = $x("//span[@class='tlid-translation translation']").getText();
}
}
}
A patch is little more (see below) than a series of instructions: "add this here", "remove that there", "change this third thing to a fourth". That's why git tells you:
The copy of the patch that failed is found in: c:/.../project2/.git/rebase-apply/patch
You can open that patch in your favorite viewer or editor, open the files-to-be-changed in your favorite editor, and "hand apply" the patch, using what you know (and git does not) to figure out how "add this here" is to be done when the files-to-be-changed now look little or nothing like what they did when they were changed earlier, with those changes delivered to you as a patch.
A three-way merge introduces that "little more" information than the plain "series of instructions": it tells you what the original version of the file was as well. If your repository has the original version, your git can compare what you did to a file, to what the patch says to do to the file.
As you saw above, if you request the three-way merge, git can't find the "original version" in the other repository, so it can't even attempt the three-way merge. As a result you get no conflict markers, and you must do the patch-application by hand.
--reject
When you have to apply the patch by hand, it's still possible that git can apply most of the patch for you automatically and leave only a few pieces to the entity with the ability to reason about the code (or whatever it is that needs patching). Adding --reject
tells git to do that, and leave the "inapplicable" parts of the patch in rejection files. If you use this option, you must still hand-apply each failing patch, and figure out what to do with the rejected portions.
Once you have made the required changes, you can git add
the modified files and use git am --continue
to tell git to commit the changes and move on to the next patch.
Since we don't have your code, I can't tell if this is the case, but sometimes, you wind up with one of the patches saying things that amount to, e.g., "fix the spelling of a word on line 42" when the spelling there was already fixed.
In this particular case, you, having looked at the patch and the current code, should say to yourself: "aha, this patch should just be skipped entirely!" That's when you use the other advice git already printed:
If you prefer to skip this patch, run "git am --skip" instead.
If you run git am --skip
, git will skip over that patch, so that if there were five patches in the mailbox, it will end up adding just four commits, instead of five (or three instead of five if you skip twice, and so on).
The JavaScript section of the Wikipedia entry, List of Unit Testing Frameworks, provides a list of available choices. It indicates whether they work client-side, server-side, or both.
You probably haven't installed GLUT:
Source: http://cacs.usc.edu/education/cs596/OGL_Setup.pdf
EDIT:
The quickest way is to download the latest header, and compiled DLLs for it, place it in your system32 folder or reference it in your project. Version 3.7 (latest as of this post) is here: http://www.opengl.org/resources/libraries/glut/glutdlls37beta.zip
Folder references:
glut.h: 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\GL\'
glut32.lib: 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\'
glut32.dll: 'C:\Windows\System32\'
For 64-bit machines, you will want to do this.
glut32.dll: 'C:\Windows\SysWOW64\'
Same pattern applies to freeglut and GLEW files with the header files in the GL folder, lib in the lib folder, and dll in the System32 (and SysWOW64) folder.
1. Under Visual C++, select Empty Project.
2. Go to Project -> Properties. Select Linker -> Input then add the following to the Additional Dependencies field:
opengl32.lib
glu32.lib
glut32.lib
There is an another mature and actively developed "player" on the javascript linting front - ESLint
:
ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code. In many ways, it is similar to JSLint and JSHint with a few exceptions:
- ESLint uses Esprima for JavaScript parsing.
- ESLint uses an AST to evaluate patterns in code.
- ESLint is completely pluggable, every single rule is a plugin and you can add more at runtime.
What really matters here is that it is extendable via custom plugins/rules. There are already multiple plugins written for different purposes. Among others, there are:
And, of course, you can use your build tool of choice to run ESLint
:
This is the exit status of the last executed command.
For example the command true
always returns a status of 0
and false
always returns a status of 1
:
true
echo $? # echoes 0
false
echo $? # echoes 1
From the manual: (acessible by calling man bash
in your shell)
$?
Expands to the exit status of the most recently executed foreground pipeline.
By convention an exit status of 0
means success, and non-zero return status means failure. Learn more about exit statuses on wikipedia.
There are other special variables like this, as you can see on this online manual: https://www.gnu.org/s/bash/manual/bash.html#Special-Parameters
I know this is an old post but having read this I think this solution is much simpler (though technically it solves the problem with Javascript not PHP).
<html>
<head>
<title>Ultan.me - Unset</title>
<script type="text/javascript">
function setTitle( text ) {
document.title = text;
}
</script>
<!-- other head info -->
</head>
<?php
// Make the call to the DB to get the title text. See OP post for example
$title_text = "Ultan.me - DB Title";
// Use body onload to set the title of the page
print "<body onload=\"setTitle( '$title_text' )\" >";
// Rest of your code here
print "<p>Either use php to print stuff</p>";
?>
<p>or just drop in and out of php</p>
<?php
// close the html page
print "</body></html>";
?>
It will use the equals method to see if the key is present even and especially if there are more than one element in the same bucket.
Building off of @gnovice's answer, you can actually create filled plots with shading only in the area between the two curves. Just use fill
in conjunction with fliplr
.
Example:
x=0:0.01:2*pi; %#initialize x array
y1=sin(x); %#create first curve
y2=sin(x)+.5; %#create second curve
X=[x,fliplr(x)]; %#create continuous x value array for plotting
Y=[y1,fliplr(y2)]; %#create y values for out and then back
fill(X,Y,'b'); %#plot filled area
By flipping the x array and concatenating it with the original, you're going out, down, back, and then up to close both arrays in a complete, many-many-many-sided polygon.
byte[] toByteArray(int value) {
return ByteBuffer.allocate(4).putInt(value).array();
}
byte[] toByteArray(int value) {
return new byte[] {
(byte)(value >> 24),
(byte)(value >> 16),
(byte)(value >> 8),
(byte)value };
}
int fromByteArray(byte[] bytes) {
return ByteBuffer.wrap(bytes).getInt();
}
// packing an array of 4 bytes to an int, big endian, minimal parentheses
// operator precedence: <<, &, |
// when operators of equal precedence (here bitwise OR) appear in the same expression, they are evaluated from left to right
int fromByteArray(byte[] bytes) {
return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
}
// packing an array of 4 bytes to an int, big endian, clean code
int fromByteArray(byte[] bytes) {
return ((bytes[0] & 0xFF) << 24) |
((bytes[1] & 0xFF) << 16) |
((bytes[2] & 0xFF) << 8 ) |
((bytes[3] & 0xFF) << 0 );
}
When packing signed bytes into an int, each byte needs to be masked off because it is sign-extended to 32 bits (rather than zero-extended) due to the arithmetic promotion rule (described in JLS, Conversions and Promotions).
There's an interesting puzzle related to this described in Java Puzzlers ("A Big Delight in Every Byte") by Joshua Bloch and Neal Gafter . When comparing a byte value to an int value, the byte is sign-extended to an int and then this value is compared to the other int
byte[] bytes = (…)
if (bytes[0] == 0xFF) {
// dead code, bytes[0] is in the range [-128,127] and thus never equal to 255
}
Note that all numeric types are signed in Java with exception to char being a 16-bit unsigned integer type.
Check out "undoing changes" section of the svn book
You should set the option:
local-infile=1
into your [mysql] entry of my.cnf file or call mysql client with the --local-infile option:
mysql --local-infile -uroot -pyourpwd yourdbname
You have to be sure that the same parameter is defined into your [mysqld] section too to enable the "local infile" feature server side.
It's a security restriction.
LOAD DATA LOCAL INFILE '/softwares/data/data.csv' INTO TABLE tableName;
A better solution for python2:
from multiprocessing import Pool
def func((i, (a, b))):
print i, a, b
return a + b
pool = Pool(3)
pool.map(func, [(0,(1,2)), (1,(2,3)), (2,(3, 4))])
2 3 4
1 2 3
0 1 2
out[]:
[3, 5, 7]
You need to add your tiles into your resource bundle. I mean add all those files to your project make sure to copy all files to project directory option checked.
My personal preference is to delete the branch name after I’m done with a topic branch.
Instead of trying to use the branch name to explain the meaning of the branch, I start the subject line of the commit message in the first commit on that branch with “Branch:” and include further explanations in the body of the message if the subject does not give me enough space.
The branch name in my use is purely a handle for referring to a topic branch while working on it. Once work on the topic branch has concluded, I get rid of the branch name, sometimes tagging the commit for later reference.
That makes the output of git branch
more useful as well: it only lists long-lived branches and active topic branches, not all branches ever.
Here is how i resolved this:
1 - create a Field Variable like: private Menu mMenuItem;
2 - override the method invalidateOptionsMenu():
@Override
public void invalidateOptionsMenu() {
super.invalidateOptionsMenu();
}
3 - call the method invalidateOptionsMenu()
in your onCreate()
4 - add mMenuItem = menu
in your onCreateOptionsMenu(Menu menu)
like this:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.webview_menu, menu);
mMenuItem = menu;
return super.onCreateOptionsMenu(menu);
}
5 - in the method onOptionsItemSelected(MenuItem item)
change the icon you want like this:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.R.id.action_settings:
mMenuItem.getItem(0).setIcon(R.drawable.ic_launcher); // to change the fav icon
//Toast.makeText(this, " " + mMenuItem.getItem(0).getTitle(), Toast.LENGTH_SHORT).show(); <<--- this to check if the item in the index 0 is the one you are looking for
return true;
}
return super.onOptionsItemSelected(item);
}
Searched on the go-nuts email list and found a solution posted by Peter Froehlich on 11/15/2009.
package main
import "fmt"
func main() {
dict := map[string]int {"foo" : 1, "bar" : 2}
value, ok := dict["baz"]
if ok {
fmt.Println("value: ", value)
} else {
fmt.Println("key not found")
}
}
Or, more compactly,
if value, ok := dict["baz"]; ok {
fmt.Println("value: ", value)
} else {
fmt.Println("key not found")
}
Note, using this form of the if
statement, the value
and ok
variables are only visible inside the if
conditions.
Use window.open()
. It's pretty straightforward !
In your component.html
file-
<a (click)="goToLink("www.example.com")">page link</a>
In your component.ts
file-
goToLink(url: string){
window.open(url, "_blank");
}
You can solve your problem with help of Attribute routing
Controller
[Route("api/category/{categoryId}")]
public IEnumerable<Order> GetCategoryId(int categoryId) { ... }
URI in jquery
api/category/1
Route Configuration
using System.Web.Http;
namespace WebApplication
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
// Other Web API configuration not shown.
}
}
}
and your default routing is working as default convention-based routing
Controller
public string Get(int id)
{
return "object of id id";
}
URI in Jquery
/api/records/1
Route Configuration
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Attribute routing.
config.MapHttpAttributeRoutes();
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Review article for more information Attribute routing and onvention-based routing here & this
for the function on String: components(separatedBy: String)
in Swift 5.1
have change to:
string.split(separator: "/")
I think that what you have to do is make a thorough check of some properties that will always be in a dom element, but their combination won't most likely be in another object, like so:
var isDom = function (inp) {
return inp && inp.tagName && inp.nodeName && inp.ownerDocument && inp.removeAttribute;
};
SimpleDateFormat
is great, just note that HH
is different from hh
when working with hours. HH
will return 24 hour based hours and hh will return 12 hour based hours.
For example, the following will return 12 hour time:
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
While this will return 24 hour time:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
you can use whodid (https://www.npmjs.com/package/whodid)
$ npm install whodid -g
$ cd your-project-dir
and
$ whodid author --include-merge=false --path=./ --valid-threshold=1000 --since=1.week
or just type
$ whodid
then you can see result like this
Contribution state
=====================================================
score | author
-----------------------------------------------------
3059 | someguy <[email protected]>
585 | somelady <[email protected]>
212 | niceguy <[email protected]>
173 | coolguy <[email protected]>
=====================================================
In case you actually mean what you seem to ask, I'll provide this alternative answer.
You say you want the dict to return a specified value, you do not say you want to set that value at the same time, like defaultdict
does. This will do so:
class DictWithDefault(dict):
def __init__(self, default, **kwargs):
self.default = default
super(DictWithDefault, self).__init__(**kwargs)
def __getitem__(self, key):
if key in self:
return super(DictWithDefault, self).__getitem__(key)
return self.default
Use like this:
d = DictWIthDefault(99, x=5, y=3)
print d["x"] # 5
print d[42] # 99
42 in d # False
d[42] = 3
42 in d # True
Alternatively, you can use a standard dict
like this:
d = {3: 9, 4: 2}
default = 99
print d.get(3, default) # 9
print d.get(42, default) # 99
2,147,483,647 bytes, since the value is a signed integer (Int32). That's probably more than you'll need.
A alternative without glib dependency is pkg-config-lite.
Extract pkg-config.exe
from the archive and put it in your path.
Nowdays this package is available using chocolatey, then it could be installed whith
choco install pkgconfiglite
The first answer is good for understanding how it works. But I wanted to understand how I should be using it in practice.
SUMMARY
class_weight="balanced"
works decent in the absence of you wanting to optimize manuallyclass_weight="balanced"
you capture more true events (higher TRUE recall) but also you are more likely to get false alerts (lower TRUE precision)
NB
The result might differ when using RF or GBM. sklearn does not have class_weight="balanced"
for GBM but lightgbm has LGBMClassifier(is_unbalance=False)
CODE
# scikit-learn==0.21.3
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, classification_report
import numpy as np
import pandas as pd
# case: moderate imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.8]) #,flip_y=0.1,class_sep=0.5)
np.mean(y) # 0.2
LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.184
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X).mean() # 0.296 => seems to make things worse?
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.292 => seems to make things worse?
roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.83
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X)) # 0.86 => about the same
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.86 => about the same
# case: strong imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.95])
np.mean(y) # 0.06
LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.02
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X).mean() # 0.25 => huh??
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.22 => huh??
(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).mean() # same as last
roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.64
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X)) # 0.84 => much better
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.85 => similar to manual
roc_auc_score(y,(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).astype(int)) # same as last
print(classification_report(y,LogisticRegression(C=1e9).fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True,normalize='index') # few prediced TRUE with only 28% TRUE recall and 86% TRUE precision so 6%*28%~=2%
print(classification_report(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True,normalize='index') # 88% TRUE recall but also lot of false positives with only 23% TRUE precision, making total predicted % TRUE > actual % TRUE
There is another the error happening which related to the order when calling initializing global variables. I've had the sample of code has similar error FailedPreconditionError (see above for traceback): Attempting to use uninitialized value W
def linear(X, n_input, n_output, activation = None):
W = tf.Variable(tf.random_normal([n_input, n_output], stddev=0.1), name='W')
b = tf.Variable(tf.constant(0, dtype=tf.float32, shape=[n_output]), name='b')
if activation != None:
h = tf.nn.tanh(tf.add(tf.matmul(X, W),b), name='h')
else:
h = tf.add(tf.matmul(X, W),b, name='h')
return h
from tensorflow.python.framework import ops
ops.reset_default_graph()
g = tf.get_default_graph()
print([op.name for op in g.get_operations()])
with tf.Session() as sess:
# RUN INIT
sess.run(tf.global_variables_initializer())
# But W hasn't in the graph yet so not know to initialize
# EVAL then error
print(linear(np.array([[1.0,2.0,3.0]]).astype(np.float32), 3, 3).eval())
You should change to following
from tensorflow.python.framework import ops
ops.reset_default_graph()
g = tf.get_default_graph()
print([op.name for op in g.get_operations()])
with tf.Session() as
# NOT RUNNING BUT ASSIGN
l = linear(np.array([[1.0,2.0,3.0]]).astype(np.float32), 3, 3)
# RUN INIT
sess.run(tf.global_variables_initializer())
print([op.name for op in g.get_operations()])
# ONLY EVAL AFTER INIT
print(l.eval(session=sess))
The above answer seems good. But another way of doing this is adding the auto commit option along with the db connect. This automatically commits every other operations performed in the db, avoiding the use of mentioning sql.commit()
every time.
mydb = MySQLdb.connect(host='localhost',
user='root',
passwd='',
db='mydb',autocommit=true)
If you use String concatenation in a loop, something like this,
String s = "";
for (int i = 0; i < 100; i++) {
s += ", " + i;
}
then you should use a StringBuilder
(not StringBuffer
) instead of a String
, because it is much faster and consumes less memory.
If you have a single statement,
String s = "1, " + "2, " + "3, " + "4, " ...;
then you can use String
s, because the compiler will use StringBuilder
automatically.
an EXE
file is created as long as you build the project. you can usually find this on the debug folder of you project.
C:\Users\username\Documents\Visual Studio 2012\Projects\ProjectName\bin\Debug
Don't try to scan text with nextLine(); AFTER using nextInt() with the same scanner! It doesn't work well with Java Scanner, and many Java developers opt to just use another Scanner for integers. You can call these scanners scan1 and scan2 if you want.
Dynamically Created for a Row in a Table
See below the Link
http://msdn.microsoft.com/en-us/library/7bewx260(v=vs.100).aspx
Put the command to execute the sql script into a batch file then run the below code
string batchFileName = @"c:\batosql.bat";
string sqlFileName = @"c:\MySqlScripts.sql";
Process proc = new Process();
proc.StartInfo.FileName = batchFileName;
proc.StartInfo.Arguments = sqlFileName;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.ErrorDialog = false;
proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(batchFileName);
proc.Start();
proc.WaitForExit();
if ( proc.ExitCode!= 0 )
in the batch file write something like this (sample for sql server)
osql -E -i %1
This is a modified version of Alex's answer. We can save the state of a module's namespace and restore it by using the following 2 methods...
__saved_context__ = {}
def saveContext():
import sys
__saved_context__.update(sys.modules[__name__].__dict__)
def restoreContext():
import sys
names = sys.modules[__name__].__dict__.keys()
for n in names:
if n not in __saved_context__:
del sys.modules[__name__].__dict__[n]
saveContext()
hello = 'hi there'
print hello # prints "hi there" on stdout
restoreContext()
print hello # throws an exception
You can also add a line "clear = restoreContext" before calling saveContext() and clear() will work like matlab's clear.
You need an scp client. Putty is not one. You can use WinSCP or PSCP. Both are free software.
Although overloading paradigm is not fully supported by PHP the same (or very similar) effect can be achieved with default parameter(s) (as somebody mentioned before).
If you define your function like this:
function f($p=0)
{
if($p)
{
//implement functionality #1 here
}
else
{
//implement functionality #2 here
}
}
When you call this function like:
f();
you'll get one functionality (#1), but if you call it with parameter like:
f(1);
you'll get another functionality (#2). That's the effect of overloading - different functionality depending on function's input parameter(s).
I know, somebody will ask now what functionality one will get if he/she calls this function as f(0).
An inline-block covers the whole line (from left to right), so a margin left and/or right won't work here. What you need is a block, a block has borders on the left and the right so can be influenced by margins.
This is how it works for me:
#content {
display: block;
margin: 0 auto;
}
It is actually very simple. You don't have to go through a lot of stuff. Just run the following command in terminal and follow on-screen instructions.
sudo mysql_secure_installation
Edit: Since this turned out to be a popular answer, I'm adding the disclaimer that @crush mentioned in a comment below. If you use this work around, be aware that you're opening yourself up for an XSS vulnerability. Only use this solution if you know what you're doing and can be certain of the HTML content in the attribute.
The easiest way to do this is to supply a function to the content
option that overrides the default behavior:
$(function () {
$(document).tooltip({
content: function () {
return $(this).prop('title');
}
});
});
Example: http://jsfiddle.net/Aa5nK/12/
Another option would be to override the tooltip widget with your own that changes the content
option:
$.widget("ui.tooltip", $.ui.tooltip, {
options: {
content: function () {
return $(this).prop('title');
}
}
});
Now, every time you call .tooltip
, HTML content will be returned.
Example: http://jsfiddle.net/Aa5nK/14/
Had a similar problem. My issue was that I had several projects within the same solution that each were referencing a specific version of a DLL but different versions. The solution was to set 'Specific Version' to false in the all of the properties of all of the references.
You can use relative positioning to overlap your elements. However, the space they would normally occupy will still be reserved for the element:
<div style="background-color:#f00;width:200px;height:100px;">
DEFAULT POSITIONED
</div>
<div style="background-color:#0f0;width:200px;height:100px;position:relative;top:-50px;left:50px;">
RELATIVE POSITIONED
</div>
<div style="background-color:#00f;width:200px;height:100px;">
DEFAULT POSITIONED
</div>
In the example above, there will be a block of white space between the two 'DEFAULT POSITIONED' elements. This is caused, because the 'RELATIVE POSITIONED' element still has it's space reserved.
If you use absolute positioning, your elements will not have any space reserved, so your element will actually overlap, without breaking your document:
<div style="background-color:#f00;width:200px;height:100px;">
DEFAULT POSITIONED
</div>
<div style="background-color:#0f0;width:200px;height:100px;position:absolute;top:50px;left:50px;">
ABSOLUTE POSITIONED
</div>
<div style="background-color:#00f;width:200px;height:100px;">
DEFAULT POSITIONED
</div>
Finally, you can control which elements are on top of the others by using z-index:
<div style="z-index:10;background-color:#f00;width:200px;height:100px;">
DEFAULT POSITIONED
</div>
<div style="z-index:5;background-color:#0f0;width:200px;height:100px;position:absolute;top:50px;left:50px;">
ABSOLUTE POSITIONED
</div>
<div style="z-index:0;background-color:#00f;width:200px;height:100px;">
DEFAULT POSITIONED
</div>
I'm not sure the default hashcode is the address - I read the OpenJDK source for hashcode generation a while ago, and I remember it being something a bit more complicated. Still not something that guarantees a good distribution, perhaps. However, that is to some extent moot, as few classes you'd use as keys in a hashmap use the default hashcode - they supply their own implementations, which ought to be good.
On top of that, what you may not know (again, this is based in reading source - it's not guaranteed) is that HashMap stirs the hash before using it, to mix entropy from throughout the word into the bottom bits, which is where it's needed for all but the hugest hashmaps. That helps deal with hashes that specifically don't do that themselves, although i can't think of any common cases where you'd see that.
Finally, what happens when the table is overloaded is that it degenerates into a set of parallel linked lists - performance becomes O(n). Specifically, the number of links traversed will on average be half the load factor.
psutil can find process by name and kill it:
import psutil
PROCNAME = "python.exe"
for proc in psutil.process_iter():
# check whether the process name matches
if proc.name() == PROCNAME:
proc.kill()
Create table #temp1
(
id int identity(1,1),
name varchar(50),
profession varchar(50)
)
Create table #temp2
(
id int identity(1,1),
name varchar(50),
profession varchar(50)
)
-----main query ------
insert into #temp1(name,profession)
output inserted.name,inserted.profession into #temp2
select 'Shekhar','IT'
The error says it all actually. Your configuration tells Nginx to listen on port 80 (HTTP) and use SSL. When you point your browser to http://localhost
, it tries to connect via HTTP. Since Nginx expects SSL, it complains with the error.
The workaround is very simple. You need two server
sections:
server {
listen 80;
// other directives...
}
server {
listen 443;
ssl on;
// SSL directives...
// other directives...
}
You just need to add this line to the window there:
exec (your stored proc name) (and possibly add parameters)
What is your stored proc called, and what parameters does it expect?
$(function() {
$('#myselect').change(function() {
$('#myhidden').val =$("#myselect option:selected").text();
});
});
When we apply local url, ErrorDocument directive expect the full path from DocumentRoot. There fore,
ErrorDocument 404 /yourfoldernames/errors/404.html
Alpine uses the command adduser
and addgroup
for creating users and groups (rather than useradd
and usergroup
).
FROM alpine:latest
# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
# Tell docker that all future commands should run as the appuser user
USER appuser
The flags for adduser
are:
Usage: adduser [OPTIONS] USER [GROUP] Create new user, or add USER to GROUP -h DIR Home directory -g GECOS GECOS field -s SHELL Login shell -G GRP Group -S Create a system user -D Don't assign a password -H Don't create home directory -u UID User id -k SKEL Skeleton directory (/etc/skel)
Here is a code to split the data into n=5 folds in a stratified manner
% X = data array
% y = Class_label
from sklearn.cross_validation import StratifiedKFold
skf = StratifiedKFold(y, n_folds=5)
for train_index, test_index in skf:
print("TRAIN:", train_index, "TEST:", test_index)
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
You would need to loop through the rows of each table, and then through each column within that loop to compare individual values.
There's a code sample here: http://canlu.blogspot.com/2009/05/how-to-compare-two-datatables-in-adonet.html
Also you can try to use
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
if you are dealing with jackson with version below 2+ (1.9.5) i tested it, you can easily use this annotation above the class. Not for specified for the attributes, just for class decleration.
Code used basic nav bootstrap
<!--MENU CENTER`enter code here` RESPONSIVE -->_x000D_
_x000D_
<div class="container-fluid">_x000D_
<div class="container logo"><h1>LOGO</h1></div>_x000D_
<nav class="navbar navbar-default menu">_x000D_
<div class="container-fluid">_x000D_
<!-- Brand and toggle get grouped for better mobile display -->_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#defaultNavbar2"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button>_x000D_
</div>_x000D_
<!-- Collect the nav links, forms, and other content for toggling -->_x000D_
<div class="collapse navbar-collapse" id="defaultNavbar2">_x000D_
<ul class="nav nav-justified" >_x000D_
<li><a href="#">Home</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
<!-- /.navbar-collapse -->_x000D_
</div>_x000D_
<!-- /.container-fluid -->_x000D_
</nav>_x000D_
</div>_x000D_
<!-- END MENU-->
_x000D_
If I understand correctly, you want to get the String of an Editable object, right? If yes, try using toString()
.
If you are interested in a more compact stack trace with more information (package detail) that looks like:
java.net.SocketTimeoutException:Receive timed out
at j.n.PlainDatagramSocketImpl.receive0(Native Method)[na:1.8.0_151]
at j.n.AbstractPlainDatagramSocketImpl.receive(AbstractPlainDatagramSocketImpl.java:143)[^]
at j.n.DatagramSocket.receive(DatagramSocket.java:812)[^]
at o.s.n.SntpClient.requestTime(SntpClient.java:213)[classes/]
at o.s.n.SntpClient$1.call(^:145)[^]
at ^.call(^:134)[^]
at o.s.f.SyncRetryExecutor.call(SyncRetryExecutor.java:124)[^]
at o.s.f.RetryPolicy.call(RetryPolicy.java:105)[^]
at o.s.f.SyncRetryExecutor.call(SyncRetryExecutor.java:59)[^]
at o.s.n.SntpClient.requestTimeHA(SntpClient.java:134)[^]
at ^.requestTimeHA(^:122)[^]
at o.s.n.SntpClientTest.test2h(SntpClientTest.java:89)[test-classes/]
at s.r.NativeMethodAccessorImpl.invoke0(Native Method)[na:1.8.0_151]
you can try to use Throwables.writeTo from the spf4j lib.
You can do this by using Year(), Month() Day() and datepart().
In you example this would be:
select Closing_Date, Category, COUNT(Status)TotalCount from MyTable
where Closing_Date >= '2012-02-01' and Closing_Date <= '2012-12-31'
and Defect_Status1 is not null
group by Year(Closing_Date), Month(Closing_Date), Category
For Chrome users, I recommend Stylebot, which will let you override any CSS on any page, also let you search and install other share custom CSS. However, for our purpose we don't need any advance theme. Open Stylebot, change to Edit CSS
. Jupyter captures some keystrokes, so you will not be able to type the code below in. Just copy and paste, or just your editor:
#notebook-container.container {
width: 90%;
}
Change the width as you like, I find 90% looks nicer than 100%. But it is totally up to your eye.
It seems no one has mentioned about using nonNull
method which also can be used with streams
in Java 8 to remove null (but not empty) as:
String[] origArray = {"Apple", "", "Cat", "Dog", "", null};
String[] cleanedArray = Arrays.stream(firstArray).filter(Objects::nonNull).toArray(String[]::new);
System.out.println(Arrays.toString(origArray));
System.out.println(Arrays.toString(cleanedArray));
And the output is:
[Apple, , Cat, Dog, , null]
[Apple, , Cat, Dog, ]
If we want to incorporate empty also then we can define a utility method (in class Utils
(say)):
public static boolean isEmpty(String string) {
return (string != null && string.isEmpty());
}
And then use it to filter the items as:
Arrays.stream(firstArray).filter(Utils::isEmpty).toArray(String[]::new);
I believe Apache common also provides a utility method StringUtils.isNotEmpty
which can also be used.
Reference the checkbox by it's id and not with the # Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
I do a mix of edem's answer and your second code. This way, I have the benefits of common getter/setters (code completion in your IDE), ease of coding if I want, exceptions due to inexistent properties (great for discovering typos: $foo->naem
instead of $foo->name
), read only properties and compound properties.
class Foo
{
private $_bar;
private $_baz;
public function getBar()
{
return $this->_bar;
}
public function setBar($value)
{
$this->_bar = $value;
}
public function getBaz()
{
return $this->_baz;
}
public function getBarBaz()
{
return $this->_bar . ' ' . $this->_baz;
}
public function __get($var)
{
$func = 'get'.$var;
if (method_exists($this, $func))
{
return $this->$func();
} else {
throw new InexistentPropertyException("Inexistent property: $var");
}
}
public function __set($var, $value)
{
$func = 'set'.$var;
if (method_exists($this, $func))
{
$this->$func($value);
} else {
if (method_exists($this, 'get'.$var))
{
throw new ReadOnlyException("property $var is read-only");
} else {
throw new InexistentPropertyException("Inexistent property: $var");
}
}
}
}
Via Type.GetType you can get the type information. You can use this class to get the method information and then invoke the method (for static methods, leave the first parameter null).
You might also need the Assembly name to correctly identify the type.
If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.
I'd suggest <a href='page1.jsp'>Refresh</a>
.
To sort the array by the value of the "title" key use:
uasort($myArray, function($a, $b) {
return strcmp($a['title'], $b['title']);
});
strcmp compare the strings.
uasort() maintains the array keys as they were defined.
Basically React.useState(0)
magically sees that it should return the tuple count
and setCount
(a method to change count
). The parameter useState
takes sets the initial value of count
.
const [count, setCount] = React.useState(0);
const [count2, setCount2] = React.useState(0);
// increments count by 1 when first button clicked
function handleClick(){
setCount(count + 1);
}
// increments count2 by 1 when second button clicked
function handleClick2(){
setCount2(count2 + 1);
}
return (
<div>
<h2>A React counter made with the useState Hook!</h2>
<p>You clicked {count} times</p>
<p>You clicked {count2} times</p>
<button onClick={handleClick}>
Click me
</button>
<button onClick={handleClick2}>
Click me2
</button>
);
Based off Enmanuel Duran's example, but shows two counters and writes lambda functions as normal functions, so some people might understand it easier.
Like so:
def find_and_replace(file, word, replacement):
with open(file, 'r+') as f:
text = f.read()
f.write(text.replace(word, replacement))
There is OxyPlot which I recommend. It has packages for WPF, Metro, Silverlight, Windows Forms, Avalonia UI, XWT. Besides graphics it can export to SVG, PDF, Open XML, etc. And it even supports Mono and Xamarin for Android and iOS. It is actively developed too.
There is also a new (at least for me) open source .NET plotting library called Live-Charts. The plots are pretty interactive. Library suports WPF, WinForms and UWP. Xamarin is planned. The design is made towards MV* patterns. But @Pawel Audionysos suggests not such a good performance of Live-Charts WPF.
I would like to describe a very good example of why negative padding
would be useful and awesome.
As all of us CSS developers know, vertically aligning a dynamically sizing div within another is a hassle, and for the most part, viewed as being impossible only using CSS. The incorporation of negative padding
could change this.
Please review the following HTML:
<div style="height:600px; width:100%;">
<div class="vertical-align" style="width:100%;height:auto;" >
This DIV's height will change based the width of the screen.
</div>
</div>
With the following CSS, we would be able to vertically center the content of the inner div
within the outer div
:
.vertical-align {
position: absolute;
top:50%;
padding-top:-50%;
overflow: visible;
}
Allow me to explain...
Absolutely positioning the inner div's top at 50% places the top edge of the inner div at the center of the outer div. Pretty simple. This is because percentage based positioning is relative to the inner dimensions of the parent element.
Percentage based padding, on the other hand, is based on the inner dimensions of the targeted element. So, by applying the property of padding-top: -50%;
we have shifted the content of the inner div upward by a distance of 50% of the height of the inner div's content, therefore centering the inner div's content within the outer div and still allowing the height dimension of the inner div to be dynamic!
If you ask me OP, this would be the best use-case, and I think it should be implemented just so I can do this hack. lol. Or, they should just fix the functionality of vertical-align
and give us a version of vertical-align
that works on all elements.
There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml
. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml
mediatype.
If you only care about modern browsers, a fixed header can be achieved much easier by using CSS transforms. Sounds odd, but works great:
document.getElementById("wrap").addEventListener("scroll", function(){
var translate = "translate(0,"+this.scrollTop+"px)";
this.querySelector("thead").style.transform = translate;
});
Support for CSS transforms is widely available except for Internet Explorer 8-.
Here is the full example for reference:
document.getElementById("wrap").addEventListener("scroll",function(){_x000D_
var translate = "translate(0,"+this.scrollTop+"px)";_x000D_
this.querySelector("thead").style.transform = translate;_x000D_
});
_x000D_
/* Your existing container */_x000D_
#wrap {_x000D_
overflow: auto;_x000D_
height: 400px;_x000D_
}_x000D_
_x000D_
/* CSS for demo */_x000D_
td {_x000D_
background-color: green;_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
}
_x000D_
<div id="wrap">_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Foo</th>_x000D_
<th>Bar</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr><td></td><td></td></tr>_x000D_
<tr><td></td><td></td></tr>_x000D_
<tr><td></td><td></td></tr>_x000D_
<tr><td></td><td></td></tr>_x000D_
<tr><td></td><td></td></tr>_x000D_
<tr><td></td><td></td></tr>_x000D_
<tr><td></td><td></td></tr>_x000D_
<tr><td></td><td></td></tr>_x000D_
<tr><td></td><td></td></tr>_x000D_
<tr><td></td><td></td></tr>_x000D_
<tr><td></td><td></td></tr>_x000D_
<tr><td></td><td></td></tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>
_x000D_
I've successful installed Google Maps v2 on an emulator using this guide.
You should do the following steps:
It depends on what you want to do with the script (or any other program you want to run).
If you just want to run the script system
is the easiest thing to do, but it does some other stuff too, including running a shell and having it run the command (/bin/sh under most *nix).
If you want to either feed the shell script via its standard input or consume its standard output you can use popen
(and pclose
) to set up a pipe. This also uses the shell (/bin/sh under most *nix) to run the command.
Both of these are library functions that do a lot under the hood, but if they don't meet your needs (or you just want to experiment and learn) you can also use system calls directly. This also allows you do avoid having the shell (/bin/sh) run your command for you.
The system calls of interest are fork
, execve
, and waitpid
. You may want to use one of the library wrappers around execve
(type man 3 exec
for a list of them). You may also want to use one of the other wait functions (man 2 wait
has them all). Additionally you may be interested in the system calls clone
and vfork
which are related to fork.
fork
duplicates the current program, where the only main difference is that the new process gets 0 returned from the call to fork. The parent process gets the new process's process id (or an error) returned.
execve
replaces the current program with a new program (keeping the same process id).
waitpid
is used by a parent process to wait on a particular child process to finish.
Having the fork and execve steps separate allows programs to do some setup for the new process before it is created (without messing up itself). These include changing standard input, output, and stderr to be different files than the parent process used, changing the user or group of the process, closing files that the child won't need, changing the session, or changing the environmental variables.
You may also be interested in the pipe
and dup2
system calls. pipe
creates a pipe (with both an input and an output file descriptor). dup2
duplicates a file descriptor as a specific file descriptor (dup
is similar but duplicates a file descriptor to the lowest available file descriptor).
I've just had an email from a github.com admin stating the following: "We normally advise people to use the HTTPS URL unless they have a specific reason to be using the SSH protocol. HTTPS is secure and easier to set up, so we default to that when a new repository is created."
The password prompt does indeed accept the normal github.com login details. A tutorial on how to set up password caching can be found here. I followed the steps in the tutorial, and it worked for me.
[Edit] This answer is for MSVS (the IDE, as opposed to VS Code). It seems Microsoft and Google go out of their way to choose confusing names for new products. I'll leave this answer here for now, while I (continue to) look for the equivalent stackoverflow question about MSVS. Let me know in the comments if you think I should delete it. Or better, point me to the MSVS version of this question.
I installed MSVS 2017 recently. None of the suggestions I've seen fixed the problem. The solution I figured out works for MSVS 2015 and 2017. Add a comment below if you find that it works for other versions.
Under Tools -> Options -> Text Editor -> C/C++ -> Formatting -> General, try unchecking the "Automatically indent when I type a tab" box. It seems counter intuitive, but it fixed the problem for me.
Try this...
def is_int(x):
absolute = abs(x)
rounded = round(absolute)
return absolute - rounded == 0
In MySQL Workbench 6, commands have been repositioned as the "Server Administration" tab is gone.
You now find the option "Data Export" under the "Management" section when you open a standard server connection.
$arr = $array = array( 9 => 'apple', 7 => 'orange', 13 => 'plum' );
echo reset($arr); // echoes 'apple'
If you don't want to lose the current pointer position, just create an alias for the array.
You already have the right answer. And if you want to make more complicated and interesting operations between Lists (collections) use apache commons collections (CollectionUtils) It allows you to make conjuction/disjunction, find intersection, check if one collection is a subset of another and other nice things.
The conversion to list
that's been suggested in the other answers is the best way if you still want to process the generator elements afterwards, but has one flaw: It uses O(n) memory. You can count the elements in a generator without using that much memory with:
sum(1 for x in generator)
Of course, be aware that this might be slower than len(list(generator))
in common Python implementations, and if the generators are long enough for the memory complexity to matter, the operation would take quite some time. Still, I personally prefer this solution as it describes what I want to get, and it doesn't give me anything extra that's not required (such as a list of all the elements).
Also listen to delnan's advice: If you're discarding the output of the generator it is very likely that there is a way to calculate the number of elements without running it, or by counting them in another manner.
My solution shuffles the rows, then takes the first 75% of the rows as train and the last 25% as test. Super simples!
row_count <- nrow(orders_pivotted)
shuffled_rows <- sample(row_count)
train <- orders_pivotted[head(shuffled_rows,floor(row_count*0.75)),]
test <- orders_pivotted[tail(shuffled_rows,floor(row_count*0.25)),]
Simple change to syntax is all that is needed:
create table ImagenesUsuario (
idImagen int not null identity(1,1) primary key
)
By explicitly using the "constraint" keyword, you can give the primary key constraint a particular name rather than depending on SQL Server to auto-assign a name:
create table ImagenesUsuario (
idImagen int not null identity(1,1) constraint pk_ImagenesUsario primary key
)
Add the "CLUSTERED" keyword if that makes the most sense based on your use of the table (i.e., the balance of searches for a particular idImagen and amount of writing outweighs the benefits of clustering the table by some other index).
You dont need to use a regex for this, PHP has an inbuilt function ctype_alnum
which will do this for you, and execute faster:
<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
if (ctype_alnum($testcase)) {
echo "The string $testcase consists of all letters or digits.\n";
} else {
echo "The string $testcase does not consist of all letters or digits.\n";
}
}
?>
If you desperately want to use a regex, you have a few options.
Firstly:
preg_match('/^[\w]+$/', $string);
\w
includes more than alphanumeric (it includes underscore), but includes all
of \d
.
Alternatively:
/^[a-zA-Z\d]+$/
Or even just:
/^[^\W_]+$/
If the Node
is not just any node, but actually an Element
(it could also be e.g. an attribute or a text node), you can cast it to Element
and use getElementsByTagName
.
In my case I tried all the tips suggested but the error remained. I solved changing with a more recent version and writing that in the pom.xml. After this everything is now ok.
Using Array.from, Array.prototype.forEach(), and arrow functions:
Iterate over the keys:
Array.from(myMap.keys()).forEach(key => console.log(key));
Iterate over the values:
Array.from(myMap.values()).forEach(value => console.log(value));
Iterate over the entries:
Array.from(myMap.entries()).forEach(entry => console.log('Key: ' + entry[0] + ' Value: ' + entry[1]));
You can also get a quick list of changed files if thats all you're looking for using the status command with the -u option
svn status -u
This will show you what revision the file is in the current code base versus the latest revision in the repository. I only use diff when I actually want to see differences in the files themselves.
There is a good tutorial on svn command here that explains a lot of these common scenarios: SVN Command Reference
Private Sub Command0_Click()
Application.FollowHyperlink "D:\1Zsnsn\SusuBarokah\20151008 Inventory.mdb"
End Sub
file
only guesses at the file encoding and may be wrong (especially in cases where special characters only appear late in large files).hexdump
to look at bytes of non-7-bit-ASCII text and compare against code tables for common encodings (ISO 8859-*, UTF-8) to decide for yourself what the encoding is.iconv
will use whatever input/output encoding you specify regardless of what the contents of the file are. If you specify the wrong input encoding, the output will be garbled.iconv
, file
may not report any change due to the limited way in which file
attempts to guess at the encoding. For a specific example, see my long answer.I ran into this today and came across your question. Perhaps I can add a little more information to help other people who run into this issue.
First, the term ASCII is overloaded, and that leads to confusion.
7-bit ASCII only includes 128 characters (00-7F or 0-127 in decimal). 7-bit ASCII is also sometimes referred to as US-ASCII.
UTF-8 encoding uses the same encoding as 7-bit ASCII for its first 128 characters. So a text file that only contains characters from that range of the first 128 characters will be identical at a byte level whether encoded with UTF-8 or 7-bit ASCII.
The term extended ASCII (or high ASCII) refers to eight-bit or larger character encodings that include the standard seven-bit ASCII characters, plus additional characters.
ISO 8859-1 (aka "ISO Latin 1") is a specific 8-bit ASCII extension standard that covers most characters for Western Europe. There are other ISO standards for Eastern European languages and Cyrillic languages. ISO 8859-1 includes characters like Ö, é, ñ and ß for German and Spanish.
"Extension" means that ISO 8859-1 includes the 7-bit ASCII standard and adds characters to it by using the 8th bit. So for the first 128 characters, it is equivalent at a byte level to ASCII and UTF-8 encoded files. However, when you start dealing with characters beyond the first 128, your are no longer UTF-8 equivalent at the byte level, and you must do a conversion if you want your "extended ASCII" file to be UTF-8 encoded.
ISO 8859 and proprietary adaptations
file
One lesson I learned today is that we can't trust file
to always give correct interpretation of a file's character encoding.
The command tells only what the file looks like, not what it is (in the case where file looks at the content). It is easy to fool the program by putting a magic number into a file the content of which does not match it. Thus the command is not usable as a security tool other than in specific situations.
file
looks for magic numbers in the file that hint at the type, but these can be wrong, no guarantee of correctness. file
also tries to guess the character encoding by looking at the bytes in the file. Basically file
has a series of tests that helps it guess at the file type and encoding.
My file is a large CSV file. file
reports this file as US ASCII encoded, which is WRONG.
$ ls -lh
total 850832
-rw-r--r-- 1 mattp staff 415M Mar 14 16:38 source-file
$ file -b --mime-type source-file
text/plain
$ file -b --mime-encoding source-file
us-ascii
My file has umlauts in it (ie Ö). The first non-7-bit-ascii doesn't show up until over 100k lines into the file. I suspect this is why file
doesn't realize the file encoding isn't US-ASCII.
$ pcregrep -no '[^\x00-\x7F]' source-file | head -n1
102321:?
I'm on a Mac, so using PCRE's grep
. With GNU grep you could use the -P
option. Alternatively on a Mac, one could install coreutils (via Homebrew or other) in order to get GNU grep.
I haven't dug into the source-code of file
, and the man page doesn't discuss the text encoding detection in detail, but I am guessing file
doesn't look at the whole file before guessing encoding.
Whatever my file's encoding is, these non-7-bit-ASCII characters break stuff. My German CSV file is ;
-separated and extracting a single column doesn't work.
$ cut -d";" -f1 source-file > tmp
cut: stdin: Illegal byte sequence
$ wc -l *
3081673 source-file
102320 tmp
3183993 total
Note the cut
error and that my "tmp" file has only 102320 lines with the first special character on line 102321.
Let's take a look at how these non-ASCII characters are encoded. I dump the first non-7-bit-ascii into hexdump
, do a little formatting, remove the newlines (0a
) and take just the first few.
$ pcregrep -o '[^\x00-\x7F]' source-file | head -n1 | hexdump -v -e '1/1 "%02x\n"'
d6
0a
Another way. I know the first non-7-bit-ASCII char is at position 85 on line 102321. I grab that line and tell hexdump
to take the two bytes starting at position 85. You can see the special (non-7-bit-ASCII) character represented by a ".", and the next byte is "M"... so this is a single-byte character encoding.
$ tail -n +102321 source-file | head -n1 | hexdump -C -s85 -n2
00000055 d6 4d |.M|
00000057
In both cases, we see the special character is represented by d6
. Since this character is an Ö which is a German letter, I am guessing that ISO 8859-1 should include this. Sure enough, you can see "d6" is a match (ISO/IEC 8859-1).
Important question... how do I know this character is an Ö without being sure of the file encoding? The answer is context. I opened the file, read the text and then determined what character it is supposed to be. If I open it in Vim it displays as an Ö because Vim does a better job of guessing the character encoding (in this case) than file
does.
So, my file seems to be ISO 8859-1. In theory I should check the rest of the non-7-bit-ASCII characters to make sure ISO 8859-1 is a good fit... There is nothing that forces a program to only use a single encoding when writing a file to disk (other than good manners).
I'll skip the check and move on to conversion step.
$ iconv -f iso-8859-1 -t utf8 source-file > output-file
$ file -b --mime-encoding output-file
us-ascii
Hmm. file
still tells me this file is US ASCII even after conversion. Let's check with hexdump
again.
$ tail -n +102321 output-file | head -n1 | hexdump -C -s85 -n2
00000055 c3 96 |..|
00000057
Definitely a change. Note that we have two bytes of non-7-bit-ASCII (represented by the "." on the right) and the hex code for the two bytes is now c3 96
. If we take a look, seems we have UTF-8 now (c3 96
is the encoding of Ö
in UTF-8) UTF-8 encoding table and Unicode characters
But file
still reports our file as us-ascii
? Well, I think this goes back to the point about file
not looking at the whole file and the fact that the first non-7-bit-ASCII characters don't occur until late in the file.
I'll use sed
to stick a Ö at the beginning of the file and see what happens.
$ sed '1s/^/Ö\'$'\n/' source-file > test-file
$ head -n1 test-file
Ö
$ head -n1 test-file | hexdump -C
00000000 c3 96 0a |...|
00000003
Cool, we have an umlaut. Note the encoding though is c3 96
(UTF-8). Hmm.
Checking our other umlauts in the same file again:
$ tail -n +102322 test-file | head -n1 | hexdump -C -s85 -n2
00000055 d6 4d |.M|
00000057
ISO 8859-1. Oops! It just goes to show how easy it is to get the encodings screwed up. To be clear, I've managed to create a mix of UTF-8 and ISO 8859-1 encodings in the same file.
Let's try converting our new test file with the umlaut (Ö) at the front and see what happens.
$ iconv -f iso-8859-1 -t utf8 test-file > test-file-converted
$ head -n1 test-file-converted | hexdump -C
00000000 c3 83 c2 96 0a |.....|
00000005
$ tail -n +102322 test-file-converted | head -n1 | hexdump -C -s85 -n2
00000055 c3 96 |..|
00000057
Oops. The first umlaut that was UTF-8 was interpreted as ISO 8859-1 since that is what we told iconv
. The second umlaut is correctly converted from d6
(ISO 8859-1) to c3 96
(UTF-8).
I'll try again, but this time I will use Vim to do the Ö insertion instead of sed
. Vim seemed to detect the encoding better (as "latin1" aka ISO 8859-1) so perhaps it will insert the new Ö with a consistent encoding.
$ vim source-file
$ head -n1 test-file-2
?
$ head -n1 test-file-2 | hexdump -C
00000000 d6 0d 0a |...|
00000003
$ tail -n +102322 test-file-2 | head -n1 | hexdump -C -s85 -n2
00000055 d6 4d |.M|
00000057
It looks good. It looks like ISO 8859-1 for new and old umlauts.
Now the test.
$ file -b --mime-encoding test-file-2
iso-8859-1
$ iconv -f iso-8859-1 -t utf8 test-file-2 > test-file-2-converted
$ file -b --mime-encoding test-file-2-converted
utf-8
Boom! Moral of the story. Don't trust file
to always guess your encoding right. It is easy to mix encodings within the same file. When in doubt, look at the hex.
A hack (also prone to failure) that would address this specific limitation of file
when dealing with large files would be to shorten the file to make sure that special (non-ascii) characters appear early in the file so file
is more likely to find them.
$ first_special=$(pcregrep -o1 -n '()[^\x00-\x7F]' source-file | head -n1 | cut -d":" -f1)
$ tail -n +$first_special source-file > /tmp/source-file-shorter
$ file -b --mime-encoding /tmp/source-file-shorter
iso-8859-1
You could then use (presumably correct) detected encoding to feed as input to iconv
to ensure you are converting correctly.
Christos Zoulas updated file
to make the amount of bytes looked at configurable. One day turn-around on the feature request, awesome!
http://bugs.gw.com/view.php?id=533 Allow altering how many bytes to read from analyzed files from the command line
The feature was released in file
version 5.26.
Looking at more of a large file before making a guess about encoding takes time. However, it is nice to have the option for specific use-cases where a better guess may outweigh additional time and I/O.
Use the following option:
-P, --parameter name=value
Set various parameter limits.
Name Default Explanation
bytes 1048576 max number of bytes to read from file
Something like...
file_to_check="myfile"
bytes_to_scan=$(wc -c < $file_to_check)
file -b --mime-encoding -P bytes=$bytes_to_scan $file_to_check
... it should do the trick if you want to force file
to look at the whole file before making a guess. Of course, this only works if you have file
5.26 or newer.
file
to display UTF-8 instead of US-ASCIISome of the other answers seem to focus on trying to make file
display UTF-8 even if the file only contains plain 7-bit ascii. If you think this through you should probably never want to do this.
file
command is saying the file is UTF-8, that implies that the file contains some characters with UTF-8 specific encoding. If that isn't really true, it could cause confusion or problems down the line. If file
displayed UTF-8 when the file only contained 7-bit ascii characters, this would be a bug in the file
program.file
command output before accepting a file as input and it won't process the file unless it "sees" UTF-8...well that is pretty bad design. I would argue this is a bug in that program.If you absolutely must take a plain 7-bit ascii file and convert it to UTF-8, simply insert a single non-7-bit-ascii character into the file with UTF-8 encoding for that character and you are done. But I can't imagine a use-case where you would need to do this. The easiest UTF-8 character to use for this is the Byte Order Mark (BOM) which is a special non-printing character that hints that the file is non-ascii. This is probably the best choice because it should not visually impact the file contents as it will generally be ignored.
Microsoft compilers and interpreters, and many pieces of software on Microsoft Windows such as Notepad treat the BOM as a required magic number rather than use heuristics. These tools add a BOM when saving text as UTF-8, and cannot interpret UTF-8 unless the BOM is present or the file contains only ASCII.
This is key:
or the file contains only ASCII
So some tools on windows have trouble reading UTF-8 files unless the BOM character is present. However this does not affect plain 7-bit ascii only files. I.e. this is not a reason for forcing plain 7-bit ascii files to be UTF-8 by adding a BOM character.
Here is more discussion about potential pitfalls of using the BOM when not needed (it IS needed for actual UTF-8 files that are consumed by some Microsoft apps). https://stackoverflow.com/a/13398447/3616686
Nevertheless if you still want to do it, I would be interested in hearing your use case. Here is how. In UTF-8 the BOM is represented by hex sequence 0xEF,0xBB,0xBF
and so we can easily add this character to the front of our plain 7-bit ascii file. By adding a non-7-bit ascii character to the file, the file is no longer only 7-bit ascii. Note that we have not modified or converted the original 7-bit-ascii content at all. We have added a single non-7-bit-ascii character to the beginning of the file and so the file is no longer entirely composed of 7-bit-ascii characters.
$ printf '\xEF\xBB\xBF' > bom.txt # put a UTF-8 BOM char in new file
$ file bom.txt
bom.txt: UTF-8 Unicode text, with no line terminators
$ file plain-ascii.txt # our pure 7-bit ascii file
plain-ascii.txt: ASCII text
$ cat bom.txt plain-ascii.txt > plain-ascii-with-utf8-bom.txt # put them together into one new file with the BOM first
$ file plain-ascii-with-utf8-bom.txt
plain-ascii-with-utf8-bom.txt: UTF-8 Unicode (with BOM) text
When user reduces window size horizontally and this causes floats to stack vertically, remove the floats and on the second div (that was a float) use margin-top: -123px (your value) and margin-left: 444px (your value) to position the divs as they appeared with floats. When done this way, when the window narrows, the right-side div stays in place and disappears when page is too narrow to include it. ... which (to me) is better than having the right-side div "jump" down below the left-side div when the browser window is narrowed by the user.
The easiest is Simple there is a tutorial, no WEB-INF not Servlet API no dependencies. Just a simple lightweight HTTP server in a single JAR.
Comma separate the values:
UPDATE settings SET postsPerPage = $postsPerPage, style = $style WHERE id = '1'"
Pointers to classes are not real pointers; a class is a logical construct and has no physical existence in memory, however, when you construct a pointer to a member of a class it gives an offset into an object of the member's class where the member can be found; This gives an important conclusion: Since static members are not associated with any object so a pointer to a member CANNOT point to a static member(data or functions) whatsoever Consider the following:
class x {
public:
int val;
x(int i) { val = i;}
int get_val() { return val; }
int d_val(int i) {return i+i; }
};
int main() {
int (x::* data) = &x::val; //pointer to data member
int (x::* func)(int) = &x::d_val; //pointer to function member
x ob1(1), ob2(2);
cout <<ob1.*data;
cout <<ob2.*data;
cout <<(ob1.*func)(ob1.*data);
cout <<(ob2.*func)(ob2.*data);
return 0;
}
Source: The Complete Reference C++ - Herbert Schildt 4th Edition
To remove the query string from the request URI, replace the query string with an empty string:
function request_uri_without_query() {
$result = $_SERVER['REQUEST_URI'];
$query = $_SERVER['QUERY_STRING'];
if(!empty($query)) {
$result = str_replace('?' . $query, '', $result);
}
return $result;
}
If you don't want the text to wrap and you don't want the size of the column to get bigger then set a width and height on the column and set "overflow: hidden" in your stylesheet.
To do this on only one column you will want to add a class to that column on each row. Otherwise you can set it on all columns, that is up to you.
Html:
<table width="300px">
<tr>
<td>Column 1</td><td>Column 2</td>
</tr>
<tr>
<td class="column-1">this is the text in column one which wraps</td>
<td>this is the column two test</td>
</tr>
</table>
stylsheet:
.column-1
{
overflow: hidden;
width: 150px;
height: 1.2ex;
}
An ex unit is the relative font size for height, if you are using pixels to set the font size you may wish to use that instead.
Use the css property overflow . For example:
.item{
width : 100px;
overflow:hidden;
}
The overflow property can have one of many values like ( hidden , scroll , visible ) .. you can als control the overflow in one direction only using overflow-x or overflow-y.
I hope this helps.
The base of NGLG answer https://stackoverflow.com/a/8811242/6619626 you can use the following function:
type
OurArrayStr=array of string;
function SplitString(DelimeterChars:char;Str:string):OurArrayStr;
var
seg: TStringList;
i:integer;
ret:OurArrayStr;
begin
seg := TStringList.Create;
ExtractStrings([DelimeterChars],[], PChar(Str), seg);
for i:=0 to seg.Count-1 do
begin
SetLength(ret,length(ret)+1);
ret[length(ret)-1]:=seg.Strings[i];
end;
SplitString:=ret;
seg.Free;
end;
It works in all Delphi versions.
Here is a combination of the answer by @Mohsenasm and a comment from @Ghigo adopted to Swift
extension UIView {
var globalFrame: CGRect? {
let rootView = UIApplication.shared.keyWindow?.rootViewController?.view
return self.superview?.convert(self.frame, to: rootView)
}
}
How about that?
function internalHandler(e) {
e.preventDefault(); // required in some browsers
e.returnValue = ""; // required in some browsers
return "Custom message to show to the user"; // only works in old browsers
}
if (window.addEventListener) {
window.addEventListener('beforeunload', internalHandler, true);
} else if (window.attachEvent) {
window.attachEvent('onbeforeunload', internalHandler);
}
>>> any([False, False, False])
False
>>> any([False, True, False])
True
>>> all([False, True, True])
False
>>> all([True, True, True])
True
The real answer to this is to put a @ At symbol before the variable which will suppress the error
@$_GET["field"]
@$_POST["field"]
It will work some slower, but will keep the code clean.
When something saves time for the programmer, and costs time for the website users (or requires more hardware), it depends on how much people will use it.
The accepted answer is good, but it does NOT solve the problem when we need our component to reflect changes in URL.
Say, your component's code is something like:
export const Customer = (props) => {
const history = useHistory();
...
}
And you change URL:
const handleGoToPrev = () => {
history.push(`/app/customer/${prevId}`);
}
import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import store from '../store/store';
export const PrivateRoute = ({ component: Component, ...rest }) => {
let isLoggedIn = !!store.getState().data.user;
return (
<Route {...rest} render={props => isLoggedIn
? (
<Component key={props.match.params.id || 'empty'} {...props} />
) : (
<Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)
} />
)
}
<PrivateRoute exact path="/app/customer/:id" component={Customer} />
You can set up a developer application and set the url to localhost.com:port Make sure to map localhost.com to localhost on your hosts file
Works for me
The GET (and HEAD) method should never be used to do anything that has side-effects. A side-effect might be updating the state of a web application, or it might be charging your credit card. If an action has side-effects another method (POST) should be used instead.
So, a user (or their browser) shouldn't be held accountable for something done by a GET. If some harmful or expensive side-effect occurred as the result of a GET, that would be the fault of the web application, not the user. According to the spec, a user agent must not automatically follow a redirect unless it is a response to a GET or HEAD request.
Of course, a lot of GET requests do have some side-effects, even if it's just appending to a log file. The important thing is that the application, not the user, should be held responsible for those effects.
The relevant sections of the HTTP spec are 9.1.1 and 9.1.2, and 10.3.
For some people, the accepted answer is not working, I found this other answer and it is working for me: How can I pass a parameter to a setTimeout() callback?
var hello = "Hello World";
setTimeout(alert, 1000, hello);
'hello' is the parameter being passed, you can pass all the parameters after the timeout time. Thanks to @Fabio Phms for the answer.
PHP, by default, always returns the following header: "Content-Type: text/html" (notice no charset), therefore you must use
<?php header('Content-type: text/plain; charset=utf-8'); ?>
If you want the second highest number you can use
=LARGE(E4:E9;2)
although that doesn't account for duplicates so you could get the same result as the Max
If you want the largest number that is smaller than the maximum number you can use this version
=LARGE(E4:E9;COUNTIF(E4:E9;MAX(E4:E9))+1)
astype(str)
!Prior to pandas 1.0 (well, 0.25 actually) this was the defacto way of declaring a Series/column as as string:
# pandas <= 0.25
# Note to pedants: specifying the type is unnecessary since pandas will
# automagically infer the type as object
s = pd.Series(['a', 'b', 'c'], dtype=str)
s.dtype
# dtype('O')
From pandas 1.0 onwards, consider using "string"
type instead.
# pandas >= 1.0
s = pd.Series(['a', 'b', 'c'], dtype="string")
s.dtype
# StringDtype
Here's why, as quoted by the docs:
You can accidentally store a mixture of strings and non-strings in an object dtype array. It’s better to have a dedicated dtype.
object
dtype breaks dtype-specific operations likeDataFrame.select_dtypes()
. There isn’t a clear way to select just text while excluding non-text but still object-dtype columns.When reading code, the contents of an
object
dtype array is less clear than'string'
.
See also the section on Behavioral Differences between "string"
and object
.
Extension types (introduced in 0.24 and formalized in 1.0) are closer to pandas than numpy, which is good because numpy types are not powerful enough. For example NumPy does not have any way of representing missing data in integer data (since type(NaN) == float
). But pandas can using Nullable Integer columns.
Accidentally mixing dtypes
The first reason, as outlined in the docs is that you can accidentally store non-text data in object columns.
# pandas <= 0.25
pd.Series(['a', 'b', 1.23]) # whoops, this should have been "1.23"
0 a
1 b
2 1.23
dtype: object
pd.Series(['a', 'b', 1.23]).tolist()
# ['a', 'b', 1.23] # oops, pandas was storing this as float all the time.
# pandas >= 1.0
pd.Series(['a', 'b', 1.23], dtype="string")
0 a
1 b
2 1.23
dtype: string
pd.Series(['a', 'b', 1.23], dtype="string").tolist()
# ['a', 'b', '1.23'] # it's a string and we just averted some potentially nasty bugs.
Challenging to differentiate strings and other python objects
Another obvious example example is that it's harder to distinguish between "strings" and "objects". Objects are essentially the blanket type for any type that does not support vectorizable operations.
Consider,
# Setup
df = pd.DataFrame({'A': ['a', 'b', 'c'], 'B': [{}, [1, 2, 3], 123]})
df
A B
0 a {}
1 b [1, 2, 3]
2 c 123
Upto pandas 0.25, there was virtually no way to distinguish that "A" and "B" do not have the same type of data.
# pandas <= 0.25
df.dtypes
A object
B object
dtype: object
df.select_dtypes(object)
A B
0 a {}
1 b [1, 2, 3]
2 c 123
From pandas 1.0, this becomes a lot simpler:
# pandas >= 1.0
# Convenience function I call to help illustrate my point.
df = df.convert_dtypes()
df.dtypes
A string
B object
dtype: object
df.select_dtypes("string")
A
0 a
1 b
2 c
Readability
This is self-explanatory ;-)
...No. As of writing this answer (version 1.1), there are no performance benefits but the docs expect future enhancements to significantly improve performance and reduce memory usage for "string"
columns as opposed to objects. With that said, however, it's never too early to form good habits!
An inline div is a freak of the web & should be beaten until it becomes a span (at least 9 times out of 10)...
<span>foo</span>
<span>bar</span>
<span>baz</span>
...answers the original question...
You can make any dimension of list
list=[]
n= int(input())
for i in range(0,n) :
#num = input()
list.append(input().split())
print(list)
output:
Probably the closest you can do is
static bool IntegerFunction<T>(T value) where T: struct
Not sure if you could do the following
static bool IntegerFunction<T>(T value) where T: struct, IComparable
, IFormattable, IConvertible, IComparable<T>, IEquatable<T>
For something so specific, why not just have overloads for each type, the list is so short and it would possibly have less memory footprint.
ResourceBundle rb = ResourceBundle.getBundle("service"); //service.properties
System.out.println(rb.getString("server.dns")); //server.dns=http://....
Try this:
var count =0;
$('input[name="radioGroup"]').each(function(){
if (this.checked)
{
count++;
}
});
If any of radio button checked than you will get 1
<li>
s don't have a value
- only form inputs do. In fact, you're not supposed to even include the value
attribute in the HTML for <li>
s.
You can rely on .innerHTML
instead:
getPaging(this.innerHTML)
Or maybe the id
:
getPaging(this.id);
However, it's easier (and better practice) to add the click handlers from JavaScript code, and not include them in the HTML. Seeing as you're already using jQuery, this can easily be done by changing your HTML to:
<li class="clickMe">1</li>
<li class="clickMe">2</li>
And use the following JavaScript:
$(function () {
$('.clickMe').click(function () {
var str = $(this).text();
$('#loading-content').load('dataSearch.php?' + str, hideLoader);
});
});
This will add the same click handler to all your <li class="clickMe">
s, without requiring you to duplicate your onclick="getPaging(this.value)"
code for each of them.
Try string.Remove();
string str = "1,5,12,34,";
string removecomma = str.Remove(str.Length-1);
MessageBox.Show(removecomma);
USE join to get 0 count in the result using GROUP BY.
simply 'join' does Inner join in MS SQL so , Go for left or right join.
If the table which contains the primary key is mentioned first in the QUERY then use LEFT join else RIGHT join.
EG:
select WARDNO,count(WARDCODE) from MAIPADH
right join MSWARDH on MSWARDH.WARDNO= MAIPADH.WARDCODE
group by WARDNO
.
select WARDNO,count(WARDCODE) from MSWARDH
left join MAIPADH on MSWARDH.WARDNO= MAIPADH.WARDCODE group by WARDNO
Take group by from the table which has Primary key and count from the another table which has actual entries/details.
Try this:
MyContext Context = new MyContext();
Context.YourEntity.Add(obj);
Context.SaveChanges();
int ID = obj._ID;
git rm --cached file
will remove the file from the stage. That is, when you commit the file will be removed. git reset HEAD -- file
will simply reset file in the staging area to the state where it was on the HEAD commit, i.e. will undo any changes you did to it since last commiting. If that change happens to be newly adding the file, then they will be equivalent.
To blank it:
myObject["myVar"]=null;
To remove it:
delete myObject["myVar"]
as you can see in duplicate answers
I got it like this
public void onClick(View v){
v.findViewById(R.id.textView).setBackgroundColor(R.drawable.selector_row);
}
Thanks
If you have an image imported as a resource in your project there is also this:
picPreview.Image = Properties.Resources.ImageName;
Where picPreview is the name of the picture box and ImageName is the name of the file you want to display.
*Resources are located by going to: Project --> Properties --> Resources
Another scenario where this shows up is if you are using the older "Web Site" project type in Visual Studio. For that project type, it is unable to reference .dlls that are outside of it's own directory structure (current folder and down). So in the answer above, let's say your directory structure looks like this:
Where ProjectX and ProjectY are parent/child directories, and ProjectX references A.dll which in turn references B.dll, and B.dll is outside the directory structure, such as in a Nuget package on the root (Packages), then A.dll will be included, but B.dll will not.
Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium
If you are using Java, have a look at JDBC.
http://msdn.microsoft.com/en-us/library/ms378672(SQL.90).aspx
Query would be like this:
SELECT ID, AccountID, Quantity,
SUM(Quantity) OVER (PARTITION BY AccountID ) AS TopBorcT
FROM #Empl ORDER BY AccountID
Partition by works like group by. Here we are grouping by AccountID so sum would be corresponding to AccountID.
First first case, AccountID = 1 , then sum(quantity) = 10 + 5 + 2 => 17 & For AccountID = 2, then sum(Quantity) = 7+3 => 10
so result would appear like attached snapshot.
First, you should disable selinux
, edit file /etc/sysconfig/selinux
so it looks like this:
SELINUX=disabled
SELINUXTYPE=targeted
Save file and restart system.
Then you can add the new rule to iptables
:
iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT
and restart iptables with /etc/init.d/iptables restart
If it doesn't work you should check other network settings.
Sometimes it is necessary to load scripts in a specific order. For example jQuery must be loaded before jQuery UI. Most examples on this page load scripts in parallel (asynchronously) which means order of execution is not guaranteed. Without ordering, script y
that depends on x
could break if both are successfully loaded but in wrong order.
I propose a hybrid approach which allows sequential loading of dependent scripts + optional parallel loading + deferred objects:
/*_x000D_
* loads scripts one-by-one using recursion_x000D_
* returns jQuery.Deferred_x000D_
*/_x000D_
function loadScripts(scripts) {_x000D_
var deferred = jQuery.Deferred();_x000D_
_x000D_
function loadScript(i) {_x000D_
if (i < scripts.length) {_x000D_
jQuery.ajax({_x000D_
url: scripts[i],_x000D_
dataType: "script",_x000D_
cache: true,_x000D_
success: function() {_x000D_
loadScript(i + 1);_x000D_
}_x000D_
});_x000D_
} else {_x000D_
deferred.resolve();_x000D_
}_x000D_
}_x000D_
loadScript(0);_x000D_
_x000D_
return deferred;_x000D_
}_x000D_
_x000D_
/*_x000D_
* example using serial and parallel download together_x000D_
*/_x000D_
_x000D_
// queue #1 - jquery ui and jquery ui i18n files_x000D_
var d1 = loadScripts([_x000D_
"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js",_x000D_
"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"_x000D_
]).done(function() {_x000D_
jQuery("#datepicker1").datepicker(jQuery.datepicker.regional.fr);_x000D_
});_x000D_
_x000D_
// queue #2 - jquery cycle2 plugin and tile effect plugin_x000D_
var d2 = loadScripts([_x000D_
"https://cdn.rawgit.com/malsup/cycle2/2.1.6/build/jquery.cycle2.min.js",_x000D_
"https://cdn.rawgit.com/malsup/cycle2/2.1.6/build/plugin/jquery.cycle2.tile.min.js"_x000D_
_x000D_
]).done(function() {_x000D_
jQuery("#slideshow1").cycle({_x000D_
fx: "tileBlind",_x000D_
log: false_x000D_
});_x000D_
});_x000D_
_x000D_
// trigger a callback when all queues are complete_x000D_
jQuery.when(d1, d2).done(function() {_x000D_
console.log("All scripts loaded");_x000D_
});
_x000D_
@import url("https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/blitzer/jquery-ui.min.css");_x000D_
_x000D_
#slideshow1 {_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<p><input id="datepicker1"></p>_x000D_
_x000D_
<div id="slideshow1">_x000D_
<img src="https://dummyimage.com/300x100/FC0/000">_x000D_
<img src="https://dummyimage.com/300x100/0CF/000">_x000D_
<img src="https://dummyimage.com/300x100/CF0/000">_x000D_
</div>
_x000D_
The scripts in both queues will download in parallel, however, the scripts in each queue will download in sequence, ensuring ordered execution. Waterfall chart:
Try this
$("#postcontent").submit(function() {
return false;
};
$('#postsubmit').click(function(){
// your ajax request here
});
If you can convert .xls to .csv before processing, you can use the query below to import the csv to the database:
load data local infile 'FILE.CSV' into table TABLENAME fields terminated by ',' enclosed by '"' lines terminated by '\n' (FIELD1,FIELD2,FIELD3)
The root of the problem is that you are unknowingly using the Frame
class from the ttk
package rather than from the tkinter
package. The one from ttk
does not support the background option.
This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.
I recommend doing imports like this:
import tkinter as tk
import ttk
Then you prefix the widgets with either tk
or ttk
:
f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)
It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.
$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");
HTML 5 with Webforms 2 provides an <input type="range">
which will make the browser generate a native slider for you. Unfortunately all browsers doesn't have support for this, however google has implemented all Webforms 2 controls with js. IIRC the js is intelligent enough to know if the browser has implemented the control, and triggers only if there is no native implementation.
From my point of view it should be considered best practice to use the browsers native controls when possible.
C# Test Coverage Tool has very low overhead, handles huge systems of files, intuitive GUI showing coverage on specific files, and generated report with coverage breakdown at method, class, and package levels.
Simple, easy, and sophisticated. This function will be called in every 1 sec to update time.
const year = (new Date().getFullYear());
const bdayDate = new Date("04,11,2019").getTime(); //mmddyyyy
// countdown
let timer = setInterval(function () {
// get today's date
const today = new Date().getTime();
// get the difference
const diff = bdayDate - today;
// math
let days = Math.floor(diff / (1000 * 60 * 60 * 24));
let hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((diff % (1000 * 60)) / 1000);
}, 1000);
public class SwitchTest {
public static void main(String[] args){
for(int i = 0;i<10;i++){
switch(i){
case 1: case 2: case 3: case 4: //First case
System.out.println("First case");
break;
case 8: case 9: //Second case
System.out.println("Second case");
break;
default: //Default case
System.out.println("Default case");
break;
}
}
}
}
Out:
Default case
First case
First case
First case
First case
Default case
Default case
Default case
Second case
Second case
Src: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
import java.util.*;
class GetCurrentmonth
{
public static void main(String args[])
{
int month;
GregorianCalendar date = new GregorianCalendar();
month = date.get(Calendar.MONTH);
month = month+1;
System.out.println("Current month is " + month);
}
}
Java anonymous class is very similar to Javascript closure, but Java implement that in different way. (check Andersen's answer)
So in order not to confuse the Java Developer with the strange behavior that might occur for those coming from Javascript background. I guess that's why they force us to use final
, this is not the JVM limitation.
Let's look at the Javascript example below:
var add = (function () {
var counter = 0;
var func = function () {
console.log("counter now = " + counter);
counter += 1;
};
counter = 100; // line 1, this one need to be final in Java
return func;
})();
add(); // this will print out 100 in Javascript but 0 in Java
In Javascript, the counter
value will be 100, because there is only one counter
variable from the beginning to end.
But in Java, if there is no final
, it will print out 0
, because while the inner object is being created, the 0
value is copied to the inner class object's hidden properties. (there are two integer variable here, one in the local method, another one in inner class hidden properties)
So any changes after the inner object creation (like line 1), it will not affect the inner object. So it will make confusion between two different outcome and behaviour (between Java and Javascript).
I believe that's why, Java decide to force it to be final, so the data is 'consistent' from the beginning to end.
A Mutex controls access to a single shared resource. It provides operations to acquire() access to that resource and release() it when done.
A Semaphore controls access to a shared pool of resources. It provides operations to Wait() until one of the resources in the pool becomes available, and Signal() when it is given back to the pool.
When number of resources a Semaphore protects is greater than 1, it is called a Counting Semaphore. When it controls one resource, it is called a Boolean Semaphore. A boolean semaphore is equivalent to a mutex.
Thus a Semaphore is a higher level abstraction than Mutex. A Mutex can be implemented using a Semaphore but not the other way around.
The way I typically handle this is with a second piece of software. For Windows I use Notepad++, for OS X I use Sublime Text 2.
java.util.Calendar
Calendar cal = Calendar.getInstance();
// remove next line if you're always using the current time.
cal.setTime(currentDate);
cal.add(Calendar.HOUR, -1);
Date oneHourBack = cal.getTime();
java.util.Date
new Date(System.currentTimeMillis() - 3600 * 1000);
org.joda.time.LocalDateTime
new LocalDateTime().minusHours(1)
Java 8: java.time.LocalDateTime
LocalDateTime.now().minusHours(1)
Java 8 java.time.Instant
// always in UTC if not timezone set
Instant.now().minus(1, ChronoUnit.HOURS));
// with timezone, Europe/Berlin for example
Instant.now()
.atZone(ZoneId.of("Europe/Berlin"))
.minusHours(1));
Check your JAVA_HOME
to use jdk 1.8
Also check : the parameter in Android Studio in order to change at
File->Other Settings->Default Project Structure->SDKs
The code below works for me (thanks to Christopher Zimmermann for his blog post http://dev.magnolia-cms.com/blog/2012/05/strategies-for-the-iframe-on-the-ipad-problem/). The problems are:
The PDF files are not centered (still working on it)
<!DOCTYPE HTML>
<html>
<head>
<title>Testing iFrames on iPad</title>
<style>
div {
border: solid 1px green;
height:100px;
}
.scroller{
border:solid 1px #66AA66;
height: 400px;
width: 400px;
overflow: auto;
text-align:center;
}
</style>
<table>
<tr>
<td><div class="scroller">
<iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
</div>
</td>
<td><div class="scroller">
<iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
</div>
</td>
</tr>
<tr>
<td><div class="scroller">
<iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
</div>
</td>
<td><div class="scroller">
<iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
</div>
</td>
</tr>
</table>
<div> Here are some additional contents.</div>
In my case I was seeing referrals when I was accessing AD via SSO with an account in a trusted domain. The problem went away when I connected with explicit credentials in the local domain.
i.e. I replaced
DirectoryEntry de = new DirectoryEntry("blah.com");
with
DirectoryEntry de = new DirectoryEntry("blah.com", "[email protected]", "supersecret");
and the problem went away.
The details in the comments section above did not work for me (VS 2013) when trying to copy the output dll from one C++ project to the release and debug folder of another C# project within the same solution.
I had to add the following post build-action (right click on the project that has a .dll output) then properties -> configuration properties -> build events -> post-build event -> command line
now I added these two lines to copy the output dll into the two folders:
xcopy /y $(TargetPath) $(SolutionDir)aeiscontroller\bin\Release
xcopy /y $(TargetPath) $(SolutionDir)aeiscontroller\bin\Debug
Just follow these steps i can assure pdf file will be generated
<html>
<head>
<title>Exporting table data to pdf Example</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script type="text/javascript" src="js/jspdf.js"></script>
<script type="text/javascript" src="js/from_html.js"></script>
<script type="text/javascript" src="js/split_text_to_size.js"></script>
<script type="text/javascript" src="js/standard_fonts_metrics.js"></script>
<script type="text/javascript" src="js/cell.js"></script>
<script type="text/javascript" src="js/FileSaver.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#exportpdf").click(function() {
var pdf = new jsPDF('p', 'pt', 'ledger');
// source can be HTML-formatted string, or a reference
// to an actual DOM element from which the text will be scraped.
source = $('#yourTableIdName')[0];
// we support special element handlers. Register them with jQuery-style
// ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
// There is no support for any other type of selectors
// (class, of compound) at this time.
specialElementHandlers = {
// element with id of "bypass" - jQuery style selector
'#bypassme' : function(element, renderer) {
// true = "handled elsewhere, bypass text extraction"
return true
}
};
margins = {
top : 80,
bottom : 60,
left : 60,
width : 522
};
// all coords and widths are in jsPDF instance's declared units
// 'inches' in this case
pdf.fromHTML(source, // HTML string or DOM elem ref.
margins.left, // x coord
margins.top, { // y coord
'width' : margins.width, // max width of content on PDF
'elementHandlers' : specialElementHandlers
},
function(dispose) {
// dispose: object with X, Y of the last line add to the PDF
// this allow the insertion of new lines after html
pdf.save('fileNameOfGeneretedPdf.pdf');
}, margins);
});
});
</script>
</head>
<body>
<div id="yourTableIdName">
<table style="width: 1020px;font-size: 12px;" border="1">
<thead>
<tr align="left">
<th>Country</th>
<th>State</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr>
<tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr><tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr><tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr><tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr><tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr><tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr>
</tbody>
</table></div>
<input type="button" id="exportpdf" value="Download PDF">
</body>
</html>
Output:
Html file output:
Pdf file output:
The error usually means that the port you are trying to open is being already used by another application. Try using netstat to see which ports are open and then use an available port.
Also check if you are binding to the right ip address (I am assuming it would be localhost)
I have researched a lot for cleaning Backstack, and finally see Transaction BackStack and its management. Here is the solution that worked best for me.
// CLEAR BACK STACK.
private void clearBackStack() {
final FragmentManager fragmentManager = getSupportFragmentManager();
while (fragmentManager.getBackStackEntryCount() != 0) {
fragmentManager.popBackStackImmediate();
}
}
The above method loops over all the transactions in the backstack and removes them immediately one at a time.
Note: above code sometime not work and i face ANR because of this code,so please do not try this.
Update below method remove all fregment of that "name" from backstack.
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackStack("name",FragmentManager.POP_BACK_STACK_INCLUSIVE);
Run the app in debug mode and set a breakpoint on if (requestCode == SELECT_PICTURE)
and inspect each variable as you step through to ensure it is being set as expected. If you are getting a NPE on img.setImageURI(selectedImageUri);
then either img
or selectedImageUri
are not set.
To unpack a dictionary into keyword arguments, use **
. Also,, new-style formatting supports referring to attributes of objects and items of mappings:
'{0[latitude]} {0[longitude]}'.format(geopoint)
'The title is {0.title}s'.format(a) # the a from your first example
As @Agam said,
You need this statement in your driver file:
from AthleteList import AtheleteList
If the return
in the try
block is reached, it transfers control to the finally
block, and the function eventually returns normally (not a throw).
If an exception occurs, but then the code reaches a return
from the catch
block, control is transferred to the finally
block and the function eventually returns normally (not a throw).
In your example, you have a return
in the finally
, and so regardless of what happens, the function will return 34
, because finally
has the final (if you will) word.
Although not covered in your example, this would be true even if you didn't have the catch
and if an exception were thrown in the try
block and not caught. By doing a return
from the finally
block, you suppress the exception entirely. Consider:
public class FinallyReturn {
public static final void main(String[] args) {
System.out.println(foo(args));
}
private static int foo(String[] args) {
try {
int n = Integer.parseInt(args[0]);
return n;
}
finally {
return 42;
}
}
}
If you run that without supplying any arguments:
$ java FinallyReturn
...the code in foo
throws an ArrayIndexOutOfBoundsException
. But because the finally
block does a return
, that exception gets suppressed.
This is one reason why it's best to avoid using return
in finally
.
This is the Known limitation in MySQLWorkbench (you can't edit table w/o PK):
Method 1: (method not working in somecases)
right-click on a table within the Object Browser and choose the Edit Table Data option from there.
Method 2:
I would rather suggest you to add Primary Key Instead:
ALTER TABLE `your_table_name` ADD PRIMARY KEY (`column_name`);
and you might want to remove the existing rows first:
Truncate table your_table_name
I've not read through all the solutions, so forgive if this code is redundant.
This is the most thread safe implementation in my opinion.
+(SingletonObject *) sharedManager
{
static SingletonObject * sharedResourcesObj = nil;
@synchronized(self)
{
if (!sharedResourcesObj)
{
sharedResourcesObj = [[SingletonObject alloc] init];
}
}
return sharedResourcesObj;
}
react-router v6
In the upcoming v6, this can be done by combining the useLocation
and useEffect
hooks
import { useLocation } from 'react-router-dom';
const MyComponent = () => {
const location = useLocation()
React.useEffect(() => {
// runs on location, i.e. route, change
console.log('handle route change here', location)
}, [location])
...
}
For convenient reuse, you can do this in a custom useLocationChange
hook
// runs action(location) on location, i.e. route, change
const useLocationChange = (action) => {
const location = useLocation()
React.useEffect(() => { action(location) }, [location])
}
const MyComponent1 = () => {
useLocationChange((location) => {
console.log('handle route change here', location)
})
...
}
const MyComponent2 = () => {
useLocationChange((location) => {
console.log('and also here', location)
})
...
}
If you also need to see the previous route on change, you can combine with a usePrevious
hook
const usePrevious(value) {
const ref = React.useRef()
React.useEffect(() => { ref.current = value })
return ref.current
}
const useLocationChange = (action) => {
const location = useLocation()
const prevLocation = usePrevious(location)
React.useEffect(() => {
action(location, prevLocation)
}, [location])
}
const MyComponent1 = () => {
useLocationChange((location, prevLocation) => {
console.log('changed from', prevLocation, 'to', location)
})
...
}
It's important to note that all the above fire on the first client route being mounted, as well as subsequent changes. If that's a problem, use the latter example and check that a prevLocation
exists before doing anything.
This is described here: https://yarnpkg.com/en/docs/cli/add#toc-adding-dependencies
For example:
yarn add https://github.com/novnc/noVNC.git#0613d18
I had the same problem with absolutely same symptoms… I was about to rebuild my whole system in my despair)).
I even was so naive to try git config --global core.askpass "git-gui--askpass"
as some people suggest here, but it didn't work…
git push
was still freeze…
But then I figured out that there was an error with my SSH agent. So I've restarted ssh-agent and… PROFIT
Conclusion: Always check your SSH Agent and SSHD server when you have troubles with ssh connection… I'm pretty sure that was your problem (And that's why it worked after reinstallation of your system)
With does not work embedded, but it does work consecutive
;WITH A AS(
...
),
B AS(
...
)
SELECT *
FROM A
UNION ALL
SELECT *
FROM B
EDIT Fixed the syntax...
Also, have a look at the following example
Need to apply css as belows:
button:disabled,button[disabled]{
background-color: #cccccc;
cursor:not-allowed !important;
}
The rolling mean returns a Series
you only have to add it as a new column of your DataFrame
(MA
) as described below.
For information, the rolling_mean
function has been deprecated in pandas newer versions. I have used the new method in my example, see below a quote from the pandas documentation.
Warning Prior to version 0.18.0,
pd.rolling_*
,pd.expanding_*
, andpd.ewm*
were module level functions and are now deprecated. These are replaced by using theRolling
,Expanding
andEWM.
objects and a corresponding method call.
df['MA'] = df.rolling(window=5).mean()
print(df)
# Value MA
# Date
# 1989-01-02 6.11 NaN
# 1989-01-03 6.08 NaN
# 1989-01-04 6.11 NaN
# 1989-01-05 6.15 NaN
# 1989-01-09 6.25 6.14
# 1989-01-10 6.24 6.17
# 1989-01-11 6.26 6.20
# 1989-01-12 6.23 6.23
# 1989-01-13 6.28 6.25
# 1989-01-16 6.31 6.27
It's currently working, I've just changed the operator >
in order to work in the snippet, take a look:
window.onload = function() {_x000D_
_x000D_
if (window.location.href.indexOf("test") <= -1) {_x000D_
var search_span = document.getElementsByClassName("securitySearchQuery");_x000D_
search_span[0].style.color = "blue";_x000D_
search_span[0].style.fontWeight = "bold";_x000D_
search_span[0].style.fontSize = "40px";_x000D_
_x000D_
}_x000D_
_x000D_
}
_x000D_
<h1 class="keyword-title">Search results for<span class="securitySearchQuery"> "hi".</span></h1>
_x000D_
package main
import "fmt"
func main() {
nums := []int{2, 3, 4}
for _, num := range nums {
fmt.Println(num, sum)
}
}
You want
$ jar cvf asd.jar .
to specify the directory (e.g. .
) to jar
from. That will maintain your folder structure within the jar file.
I had the same problem as you. I had a long list of arguments, most of which were irrelevant. I didn't want to hard code them in. This is what I came up with
library(magrittr)
do_func_ignore_things <- function(data, what){
acceptable_args <- data[names(data) %in% (formals(what) %>% names)]
do.call(what, acceptable_args %>% as.list)
}
do_func_ignore_things(c(n = 3, hello = 12, mean = -10), "rnorm")
# -9.230675 -10.503509 -10.927077
You can't. Your only option is to divide this into multiple tables and put the form tag outside of it. You could end up nesting your tables, but this is not recommended:
<table>
<tr><td><form>
<table><tr><td>id</td><td>name</td>...</tr></table>
</form></td></tr>
</table>
I would remove the tables entirely and replace it with styled html elements like divs and spans.
It will be better to Create a New role, then grant execute, select ... etc permissions to this role and finally assign users to this role.
Create role
CREATE ROLE [db_SomeExecutor]
GO
Grant Permission to this role
GRANT EXECUTE TO db_SomeExecutor
GRANT INSERT TO db_SomeExecutor
to Add users database>security> > roles > databaseroles>Properties > Add ( bottom right ) you can search AD users and add then
OR
EXEC sp_addrolemember 'db_SomeExecutor', 'domainName\UserName'
Please refer this post
'O' stands for object.
#Loading a csv file as a dataframe
import pandas as pd
train_df = pd.read_csv('train.csv')
col_name = 'Name of Employee'
#Checking the datatype of column name
train_df[col_name].dtype
#Instead try printing the same thing
print train_df[col_name].dtype
The first line returns: dtype('O')
The line with the print statement returns the following: object
Below are two simple query using which you can check index created on a table in Oracle.
select index_name
from dba_indexes
where table_name='&TABLE_NAME'
and owner='&TABLE_OWNER';
select index_name
from user_indexes
where table_name='&TABLE_NAME';
Please check for more details and index size below. Index on a table and its size in Oracle
For folks that have programmed in nodeJs before, particularly using expressJS. I think of .ashx
as a middleware that calls the next
function. While .aspx
will be the controller that actually responds to the request either around res.redirect
, res.send
or whatever.
You can overcome this error in two simple ways
First way
using namespace std;
include <string>
// then you can use string class the normal way
Second way
// after including the class string in your cpp file as follows
include <string>
/*Now when you are using a string class you have to put **std::** before you write
string as follows*/
std::string name; // a string declaration
In my case, there was no code change at all and suddenly one of the servers started getting this and only this exception (all servers have the same code, but only one started having issues):
System.MissingMethodException: Method not found: '?'.
Stack:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at myAccountSearch.AccountSearch.searchtPhone(searchtPhoneRequest request)
at myAccountSearch.AccountSearchClient.myAccountSearch.AccountSearch.searchtPhone(searchtPhoneRequest request)
at myAccountSearch.AccountSearchClient.searchtPhone(String ID, String HashID, searchtPhone Phone1)
at WS.MyValidation(String AccountNumber, String PhoneNumber)
The issue I believe was corrupted AppPool - we have automated AppPool recycling going on every day at 3 am and the issue started at 3 am and then ended on its own at 3 am the next day.
Use a document.ready()
event around your call.
$(document).ready(function () {
$('#memberModal').modal('show');
});
jsFiddle updated - http://jsfiddle.net/uvnggL8w/1/
const double pi = boost::math::constants::pi<double>();
cv::Mat distance2ellipse(cv::Mat image, cv::RotatedRect ellipse){
float distance = 2.0f;
float angle = ellipse.angle;
cv::Point ellipse_center = ellipse.center;
float major_axis = ellipse.size.width/2;
float minor_axis = ellipse.size.height/2;
cv::Point pixel;
float a,b,c,d;
for(int x = 0; x < image.cols; x++)
{
for(int y = 0; y < image.rows; y++)
{
auto u = cos(angle*pi/180)*(x-ellipse_center.x) + sin(angle*pi/180)*(y-ellipse_center.y);
auto v = -sin(angle*pi/180)*(x-ellipse_center.x) + cos(angle*pi/180)*(y-ellipse_center.y);
distance = (u/major_axis)*(u/major_axis) + (v/minor_axis)*(v/minor_axis);
if(distance<=1)
{
image.at<cv::Vec3b>(y,x)[1] = 255;
}
}
}
return image;
}
As far as I know python will compile all modules you "import". However python will NOT compile a python script run using: "python script.py" (it will however compile any modules that the script imports).
The real questions is why you don't want python to compile the modules? You could probably automate a way of cleaning these up if they are getting in the way.
In case you want to deeply iterate into a complex (nested) object for each key & value, you can do so using Object.keys():
const iterate = (obj) => {
Object.keys(obj).forEach(key => {
console.log(`key: ${key}, value: ${obj[key]}`)
if (typeof obj[key] === 'object') {
iterate(obj[key])
}
})
}
It's a blend of coding styles. One school of thought is to preface private members with an underscore to distinguish them.
setBar( int bar)
{
_bar = bar;
}
instead of
setBar( int bar)
{
this.bar = bar;
}
Others will use underscores to indicate a temp local variable that will go out of scope at the end of the method call. (I find this pretty useless - a good method shouldn't be that long, and the declaration is RIGHT THERE! so I know it goes out of scope) Edit: God forbid a programmer from this school and a programmer from the memberData school collaborate! It would be hell.
Sometimes, generated code will preface variables with _ or __. The idea being that no human would ever do this, so it's safe.