I use this class:
public class JsonContent : StringContent
{
public JsonContent(object obj) :
base(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")
{ }
}
Sample of usage:
new HttpClient().PostAsync("http://...", new JsonContent(new { x = 1, y = 2 }));
From Microsoft documentation:
PAGEIOLATCH_SH
Occurs when a task is waiting on a latch for a buffer that is in an
I/O
request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.
In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.
If your query is like this:
Select * from <table> where <col1> = <value> order by <PrimaryKey>
, check that you have a composite index on (col1, col_primary_key)
.
If you don't have one, then you'll need either a full INDEX SCAN
if the PRIMARY KEY
is chosen, or a SORT
if an index on col1
is chosen.
Both of them are very disk I/O
consuming operations on large tables.
Another (!) issue to worry about is the possible change of implementation between early/late versions of Java. I don't believe the implementation details are set in stone, and so potentially an upgrade to a future Java version could cause problems.
Bottom line is, I wouldn't rely on the implementation of hashCode()
.
Perhaps you can highlight what problem you're actually trying to solve by using this mechanism, and that will highlight a more suitable approach.
Another solution is by using .animate() and appropriate CSS.
e.g.
$('#mydiv').animate({ marginLeft: "100%"} , 4000);
I have once written a little SQL*Plus script that uses dbms_sql
and dbms_output
to create a csv (actually an ssv). You can find it on my githup repository.
window.location = myUrl;
Anyway, this is not jQuery: it's plain javascript
In addition to the accepted answer I would like to give an answer that shows how to iterate directly over the Newtonsoft collections. It uses less code and I'm guessing its more efficient as it doesn't involve converting the collections.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//Parse the data
JObject my_obj = JsonConvert.DeserializeObject<JObject>(your_json);
foreach (KeyValuePair<string, JToken> sub_obj in (JObject)my_obj["ADDRESS_MAP"])
{
Console.WriteLine(sub_obj.Key);
}
I started doing this myself because JsonConvert automatically deserializes nested objects as JToken (which are JObject, JValue, or JArray underneath I think).
I think the parsing works according to the following principles:
Every object is abstracted as a JToken
Cast to JObject where you expect a Dictionary
Cast to JValue if the JToken represents a terminal node and is a value
Cast to JArray if its an array
JValue.Value gives you the .NET type you need
sudo service mysql restart
Or
sudo restart mysql
add
SHELL := /bin/bash
at the top of your makefile I have found it on another question How can I use Bash syntax in Makefile targets?
The difference between a shared project and a class library is that the latter is compiled and the unit of reuse is the assembly.
Whereas with the former, the unit of reuse is the source code, and the shared code is incorporated into each assembly that references the shared project.
This can be useful when you want to create separate assemblies that target specific platforms but still have code that should be shared.
See also here:
The shared project reference shows up under the References node in the Solution Explorer, but the code and assets in the shared project are treated as if they were files linked into the main project.
In previous versions of Visual Studio1, you could share source code between projects by Add -> Existing Item and then choosing to Link. But this was kind of clunky and each separate source file had to be selected individually. With the move to supporting multiple disparate platforms (iOS, Android, etc), they decided to make it easier to share source between projects by adding the concept of Shared Projects.
1 This question and my answer (up until now) suggest that Shared Projects was a new feature in Visual Studio 2015. In fact, they made their debut in Visual Studio 2013 Update 2
Only use WOFF2, or if you need legacy support, WOFF. Do not use any other format
(svg
and eot
are dead formats, ttf
and otf
are full system fonts, and should not be used for web purposes)
In short, font-face is very old, but only recently has been supported by more than IE.
eot
is needed for Internet Explorers that are older than IE9 - they invented the spec, but eot was a proprietary solution.
ttf
and otf
are normal old fonts, so some people got annoyed that this meant anyone could download expensive-to-license fonts for free.
Time passes, SVG 1.1 adds a "fonts" chapter that explains how to model a font purely using SVG markup, and people start to use it. More time passes and it turns out that they are absolutely terrible compared to just a normal font format, and SVG 2 wisely removes the entire chapter again.
Then, woff
gets invented by people with quite a bit of domain knowledge, which makes it possible to host fonts in a way that throws away bits that are critically important for system installation, but irrelevant for the web (making people worried about piracy happy) and allows for internal compression to better suit the needs of the web (making users and hosts happy). This becomes the preferred format.
2019 edit A few years later, woff2
gets drafted and accepted, which improves the compression, leading to even smaller files, along with the ability to load a single font "in parts" so that a font that supports 20 scripts can be stored as "chunks" on disk instead, with browsers automatically able to load the font "in parts" as needed, rather than needing to transfer the entire font up front, further improving the typesetting experience.
If you don't want to support IE 8 and lower, and iOS 4 and lower, and android 4.3 or earlier, then you can just use WOFF (and WOFF2, a more highly compressed WOFF, for the newest browsers that support it.)
@font-face {
font-family: 'MyWebFont';
src: url('myfont.woff2') format('woff2'),
url('myfont.woff') format('woff');
}
Support for woff
can be checked at http://caniuse.com/woff
Support for woff2
can be checked at http://caniuse.com/woff2
"o" format is different for DateTime vs DateTimeOffset :(
DateTime.UtcNow.ToString("o") -> "2016-03-09T03:30:25.1263499Z"
DateTimeOffset.UtcNow.ToString("o") -> "2016-03-09T03:30:46.7775027+00:00"
My final answer is
DateTimeOffset.UtcDateTime.ToString("o") //for DateTimeOffset type
DateTime.UtcNow.ToString("o") //for DateTime type
Use psexec -s
The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.
In my scenario this was happening because I renamed a parameter in swagger.yaml
but did not reload the docs page.
Hence I was trying the API with an unexpected input parameter.
Long story short, F5 is my friend.
Make sure your root index.php
file has the correct permission, its permission must be 0755
or 0644
Nowadays people are just using CSS3 transitions because it's a lot easier than messing with JS, browser support is reasonably good and it's merely cosmetic so it doesn't matter if it doesn't work.
Something like this gets the job done:
a {
color:blue;
/* First we need to help some browsers along for this to work.
Just because a vendor prefix is there, doesn't mean it will
work in a browser made by that vendor either, it's just for
future-proofing purposes I guess. */
-o-transition:.5s;
-ms-transition:.5s;
-moz-transition:.5s;
-webkit-transition:.5s;
/* ...and now for the proper property */
transition:.5s;
}
a:hover { color:red; }
You can also transition specific CSS properties with different timings and easing functions by separating each declaration with a comma, like so:
a {
color:blue; background:white;
-o-transition:color .2s ease-out, background 1s ease-in;
-ms-transition:color .2s ease-out, background 1s ease-in;
-moz-transition:color .2s ease-out, background 1s ease-in;
-webkit-transition:color .2s ease-out, background 1s ease-in;
/* ...and now override with proper CSS property */
transition:color .2s ease-out, background 1s ease-in;
}
a:hover { color:red; background:yellow; }
You have a block element (div) inside an inline element (a). This works in HTML 5, but not HTML 4. Thus also only browsers that actually support HTML 5.
When browsers encounter invalid markup, they will try to fix it, but different browsers will do that in different ways, so the result varies. Some browsers will move the block element outside the inline element, some will ignore it.
In my case, I had the same error when I run the app in kitkat API 19 version device. I figured out the problem; I had some drawable resources which was in the drawable-v21 directory (Which is used for versions from API 21 Lollipop). I just put the same resources in the "Drawable" folder to work with the version below API 21. It works. You can put it on the corresponding directory
PowerShell comes with a built in command for it. So running directly from a .bat
file:
powershell -ExecutionPolicy ByPass -Command Send-MailMessage ^
-SmtpServer server.address.name ^
-To [email protected] ^
-From [email protected] ^
-Subject Testing ^
-Body 123
NB -ExecutionPolicy ByPass
is only needed if you haven't set up permissions for running PS from CMD
Also for those looking to call it from within powershell, drop everything before -Command
[inclusive], and `
will be your escape character (not ^
)
Tk is available for Ruby. Some nice examples (in Ruby, Perl and Tcl) can be found at http://www.tkdocs.com/
This kind of code perhaps should work for You
SELECT
*,
CASE
WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
ELSE '00'
END AS modifiedpvc
FROM my_table;
gid | datepose | pvc | modifiedpvc
-----+----------+-----+-------------
1 | 1961 | 01 | 00
2 | 1949 | | 01
3 | 1990 | 02 | 00
1 | 1981 | | 02
1 | | 03 | 00
1 | | | 03
(6 rows)
length
and dbms_lob.getlength
return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength
will return the number of bytes, which may differ from the number of characters in a multi-byte character set.
As the documentation doesn't specify what happens when you apply length
on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength
.
This didn't work for me, as it went too far up the tree, and got the absolute root window for the entire application:
Window parentWindow = Window.GetWindow(userControlReference);
However, this worked to get the immediate window:
DependencyObject parent = uiElement;
int avoidInfiniteLoop = 0;
while ((parent is Window)==false)
{
parent = VisualTreeHelper.GetParent(parent);
avoidInfiniteLoop++;
if (avoidInfiniteLoop == 1000)
{
// Something is wrong - we could not find the parent window.
break;
}
}
Window window = parent as Window;
window.DragMove();
The first method passes n
by value, i.e. a copy of n
is sent to the function. The second one passes n
by reference which basically means that a pointer to the n
with which the function is called is sent to the function.
For integral types like int
it doesn't make much sense to pass as a const reference since the size of the reference is usually the same as the size of the reference (the pointer). In the cases where making a copy is expensive it's usually best to pass by const reference.
import sys
for x in range(10000):
print "HAPPY >> %s <<\r" % str(x),
sys.stdout.flush()
Another reason why people might struggle to get Syntax Highlighting working is because they don't have the appropriate syntax package installed. While some default syntax packages come pre-installed (like Swift, C, JS, CSS), others may not be available.
To solve this you can Cmd + Shift + P ? "install Extensions" and look for the language you want to add, say "Scala".
Find the suitable Syntax package, install it and reload. This will pick up the correct syntax for your files with the predefined extension, i.e. .scala
in this case.
On top of that you might want VS Code to treat all files with certain custom extensions as your preferred language of choice. Let's say you want to highlight all *.es
files as JavaScript, then just open "User Settings" (Cmd + Shift + P ? "User Settings") and configure your custom files association like so:
"files.associations": {
"*.es": "javascript"
},
The problem is in your playerMovement
method. You are creating the string name of your room variables (ID1
, ID2
, ID3
):
letsago = "ID" + str(self.dirDesc.values())
However, what you create is just a str
. It is not the variable. Plus, I do not think it is doing what you think its doing:
>>>str({'a':1}.values())
'dict_values([1])'
If you REALLY needed to find the variable this way, you could use the eval
function:
>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'
or the globals
function:
class Foo(object):
def __init__(self):
super(Foo, self).__init__()
def test(self, name):
print(globals()[name])
foo = Foo()
bar = 'Hello World!'
foo.text('bar')
However, instead I would strongly recommend you rethink you class(es). Your userInterface
class is essentially a Room
. It shouldn't handle player movement. This should be within another class, maybe GameManager
or something like that.
Solution if literals are involved.
I am using Pentaho Data Integration and dont get to specify the sql syntax. Using a very simple DB lookup gave the error "Illegal mix of collations (cp850_general_ci,COERCIBLE) and (latin1_swedish_ci,COERCIBLE) for operation '='"
The generated code was "SELECT DATA_DATE AS latest_DATA_DATE FROM hr_cc_normalised_data_date_v WHERE PSEUDO_KEY = ?"
Cutting the story short the lookup was to a view and when I issued
mysql> show full columns from hr_cc_normalised_data_date_v;
+------------+------------+-------------------+------+-----+
| Field | Type | Collation | Null | Key |
+------------+------------+-------------------+------+-----+
| PSEUDO_KEY | varchar(1) | cp850_general_ci | NO | |
| DATA_DATE | varchar(8) | latin1_general_cs | YES | |
+------------+------------+-------------------+------+-----+
which explains where the 'cp850_general_ci' comes from.
The view was simply created with 'SELECT 'X',......' According to the manual literals like this should inherit their character set and collation from server settings which were correctly defined as 'latin1' and 'latin1_general_cs' as this clearly did not happen I forced it in the creation of the view
CREATE OR REPLACE VIEW hr_cc_normalised_data_date_v AS
SELECT convert('X' using latin1) COLLATE latin1_general_cs AS PSEUDO_KEY
, DATA_DATE
FROM HR_COSTCENTRE_NORMALISED_mV
LIMIT 1;
now it shows latin1_general_cs for both columns and the error has gone away. :)
The usual answer to this is "use a DocumentListener
". However, I always find that interface cumbersome. Truthfully the interface is over-engineered. It has three methods, for insertion, removal, and replacement of text, when it only needs one method: replacement. (An insertion can be viewed as a replacement of no text with some text, and a removal can be viewed as a replacement of some text with no text.)
Usually all you want is to know is when the text in the box has changed, so a typical DocumentListener
implementation has the three methods calling one method.
Therefore I made the following utility method, which lets you use a simpler ChangeListener
rather than a DocumentListener
. (It uses Java 8's lambda syntax, but you can adapt it for old Java if needed.)
/**
* Installs a listener to receive notification when the text of any
* {@code JTextComponent} is changed. Internally, it installs a
* {@link DocumentListener} on the text component's {@link Document},
* and a {@link PropertyChangeListener} on the text component to detect
* if the {@code Document} itself is replaced.
*
* @param text any text component, such as a {@link JTextField}
* or {@link JTextArea}
* @param changeListener a listener to receieve {@link ChangeEvent}s
* when the text is changed; the source object for the events
* will be the text component
* @throws NullPointerException if either parameter is null
*/
public static void addChangeListener(JTextComponent text, ChangeListener changeListener) {
Objects.requireNonNull(text);
Objects.requireNonNull(changeListener);
DocumentListener dl = new DocumentListener() {
private int lastChange = 0, lastNotifiedChange = 0;
@Override
public void insertUpdate(DocumentEvent e) {
changedUpdate(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
changedUpdate(e);
}
@Override
public void changedUpdate(DocumentEvent e) {
lastChange++;
SwingUtilities.invokeLater(() -> {
if (lastNotifiedChange != lastChange) {
lastNotifiedChange = lastChange;
changeListener.stateChanged(new ChangeEvent(text));
}
});
}
};
text.addPropertyChangeListener("document", (PropertyChangeEvent e) -> {
Document d1 = (Document)e.getOldValue();
Document d2 = (Document)e.getNewValue();
if (d1 != null) d1.removeDocumentListener(dl);
if (d2 != null) d2.addDocumentListener(dl);
dl.changedUpdate(null);
});
Document d = text.getDocument();
if (d != null) d.addDocumentListener(dl);
}
Unlike with adding a listener directly to the document, this handles the (uncommon) case that you install a new document object on a text component. Additionally, it works around the problem mentioned in Jean-Marc Astesana's answer, where the document sometimes fires more events than it needs to.
Anyway, this method lets you replace annoying code which looks like this:
someTextBox.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
doSomething();
}
@Override
public void removeUpdate(DocumentEvent e) {
doSomething();
}
@Override
public void changedUpdate(DocumentEvent e) {
doSomething();
}
});
With:
addChangeListener(someTextBox, e -> doSomething());
Code released to public domain. Have fun!
Add the below theme in values -> style.xml
<style name="Theme_Dialog" parent="android:Theme.Light">
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
</style>
Use this theme in your onCreateDialog
method like this:
Dialog dialog = new Dialog(FlightBookActivity.this,R.style.Theme_Dialog);
Define your dialog layout including title bar in the xml file and set that xml file like this:
dialog.setContentView(R.layout.your_dialog_layout);
An include is just like a code insertion. You get in your included code the exact same variables you have in your base code. So you can do this in your main file :
<?
if ($condition == true)
{
$id = 12345;
include 'myFile.php';
}
?>
And in "myFile.php" :
<?
echo 'My id is : ' . $id . '!';
?>
This will output :
My id is 12345 !
I don't see anything immediately obvious as to what would cause a segmentation fault. My only suspicion is that your code expects to get a filename as a parameter when you run it, but if you don't pass it, it will attempt to reference one, anyway.
Accessing argv[1]
when it doesn't exist would cause a segmentation fault. It's generally good practice to check the number of arguments before trying to reference them. You can do this by using the following function prototype for main()
, and checking that argc
is greater than 1 (simply, it will indicate the number entries in argv).
int main(int argc, char** argv)
The best way to figure out what causes a segfault in general is to use a debugger. If you're in Visual Studio, put a breakpoint at the top of your main function and then choose Run with debugging instead of "Run without debugging" when you start the program. It will stop execution at the top, and let you step line-by-line until you see a problem.
If you're in Linux, you can just grab the core file (it will have "core" in the name) and load that with gdb
(GNU Debugger). It can give you a stack dump which will point you straight to the line that caused the segmentation fault to occur.
EDIT: I see you changed your question and code. So this answer probably isn't useful anymore, but I'll leave it as it's good advice anyway, and see if I can address the modified question, shortly).
If you are using eclipse plugin, double click on the app-name in My Heroku Applications. In Processes tab, press Scale Button. A small window will pop-up. Increase/decrease the count and just say OK.
Standard Unix exit codes are defined by sysexits.h, as another poster mentioned. The same exit codes are used by portable libraries such as Poco - here is a list of them:
http://pocoproject.org/docs/Poco.Util.Application.html#16218
A signal 11 is a SIGSEGV (segment violation) signal, which is different from a return code. This signal is generated by the kernel in response to a bad page access, which causes the program to terminate. A list of signals can be found in the signal man page (run "man signal").
You can use this:
Range("MyTable[#Data]").Rows.Count
You have to distinguish between a table which has either one row of data or no data, as the previous code will return "1" for both cases. Use this to test for an empty table:
If WorksheetFunction.CountA(Range("MyTable[#Data]"))
The string.isalpha()
function will work for you.
In my case, I was using Relative Layout
for a emptyString
After struggling on this for an hour. Only this worked for me:
android:layout_toRightOf="@id/welcome"
android:layout_toEndOf="@id/welcome"
android:layout_alignBaseline="@id/welcome"
layout_toRightOf
or layout_toEndOf
both works, but to support it better, I used both.
To make it more clear:
This was what I was trying to do:
And this was the emulator's output
Layout:
<TextView
android:id="@+id/welcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="Welcome "
android:textSize="16sp" />
<TextView
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@id/welcome"
android:layout_toRightOf="@id/welcome"
android:text="@string/emptyString"
android:textSize="16sp" />
Notice that:
android:layout_width="wrap_content"
worksGravity
is not usedI wrote this function:
public static String encode(@NonNull String uriString) {
if (TextUtils.isEmpty(uriString)) {
Assert.fail("Uri string cannot be empty!");
return uriString;
}
// getQueryParameterNames is not exist then cannot iterate on queries
if (Build.VERSION.SDK_INT < 11) {
return uriString;
}
// Check if uri has valid characters
// See https://tools.ietf.org/html/rfc3986
Pattern allowedUrlCharacters = Pattern.compile("([A-Za-z0-9_.~:/?\\#\\[\\]@!$&'()*+,;" +
"=-]|%[0-9a-fA-F]{2})+");
Matcher matcher = allowedUrlCharacters.matcher(uriString);
String validUri = null;
if (matcher.find()) {
validUri = matcher.group();
}
if (TextUtils.isEmpty(validUri) || uriString.length() == validUri.length()) {
return uriString;
}
// The uriString is not encoded. Then recreate the uri and encode it this time
Uri uri = Uri.parse(uriString);
Uri.Builder uriBuilder = new Uri.Builder()
.scheme(uri.getScheme())
.authority(uri.getAuthority());
for (String path : uri.getPathSegments()) {
uriBuilder.appendPath(path);
}
for (String key : uri.getQueryParameterNames()) {
uriBuilder.appendQueryParameter(key, uri.getQueryParameter(key));
}
String correctUrl = uriBuilder.build().toString();
return correctUrl;
}
Below is example to call synchronously but you can easily change to async by using await-sync:
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("login", "abc")
};
var content = new FormUrlEncodedContent(pairs);
var client = new HttpClient {BaseAddress = new Uri("http://localhost:6740")};
// call sync
var response = client.PostAsync("/api/membership/exist", content).Result;
if (response.IsSuccessStatusCode)
{
}
all(getattr(someTime,x)==getattr(today(),x) for x in ['year','month','day'])
One should compare using .date()
, but I leave this method as an example in case one wanted to, for example, compare things by month or by minute, etc.
I think the most elegant solution is to pass a lambda function to "type", as mentioned by Chepner. In addition to this, if you do not know beforehand what the delimiter of your list will be, you can also pass multiple delimiters to re.split:
# python3 test.py -l "abc xyz, 123"
import re
import argparse
parser = argparse.ArgumentParser(description='Process a list.')
parser.add_argument('-l', '--list',
type=lambda s: re.split(' |, ', s),
required=True,
help='comma or space delimited list of characters')
args = parser.parse_args()
print(args.list)
# Output: ['abc', 'xyz', '123']
This javascript is nice that it doesn't open a new window or tab.
window.location.assign(url);
You can use two elements, one inside the other, and give the outer one overflow: hidden
and a width equal to the inner element together with a bottom padding so that the shadow on all the other sides are "cut off"
#outer {
width: 100px;
overflow: hidden;
padding-bottom: 10px;
}
#outer > div {
width: 100px;
height: 100px;
background: orange;
-moz-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
-webkit-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
}
Alternatively, float the outer element to cause it to shrink to the size of the inner element. See: http://jsfiddle.net/QJPd5/1/
As Rahul stated, it is a common Chrome and an OSX bug. I was having similar issues in the past. In fact I finally got tired of making the 2 [yes I know it is not many] additional clicks when testing a local site for work.
As for a possible workaround to this issue [using Windows], I would using one of the many self signing certificate utilities available.
Recommended Steps:
Use the Calendar-API:
// get Calendar instance
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
// substract 7 days
// If we give 7 there it will give 8 days back
cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)-6);
// convert to date
Date myDate = cal.getTime();
Hope this helps. Have Fun!
You can use simple date format in Java using the code below
SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy");
Date newDate = new Date();
String expectedDate= simpledatafo.format(newDate);
Here is code support your question is_char() check for validate string count those strings alone, Hashmap is dictionary in python
def is_word(word):
cnt =0
for c in word:
if 'a' <= c <='z' or 'A' <= c <= 'Z' or '0' <= c <= '9' or c == '$':
cnt +=1
if cnt==len(word):
return True
return False
def words_freq(s):
d={}
for i in s.split():
if is_word(i):
if i in d:
d[i] +=1
else:
d[i] = 1
return d
print(words_freq('the the sky$ is blue not green'))
Have you tried loading the socket.io script not from a relative URL?
You're using:
<script src="socket.io/socket.io.js"></script>
And:
socket.connect('http://127.0.0.1:8080');
You should try:
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
And:
socket.connect('http://localhost:8080');
Switch localhost:8080
with whatever fits your current setup.
Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).
typeof null; // object
typeof undefined; // undefined
The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.
var x = null;
var y;
x is declared & defined as null
y is declared but not defined. It is declared with no value so it is undefined.
z is not declared so would also be undefined if you attempted to use z.
if you have "scattered" (not inside an array) values you can use:
var max_value = Math.max(val1, val2, val3, val4, val5);
There are five common ways by which a class data store data that cannot be modified outside the storing class' control:
Because strings are of variable length, they cannot be value-type primitives, nor can their character data be stored in a struct. Among the remaining choices, the only one which wouldn't require that strings' character data be stored in some kind of immutable object would be #5. While it would be possible to design a framework around option #5, that choice would require that any code which wanted a copy of a string that couldn't be changed outside its control would have to make a private copy for itself. While it hardly be impossible to do that, the amount of extra code required to do that, and the amount of extra run-time processing necessary to make defensive copies of everything, would far outweigh the slight benefits that could come from having string
be mutable, especially given that there is a mutable string type (System.Text.StringBuilder
) which accomplishes 99% of what could be accomplished with a mutable string
.
I think I can illustrate this quite nicely. Since nextTick
is called at the end of the current operation, calling it recursively can end up blocking the event loop from continuing. setImmediate
solves this by firing in the check phase of the event loop, allowing event loop to continue normally.
+-----------------------+
+->¦ timers ¦
¦ +-----------------------+
¦ +-----------------------+
¦ ¦ I/O callbacks ¦
¦ +-----------------------+
¦ +-----------------------+
¦ ¦ idle, prepare ¦
¦ +-----------------------+ +---------------+
¦ +-----------------------+ ¦ incoming: ¦
¦ ¦ poll ¦<-----¦ connections, ¦
¦ +-----------------------+ ¦ data, etc. ¦
¦ +-----------------------+ +---------------+
¦ ¦ check ¦
¦ +-----------------------+
¦ +-----------------------+
+--¦ close callbacks ¦
+-----------------------+
source: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/
Notice that the check phase is immediately after the poll phase. This is because the poll phase and I/O callbacks are the most likely places your calls to setImmediate
are going to run. So ideally most of those calls will actually be pretty immediate, just not as immediate as nextTick
which is checked after every operation and technically exists outside of the event loop.
Let's take a look at a little example of the difference between setImmediate
and process.nextTick
:
function step(iteration) {
if (iteration === 10) return;
setImmediate(() => {
console.log(`setImmediate iteration: ${iteration}`);
step(iteration + 1); // Recursive call from setImmediate handler.
});
process.nextTick(() => {
console.log(`nextTick iteration: ${iteration}`);
});
}
step(0);
Let's say we just ran this program and are stepping through the first iteration of the event loop. It will call into the step
function with iteration zero. It will then register two handlers, one for setImmediate
and one for process.nextTick
. We then recursively call this function from the setImmediate
handler which will run in the next check phase. The nextTick
handler will run at the end of the current operation interrupting the event loop, so even though it was registered second it will actually run first.
The order ends up being: nextTick
fires as current operation ends, next event loop begins, normal event loop phases execute, setImmediate
fires and recursively calls our step
function to start the process all over again. Current operation ends, nextTick
fires, etc.
The output of the above code would be:
nextTick iteration: 0
setImmediate iteration: 0
nextTick iteration: 1
setImmediate iteration: 1
nextTick iteration: 2
setImmediate iteration: 2
nextTick iteration: 3
setImmediate iteration: 3
nextTick iteration: 4
setImmediate iteration: 4
nextTick iteration: 5
setImmediate iteration: 5
nextTick iteration: 6
setImmediate iteration: 6
nextTick iteration: 7
setImmediate iteration: 7
nextTick iteration: 8
setImmediate iteration: 8
nextTick iteration: 9
setImmediate iteration: 9
Now let's move our recursive call to step
into our nextTick
handler instead of the setImmediate
.
function step(iteration) {
if (iteration === 10) return;
setImmediate(() => {
console.log(`setImmediate iteration: ${iteration}`);
});
process.nextTick(() => {
console.log(`nextTick iteration: ${iteration}`);
step(iteration + 1); // Recursive call from nextTick handler.
});
}
step(0);
Now that we have moved the recursive call to step
into the nextTick
handler things will behave in a different order. Our first iteration of the event loop runs and calls step
registering a setImmedaite
handler as well as a nextTick
handler. After the current operation ends our nextTick
handler fires which recursively calls step
and registers another setImmediate
handler as well as another nextTick
handler. Since a nextTick
handler fires after the current operation, registering a nextTick
handler within a nextTick
handler will cause the second handler to run immediately after the current handler operation finishes. The nextTick
handlers will keep firing, preventing the current event loop from ever continuing. We will get through all our nextTick
handlers before we see a single setImmediate
handler fire.
The output of the above code ends up being:
nextTick iteration: 0
nextTick iteration: 1
nextTick iteration: 2
nextTick iteration: 3
nextTick iteration: 4
nextTick iteration: 5
nextTick iteration: 6
nextTick iteration: 7
nextTick iteration: 8
nextTick iteration: 9
setImmediate iteration: 0
setImmediate iteration: 1
setImmediate iteration: 2
setImmediate iteration: 3
setImmediate iteration: 4
setImmediate iteration: 5
setImmediate iteration: 6
setImmediate iteration: 7
setImmediate iteration: 8
setImmediate iteration: 9
Note that had we not interrupted the recursive call and aborted it after 10 iterations then the nextTick
calls would keep recursing and never letting the event loop continue to the next phase. This is how nextTick
can become blocking when used recursively whereas setImmediate
will fire in the next event loop and setting another setImmediate
handler from within one won't interrupt the current event loop at all, allowing it to continue executing phases of the event loop as normal.
Hope that helps!
PS - I agree with other commenters that the names of the two functions could easily be swapped since nextTick
sounds like it's going to fire in the next event loop rather than the end of the current one, and the end of the current loop is more "immediate" than the beginning of the next loop. Oh well, that's what we get as an API matures and people come to depend on existing interfaces.
I know this is an old question, but maybe I can be of help to someone, bc this also stumped me until I read the documentation a bit more:
prevArrow string (html|jQuery selector) | object (DOM node|jQuery object) Previous Allows you to select a node or customize the HTML for the "Previous" arrow.
nextArrow string (html|jQuery selector) | object (DOM node|jQuery object) Next Allows you to select a node or customize the HTML for the "Next" arrow.
this is how i changed my buttons.. worked perfectly.
$('.carousel-content').slick({
prevArrow:"<img class='a-left control-c prev slick-prev' src='../images/shoe_story/arrow-left.png'>",
nextArrow:"<img class='a-right control-c next slick-next' src='../images/shoe_story/arrow-right.png'>"
});
Looks like the solution is to set the value of the properties inside the default constructor. So in this case the java class is:
class JavaObject {
public JavaObject() {
optionalMember = "Value";
}
@NotNull
public String notNullMember;
public String optionalMember;
}
After the mapping with Jackson, if the optionalMember
is missing from the JSON its value in the Java class is "Value"
.
However, I am still interested to know if there is a solution with annotations and without the default constructor.
try to use unix4j. it s about a library in java to run linux command. for instance if you got a command like: cat test.txt | grep "Tuesday" | sed "s/kilogram/kg/g" | sort in this program will become: Unix4j.cat("test.txt").grep("Tuesday").sed("s/kilogram/kg/g").sort();
If you need a dynamic array of objects that are not copy-constructible, then a smart pointer to an array is the way to go. For example, what if you need an array of atomics.
You can also do the following. in your form class def:
max_number = forms.ChoiceField(widget = forms.Select(),
choices = ([('1','1'), ('2','2'),('3','3'), ]), initial='3', required = True,)
then when calling the form in your view you can dynamically set both initial choices and choice list.
yourFormInstance = YourFormClass()
yourFormInstance.fields['max_number'].choices = [(1,1),(2,2),(3,3)]
yourFormInstance.fields['max_number'].initial = [1]
Note: the initial values has to be a list and the choices has to be 2-tuples, in my example above i have a list of 2-tuples. Hope this helps.
I am a VIMer. I can do some rare Hex edits with:
:%!xxd
to switch into hex mode
:%!xxd -r
to exit from hex mode
But I strongly recommend ht
apt-cache show ht
Package: ht
Version: 2.0.18-1
Installed-Size: 1780
Maintainer: Alexander Reichle-Schmehl <[email protected]>
Homepage: http://hte.sourceforge.net/
Note: The package is called ht
, whereas the executable is named hte
after the package was installed.
Simply with command line:
javac MyApp.java
jar -cf myJar.jar MyApp.class
Sure IDEs avoid using command line terminal
if you are in dev mode with not valid certificate, why not just set weClient.setUseInsecureSSL(true)
. works for me
On this web page, I see that:
"Remember that the dot is not a metacharacter inside a character class, so we do not need to escape it with a backslash."
So I guess the escaping of it is unnecessary...
'Date' is your index so you want to do,
print (df.index.min())
print (df.index.max())
2014-03-13 00:00:00
2014-03-31 00:00:00
In order to query a table for the number of rows in that table, you want your query to be as efficient as possible. Reference.
Use something like this:
/**
* Query the Number of Entries in a Sqlite Table
* */
public long QueryNumEntries()
{
SQLiteDatabase db = this.getReadableDatabase();
return DatabaseUtils.queryNumEntries(db, "table_name");
}
Because I know it's possible in while conditions, but I'm not sure if I'm doing it wrong for the if-statement or if it's just not possible.
HINT: what type while and if condition should be ??
If it can be done with while, it can be done with if statement as weel, as both of them expect a boolean condition.
THIS DOES NOT FORCE APPLICATION TO WORK AS ADMINISTRATOR.
This is a simplified version of the this answer, above by @NG
public bool IsUserAdministrator()
{
try
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch
{
return false;
}
}
In case you had enabled 2-Step verification for your Microsoft account disable it when updating the VS License using the 'Check for Updated License' option provided in the window.
You have installed the library in a non-standard location ($HOME/zlib/
). That means the compiler will not know where your header files are and you need to tell the compiler that.
You can add a path to the list that the compiler uses to search for header files by using the -I
(upper-case i) option.
Also note that the LD_LIBRARY_PATH
is for the run-time linker and loader, and is searched for dynamic libraries when attempting to run an application. To add a path for the build-time linker use the -L
option.
All-together the command line should look like
$ c++ -I$HOME/zlib/include some_file.cpp -L$HOME/zlib/lib -lz
cast(str_column as int)
you can use css property to hide style="display:none;"
<div style="display:none;">CREDITS_HERE</div>
Your secondNumber seems to be an ivar, so you have to use a local var to unwrap the optional. And careful. You don't test secondNumber for 0, which can lead into a division by zero. Technically you need another case to handle an impossible operation. For instance checkin if the number is 0 and do nothing in that case would at least not crash.
@IBAction func equals(sender: AnyObject) {
guard let number = Screen.text?.toInt(), number > 0 else {
return
}
secondNumber = number
if operation == "+"{
result = firstNumber + secondNumber
}
else if operation == "-" {
result = firstNumber - secondNumber
}
else if operation == "x" {
result = firstNumber * secondNumber
}
else {
result = firstNumber / secondNumber
}
Screen.text = "\(result)"
}
When I paste code into Outlook or have sentences containing code or technical syntax I get annoyed by all of the red squiggles that identify spelling errors. If you want Outlook to clear all of the red spellcheck squiggles you can add a button to the Quick Access Toolbar that calls a VBA macro and removes all squiggles from the current document.
I prefer to run this macro separate from my style choice because I often use it on a selection of text that has mixed content.
For syntax highlighting I use the Notepad++ technique already listed by @srujanreddy, though I discovered that the right-click context menu option a bit handier than navigating the Plugins menu.
If you get annoyed by spell check while you are preparing your email you can add a button to your quick access toolbar that will remove the red squiggles from the message body.
See this article: https://stackoverflow.com/a/49865743/1898524
// Return today's date and time
var currentTime = new Date()
// returns the month (from 0 to 11)
var month = currentTime.getMonth() + 1
// returns the day of the month (from 1 to 31)
var day = currentTime.getDate()
// returns the year (four digits)
var year = currentTime.getFullYear()
// write output MM/dd/yyyy
document.write(month + "/" + day + "/" + year)
use following to send json
final JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("key", "value");
} catch (JSONException e){
e.printStackTrace();
}
RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),(jsonBody).toString());
and pass it to url
@Body RequestBody key
Whilst the listed answer is correct, may I suggest that if your column is to hold case sensitive strings you read the documentation and alter your table definition accordingly.
In my case this amounted to defining my column as:
`tag` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT ''
This is in my opinion preferential to adjusting your queries.
stdclass is a way in which the php avoid stopping interpreting the script when there is some data must be put in a class , but unfortunately this class was not defined
Example :
return $statement->fetchAll(PDO::FETCH_CLASS , 'Tasks');
Here the data will be put in the predefined 'Tasks' . But, if we did the code as this :
return $statement->fetchAll(PDO::FETCH_CLASS );
then the php will put the results in stdclass .
simply php says that : look , we have a good KIDS[Objects] Here but without Parents . So , we will send them to a infant child Care Home stdclass :)
You can also try the HTTP Debugger, it has the built-in ability to display incoming HTTP requests and does not require any changes to the system configuration.
This will open a second cmd.exe window. If you want it to go away, replace the /K with /C.
Obviously, replace new_file_loc with whatever your new file location will be.
@echo off
for /F %%i in ('dir /B /O:-D *.txt') do (
call :open "%%i"
exit /B 0
)
:open
start "window title" "cmd /K copy %~1 new_file_loc"
exit /B 0
Easiest way which I've found, supports all android versions
Arrays.sort(series1Numbers);
int maxSeries = Integer.parseInt(String.valueOf(series1Numbers[series1Numbers.length-1]));
ZoomX — Android Logger Interceptor is a great interceptor can help you to solve your problem.
<script type="text/javascript">
document.getElementById('button1').onChange = function () {
document.getElementById('hidden_field_id').value = document.getElementById('span_id').innerHTML;
}
</script>
So, after update I had the same issue. I was using PEM key_file
without extension and simply adding .pem
fixed my issue. Now the file is key_file.pem
.
We can also use ReentrantLock to achieve the synchronization for static variables.
public class Test {
private static int count = 0;
private static final ReentrantLock reentrantLock = new ReentrantLock();
public void foo() {
reentrantLock.lock();
count = count + 1;
reentrantLock.unlock();
}
}
if ($elem.parents('.left').length) {
}
The best solution I have found is to load an empty page in the OnReceivedError event like this:
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
view.loadUrl("about:blank");
}
From MSDN:
Top-level types, which are not nested in other types, can only have internal
or public
accessibility. The default accessibility for these types is internal
.
Source: Accessibility Levels (C# Reference) (December 6th, 2017)
Assuming you use VS Express and C#. The icon is set in the project properties page. To open it right click on the project name in the solution explorer. in the page that opens, there is an Application tab, in this tab you can set the icon.
To add to already great and easy solution provided by Przemek315, the same config if you use Kotlin DSL:
tasks.test {
useJUnitPlatform()
}
There are several ways to do this. Having a container around the radio buttons is highly recommended regardless, but you can also put a class directly on the buttons. With this HTML:
<ul id="shapeList" class="radioList">
<li><label>Shape:</label></li>
<li><input id="shapeList_0" class="shapeButton" type="radio" value="Circular" name="shapeList" /><label for="shapeList_0">Circular</label></li>
<li><input id="shapeList_1" class="shapeButton" type="radio" value="Rectangular" name="shapeList" /><label for="shapeList_1">Rectangular</label></li>
</ul>
you can select by class:
$(".shapeButton").click(SetShape);
or select by container ID:
$("#shapeList").click(SetShape);
In either case, the event will trigger on clicking either the radio button or the label for it, though oddly in the latter case (Selecting by "#shapeList"), clicking on the label will trigger the click function twice for some reason, at least in FireFox; selecting by class won't do that.
SetShape is a function, and looks like this:
function SetShape() {
var Shape = $('.shapeButton:checked').val();
//dostuff
}
This way, you can have labels on your buttons, and can have multiple radio button lists on the same page that do different things. You can even have each individual button in the same list do different things by setting up different behavior in SetShape() based on the button's value.
The final
keyword has several usages in Java. It corresponds to both the sealed
and readonly
keywords in C#, depending on the context in which it is used.
To prevent subclassing (inheritance from the defined class):
Java
public final class MyFinalClass {...}
C#
public sealed class MyFinalClass {...}
Prevent overriding of a virtual
method.
Java
public class MyClass
{
public final void myFinalMethod() {...}
}
C#
public class MyClass : MyBaseClass
{
public sealed override void MyFinalMethod() {...}
}
As Joachim Sauer points out, a notable difference between the two languages here is that Java by default marks all non-static methods as virtual
, whereas C# marks them as sealed
. Hence, you only need to use the sealed
keyword in C# if you want to stop further overriding of a method that has been explicitly marked virtual
in the base class.
To only allow a variable to be assigned once:
Java
public final double pi = 3.14; // essentially a constant
C#
public readonly double pi = 3.14; // essentially a constant
As a side note, the effect of the readonly
keyword differs from that of the const
keyword in that the readonly
expression is evaluated at runtime rather than compile-time, hence allowing arbitrary expressions.
In class file you can either use:
module.exports = class ClassNameHere {
print() {
console.log('In print function');
}
}
or you can use this syntax
class ClassNameHere{
print(){
console.log('In print function');
}
}
module.exports = ClassNameHere;
On the other hand to use this class in any other file you need to do these steps.
First require that file using this syntax:
const anyVariableNameHere = require('filePathHere');
Then create an object
const classObject = new anyVariableNameHere();
After this you can use classObject
to access the actual class variables
There are a number of ways to get information on the attributes of your DataFrame or Series.
Create Sample DataFrame and Series
df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df
a b
0 5.0 9
1 2.0 2
2 NaN 4
s = df['a']
s
0 5.0
1 2.0
2 NaN
Name: a, dtype: float64
shape
AttributeThe shape
attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.
df.shape
(3, 2)
s.shape
(3,)
len
functionTo get the number of rows of a DataFrame or get the length of a Series, use the len
function. An integer will be returned.
len(df)
3
len(s)
3
size
attributeTo get the total number of elements in the DataFrame or Series, use the size
attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len
function:
df.size
6
s.size
3
ndim
attributeThe ndim
attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:
df.ndim
2
s.ndim
1
count
methodThe count
method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.
df.count() # by default, get the count of each column
a 2
b 3
dtype: int64
df.count(axis='columns') # change direction to get count of each row
0 2
1 2
2 1
dtype: int64
For a Series, there is only one axis for computation and so it just returns a scalar:
s.count()
2
info
method for retrieving metadataThe info
method returns the number of non-missing values and data types of each column
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a 2 non-null float64
b 3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes
Take a look at this similar question. Tool to discover same class..
I think the most relevant obstacle is if you have a custom classloader ( loading from a db or ldap )
I tried all the solutions above and in addition, those in related answers as well. Solutions including but not limited to passing the blob manually to a HTMLInputElement's file property, calling all the readAs* methods on FileReader, using a File instance as second argument for a FormData.append call, trying to get the blob data as a string by getting the values at URL.createObjectURL(myBlob) which turned out nasty and crashed my machine.
Now, if you happen to attempt those or more and still find you're unable to upload your blob, it could mean the problem is server-side. In my case, my blob exceeded the http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize and post_max_size limit in PHP.INI so the file was leaving the front end form but getting rejected by the server. You could either increase this value directly in PHP.INI or via .htaccess
Change the code where you load the partial view to:
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable
Update: Does not apply to the Android Studio released after this answer (April 2016)
Note: I think this might be a bug in Android Studio.
Now revert Compiled Sdk Version back to Google API xx.
If this not work, then:
You'll probably want to try textContent
instead of innerHTML
.
Given innerHTML
will return DOM content as a String
and not exclusively the "text" in the div
. It's fine if you know that your div
contains only text but not suitable if every use case. For those cases, you'll probably have to use textContent
instead of innerHTML
For example, considering the following markup:
<div id="test">
Some <span class="foo">sample</span> text.
</div>
You'll get the following result:
var node = document.getElementById('test'),
htmlContent = node.innerHTML,
// htmlContent = "Some <span class="foo">sample</span> text."
textContent = node.textContent;
// textContent = "Some sample text."
See MDN for more details:
Easily readable and customisable way to get a timestamp in your desired format, without use of any library:
function timestamp(){
function pad(n) {return n<10 ? "0"+n : n}
d=new Date()
dash="-"
colon=":"
return d.getFullYear()+dash+
pad(d.getMonth()+1)+dash+
pad(d.getDate())+" "+
pad(d.getHours())+colon+
pad(d.getMinutes())+colon+
pad(d.getSeconds())
}
(If you require time in UTC format, then just change the function calls. For example "getMonth" becomes "getUTCMonth")
Run Following command to show catalina logs on the terminal---
sh start-camunda.sh; tail -f server/apache-tomcat-8.0.24/logs/catalina.out
I'll add something that helps me out a lot with cygwin. Whenever setting up a new system, I always do this
ln -s /cygdrive/c /c
This creates a symbolic link to /cygdrive/c
with a new file called /c
(in the home directory)
Then you can do this in your shell
cd /c/Foo
cd /c/
Very handy.
I think the best answer is
int words = 0;
int lines = 0;
int chars = 0;
while(in.hasNextLine()) {
lines++;
String line = in.nextLine();
for(int i=0;i<line.length();i++)
{
if(line.charAt(i)!=' ' && line.charAt(i)!='\n')
chars ++;
}
words += new StringTokenizer(line, " ,").countTokens();
}
To store the array values in cookie, first you need to convert them to string, so here is some options.
Storing code
setcookie('your_cookie_name', json_encode($info), time()+3600);
Reading code
$data = json_decode($_COOKIE['your_cookie_name'], true);
JSON can be good choose also if you need read cookie in front end with JavaScript.
Actually you can use any encrypt_array_to_string
/decrypt_array_from_string
methods group that will convert array to string and convert string back to same array.
For example you can also use explode
/implode
for array of integers.
From PHP.net
Do not pass untrusted user input to unserialize().
- Anything that coming by HTTP including cookies is untrusted!
References related to security
setcookie('my_array[0]', 'value1' , time()+3600);
setcookie('my_array[1]', 'value2' , time()+3600);
setcookie('my_array[2]', 'value3' , time()+3600);
And after if you will print $_COOKIE
variable, you will see the following
echo '<pre>';
print_r( $_COOKIE );
die();
Array ( [my_array] => Array ( [0] => value1 [1] => value2 [2] => value3 ) )
This is documented PHP feature.
From PHP.net
Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system.
Here is an easy and convenient way of using something similar to the Java map:
var map= {
'map_name_1': map_value_1,
'map_name_2': map_value_2,
'map_name_3': map_value_3,
'map_name_4': map_value_4
}
And to get the value:
alert( map['map_name_1'] ); // fives the value of map_value_1
...... etc .....
You can, if you want, use standalone strings for multi-line comments — I've always thought that prettier than if (FALSE) { }
blocks. The string will get evaluated and then discarded, so as long as it's not the last line in a function nothing will happen.
"This function takes a value x, and does things and returns things that
take several lines to explain"
doEverythingOften <- function(x) {
# Non! Comment it out! We'll just do it once for now.
"if (x %in% 1:9) {
doTenEverythings()
}"
doEverythingOnce()
...
return(list(
everythingDone = TRUE,
howOftenDone = 1
))
}
The main limitation is that when you're commenting stuff out, you've got to watch your quotation marks: if you've got one kind inside, you'll have to use the other kind for the comment; and if you've got something like "strings with 'postrophes" inside that block, then there's no way this method is a good idea. But then there's still the if (FALSE)
block.
The other limitation, one that both methods have, is that you can only use such blocks in places where an expression would be syntactically valid - no commenting out parts of lists, say.
Regarding what do in which IDE: I'm a Vim user, and I find NERD Commenter an utterly excellent tool for quickly commenting or uncommenting multiple lines. Very user-friendly, very well-documented.
Lastly, at the R prompt (at least under Linux), there's the lovely Alt-Shift-# to comment the current line. Very nice to put a line 'on hold', if you're working on a one-liner and then realise you need a prep step first.
SELECT * FROM (SELECT ROW_NUMBER () OVER (ORDER BY sal DESC) row_number, sr,sal FROM empsal) a WHERE (row_number%2) = 1
and
SELECT * FROM (SELECT ROW_NUMBER () OVER (ORDER BY sal DESC) row_number, sr,sal FROM empsal) a WHERE (row_number%2) = 0
Expanding on comments by mbargiel and mycelo on the accepted answer, the following can be used with a non-blocking socket on the server end to inform whether the client has shut down.
This approach does not suffer the race condition that affects the Poll method in the accepted answer.
// Determines whether the remote end has called Shutdown
public bool HasRemoteEndShutDown
{
get
{
try
{
int bytesRead = socket.Receive(new byte[1], SocketFlags.Peek);
if (bytesRead == 0)
return true;
}
catch
{
// For a non-blocking socket, a SocketException with
// code 10035 (WSAEWOULDBLOCK) indicates no data available.
}
return false;
}
}
The approach is based on the fact that the Socket.Receive
method returns zero immediately after the remote end shuts down its socket and we've read all of the data from it. From Socket.Receive documentation:
If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the Receive method will complete immediately and return zero bytes.
If you are in non-blocking mode, and there is no data available in the protocol stack buffer, the Receive method will complete immediately and throw a SocketException.
The second point explains the need for the try-catch.
Use of the SocketFlags.Peek
flag leaves any received data untouched for a separate receive mechanism to read.
The above will work with a blocking socket as well, but be aware that the code will block on the Receive call (until data is received or the receive timeout elapses, again resulting in a SocketException
).
Your "scary" solution does not appear scary to me. Calling shuffle()
for two sequences of the same length results in the same number of calls to the random number generator, and these are the only "random" elements in the shuffle algorithm. By resetting the state, you ensure that the calls to the random number generator will give the same results in the second call to shuffle()
, so the whole algorithm will generate the same permutation.
If you don't like this, a different solution would be to store your data in one array instead of two right from the beginning, and create two views into this single array simulating the two arrays you have now. You can use the single array for shuffling and the views for all other purposes.
Example: Let's assume the arrays a
and b
look like this:
a = numpy.array([[[ 0., 1., 2.],
[ 3., 4., 5.]],
[[ 6., 7., 8.],
[ 9., 10., 11.]],
[[ 12., 13., 14.],
[ 15., 16., 17.]]])
b = numpy.array([[ 0., 1.],
[ 2., 3.],
[ 4., 5.]])
We can now construct a single array containing all the data:
c = numpy.c_[a.reshape(len(a), -1), b.reshape(len(b), -1)]
# array([[ 0., 1., 2., 3., 4., 5., 0., 1.],
# [ 6., 7., 8., 9., 10., 11., 2., 3.],
# [ 12., 13., 14., 15., 16., 17., 4., 5.]])
Now we create views simulating the original a
and b
:
a2 = c[:, :a.size//len(a)].reshape(a.shape)
b2 = c[:, a.size//len(a):].reshape(b.shape)
The data of a2
and b2
is shared with c
. To shuffle both arrays simultaneously, use numpy.random.shuffle(c)
.
In production code, you would of course try to avoid creating the original a
and b
at all and right away create c
, a2
and b2
.
This solution could be adapted to the case that a
and b
have different dtypes.
IF NOT EXISTS (SELECT * FROM syscolumns
WHERE ID=OBJECT_ID('[db].[Employee]') AND NAME='EmpName')
ALTER TABLE [db].[Employee]
ADD [EmpName] VARCHAR(10)
GO
I Hope this would help. More info
both your conditions are the same:
if(s < f) { calc = f - s; n = s; }else if(f > s){ calc = s - f; n = f; }
so
if(s < f)
and
}else if(f > s){
are the same
change to
}else if(f < s){
The trick is to use "sudo" command instead of "su"
You may need to add this
username1 ALL=(username2) NOPASSWD: /path/to/svn
to your /etc/sudoers file
and change your script to:
sudo -u username2 -H sh -c "cd /home/$USERNAME/$PROJECT; svn update"
Where username2 is the user you want to run the SVN command as and username1 is the user running the script.
If you need multiple users to run this script, use a %groupname
instead of the username1
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;
When you’re faced with a problem to solve (and frankly, who isn’t these days?), the basic strategy usually taken by we computer people is called “divide and conquer.” It goes like this:
- Conceptualize the specific problem as a set of smaller sub-problems.
- Solve each smaller problem.
- Combine the results into a solution of the specific problem.
But “divide and conquer” is not the only possible strategy. We can also take a more generalist approach:
- Conceptualize the specific problem as a special case of a more general problem.
- Somehow solve the general problem.
- Adapt the solution of the general problem to the specific problem.
- Eric Lippert
I believe many solutions already exist for this problem in server-side languages such as ASP.Net/C#.
I've outlined some of the major aspects of the problem
Issue: We need to load data only for the desired language
Solution: For this purpose we save data to a separate files for each language
ex. res.de.js, res.fr.js, res.en.js, res.js(for default language)
Issue: Resource files for each page should be separated so we only get the data we need
Solution: We can use some tools that already exist like https://github.com/rgrove/lazyload
Issue: We need a key/value pair structure to save our data
Solution: I suggest a javascript object instead of string/string air. We can benefit from the intellisense from an IDE
Issue: General members should be stored in a public file and all pages should access them
Solution: For this purpose I make a folder in the root of web application called Global_Resources and a folder to store global file for each sub folders we named it 'Local_Resources'
Issue: Each subsystems/subfolders/modules member should override the Global_Resources members on their scope
Solution: I considered a file for each
Application Structure
root/ Global_Resources/ default.js default.fr.js UserManagementSystem/ Local_Resources/ default.js default.fr.js createUser.js Login.htm CreateUser.htm
The corresponding code for the files:
Global_Resources/default.js
var res = {
Create : "Create",
Update : "Save Changes",
Delete : "Delete"
};
Global_Resources/default.fr.js
var res = {
Create : "créer",
Update : "Enregistrer les modifications",
Delete : "effacer"
};
The resource file for the desired language should be loaded on the page selected from Global_Resource - This should be the first file that is loaded on all the pages.
UserManagementSystem/Local_Resources/default.js
res.Name = "Name";
res.UserName = "UserName";
res.Password = "Password";
UserManagementSystem/Local_Resources/default.fr.js
res.Name = "nom";
res.UserName = "Nom d'utilisateur";
res.Password = "Mot de passe";
UserManagementSystem/Local_Resources/createUser.js
// Override res.Create on Global_Resources/default.js
res.Create = "Create User";
UserManagementSystem/Local_Resources/createUser.fr.js
// Override Global_Resources/default.fr.js
res.Create = "Créer un utilisateur";
manager.js file (this file should be load last)
res.lang = "fr";
var globalResourcePath = "Global_Resources";
var resourceFiles = [];
var currentFile = globalResourcePath + "\\default" + res.lang + ".js" ;
if(!IsFileExist(currentFile))
currentFile = globalResourcePath + "\\default.js" ;
if(!IsFileExist(currentFile)) throw new Exception("File Not Found");
resourceFiles.push(currentFile);
// Push parent folder on folder into folder
foreach(var folder in parent folder of current page)
{
currentFile = folder + "\\Local_Resource\\default." + res.lang + ".js";
if(!IsExist(currentFile))
currentFile = folder + "\\Local_Resource\\default.js";
if(!IsExist(currentFile)) throw new Exception("File Not Found");
resourceFiles.push(currentFile);
}
for(int i = 0; i < resourceFiles.length; i++) { Load.js(resourceFiles[i]); }
// Get current page name
var pageNameWithoutExtension = "SomePage";
currentFile = currentPageFolderPath + pageNameWithoutExtension + res.lang + ".js" ;
if(!IsExist(currentFile))
currentFile = currentPageFolderPath + pageNameWithoutExtension + ".js" ;
if(!IsExist(currentFile)) throw new Exception("File Not Found");
Hope it helps :)
You can use Borderless style in AppCompatButton like below. and use android:background with it.
style="@style/Widget.AppCompat.Button.Borderless.Colored"
Button code
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/button_visa_next"
android:background="@color/colorPrimary"
style="@style/Widget.AppCompat.Button.Borderless.Colored"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/spacing_normal"
android:text="@string/next"
android:textColor="@color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
Output:
Version 4.3.5 Updated Code
Since MultipartEntity
has been deprecated. Please see the code below.
String responseBody = "failure";
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
String url = WWPApi.URL_USERS;
Map<String, String> map = new HashMap<String, String>();
map.put("user_id", String.valueOf(userId));
map.put("action", "update");
url = addQueryParams(map, url);
HttpPost post = new HttpPost(url);
post.addHeader("Accept", "application/json");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(MIME.UTF8_CHARSET);
if (career != null)
builder.addTextBody("career", career, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (gender != null)
builder.addTextBody("gender", gender, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (username != null)
builder.addTextBody("username", username, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (email != null)
builder.addTextBody("email", email, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (password != null)
builder.addTextBody("password", password, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (country != null)
builder.addTextBody("country", country, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (file != null)
builder.addBinaryBody("Filedata", file, ContentType.MULTIPART_FORM_DATA, file.getName());
post.setEntity(builder.build());
try {
responseBody = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
// System.out.println("Response from Server ==> " + responseBody);
JSONObject object = new JSONObject(responseBody);
Boolean success = object.optBoolean("success");
String message = object.optString("error");
if (!success) {
responseBody = message;
} else {
responseBody = "success";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
What works for me is to delete the bin folder, then rebuild the project.
This is what worked best for me:
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../"));
Getting the 'right' path wasn't the problem, adding '../' obviously does that, but after that, the given string isn't usable, because it will just add the '../' at the end.
Surrounding it with Path.GetFullPath()
will give you the absolute path, making it usable.
In case you came to this question but related to newer Angular version >= 2.0.
<div [id]="element.id"></div>
Swift version of @Jensen2k's answer:
let gestureRecognizer : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: "dismissKeyboard")
self.view.addGestureRecognizer(gestureRecognizer)
func dismissKeyboard() {
aTextField.resignFirstResponder()
}
One liner
self.view.addTapGesture(UITapGestureRecognizer.init(target: self, action: "endEditing:"))
Just handle the form submission on the submit event, and return false:
$('#contactForm').submit(function () {
sendContactForm();
return false;
});
You don't need any more the onclick event on the submit button:
<input class="submit" type="submit" value="Send" />
newlist=[] #make an empty list
for i in list: # loop to hv a dict in list
s={} # make an empty dict to store new dict data
for k in i.keys(): # to get keys in the dict of the list
s[k]=int(i[k]) # change the values from string to int by int func
newlist.append(s) # to add the new dict with integer to the list
imread is depreciated after version 1.2.0! So to solve this issue I had to install version 1.1.0.
pip install scipy==1.1.0
function Continue({show, onContinue}) {
return(<div className="row continue">
{ show ? <div className="col-11">
<button class="btn btn-primary btn-lg float-right" onClick= {onContinue}>Continue</button>
</div>
: null }
</div>);
}
Note - if you want to pass a data attribute to a React Component, you need to handle them a little differently than other props.
2 options
Don't use camel case
<Option data-img-src='value' ... />
And then in the component, because of the dashes, you need to refer to the prop in quotes.
// @flow
class Option extends React.Component {
props: {
'data-img-src': string
}
And when you refer to it later, you don't use the dot syntax
render () {
return (
<option data-img-src={this.props['data-img-src']} >...</option>
)
}
}
Or use camel case
<Option dataImgSrc='value' ... />
And then in the component, you need to convert.
// @flow
class Option extends React.Component {
props: {
dataImgSrc: string
}
And when you refer to it later, you don't use the dot syntax
render () {
return (
<option data-img-src={this.props.dataImgSrc} >...</option>
)
}
}
Mainly just realize data-
attributes and aria-
attributes are treated specially. You are allowed to use hyphens in the attribute name in those two cases.
Try ArrayDeque
or LinkedList
, which both implement the Queue
interface.
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayDeque.html
×
is better than ✖
as ✖
behaves strangely in Edge and Internet explorer (tested in IE11). It doesn't get the right color and is replaced by an "emoji"
COUNTIF
works well for quick difference-checking. And it's easier to remember and simpler to work with than VLOOKUP
.
=COUNTIF([Book1]Sheet1!$A:$A, A1)
will give you a column showing 1 if there's match and zero if there's no match (with the bonus of showing >1 for duplicates within the list itself).
There's the Managed Script Plugin which provides an easy way of managing user scripts. It also adds a build step action which allows you to select which user script to execute.
After wrestling with this problem today my opinion is this: BEGIN...END brackets code just like {....} does in C languages, e.g. code blocks for if...else and loops
GO is (must be) used when succeeding statements rely on an object defined by a previous statement. USE database is a good example above, but the following will also bite you:
alter table foo add bar varchar(8);
-- if you don't put GO here then the following line will error as it doesn't know what bar is.
update foo set bar = 'bacon';
-- need a GO here to tell the interpreter to execute this statement, otherwise the Parser will lump it together with all successive statements.
It seems to me the problem is this: the SQL Server SQL Parser, unlike the Oracle one, is unable to realise that you're defining a new symbol on the first line and that it's ok to reference in the following lines. It doesn't "see" the symbol until it encounters a GO token which tells it to execute the preceding SQL since the last GO, at which point the symbol is applied to the database and becomes visible to the parser.
Why it doesn't just treat the semi-colon as a semantic break and apply statements individually I don't know and wish it would. Only bonus I can see is that you can put a print() statement just before the GO and if any of the statements fail the print won't execute. Lot of trouble for a minor gain though.
Using Jupyterthemes, one can easily change look of notebook.
pip install jupyterthemes
jt -fs 15
By default code font size is set to 11 . Trying above will change font size. It can be reset using.
jt -r
This will reset all jupyter theme changes to default.
I realized this task for my needs as follows
set nocount on;
declare @ToDate date = dateadd(month,datediff(month,0,getdate())-1,0)
declare @year varchar(4) = year(@ToDate)
declare @month varchar(2) = month(@ToDate)
declare @sql nvarchar(max)
set @sql = N'
create or alter view dbo.wTempLogs
as
select * from dbo.y2019
where
year(LogDate) = ''_year_''
and
month(LogDate) = ''_month_'' '
select @sql = replace(replace(@sql,'_year_',@year),'_month_',@month)
execute sp_executesql @sql
declare @errmsg nvarchar(max)
set @errMsg = @sql
raiserror (@errMsg, 0,1) with nowait
C# 7.0 supports binary literals (and optional digit separators via underscore characters).
An example:
int myValue = 0b0010_0110_0000_0011;
You can also find more information on the Roslyn GitHub page.
One of most upleasing functional forEach
's limitations is lack of checked exceptions support.
One possible workaround is to replace terminal forEach
with plain old foreach loop:
Stream<String> stream = Stream.of("", "1", "2", "3").filter(s -> !s.isEmpty());
Iterable<String> iterable = stream::iterator;
for (String s : iterable) {
fileWriter.append(s);
}
Here is list of most popular questions with other workarounds on checked exception handling within lambdas and streams:
Java 8 Lambda function that throws exception?
Java 8: Lambda-Streams, Filter by Method with Exception
How can I throw CHECKED exceptions from inside Java 8 streams?
Java 8: Mandatory checked exceptions handling in lambda expressions. Why mandatory, not optional?
As of Feb 2016 - see the TALLY Table Example - very likely to outperform my TVF below, from Feb 2014. Keeping original post below for posterity:
Too much repeated code for my liking in the above examples. And I dislike the performance of CTEs and XML. Also, an explicit Id
so that consumers that are order specific can specify an ORDER BY
clause.
CREATE FUNCTION dbo.Split
(
@Line nvarchar(MAX),
@SplitOn nvarchar(5) = ','
)
RETURNS @RtnValue table
(
Id INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED,
Data nvarchar(100) NOT NULL
)
AS
BEGIN
IF @Line IS NULL RETURN
DECLARE @split_on_len INT = LEN(@SplitOn)
DECLARE @start_at INT = 1
DECLARE @end_at INT
DECLARE @data_len INT
WHILE 1=1
BEGIN
SET @end_at = CHARINDEX(@SplitOn,@Line,@start_at)
SET @data_len = CASE @end_at WHEN 0 THEN LEN(@Line) ELSE @end_at-@start_at END
INSERT INTO @RtnValue (data) VALUES( SUBSTRING(@Line,@start_at,@data_len) );
IF @end_at = 0 BREAK;
SET @start_at = @end_at + @split_on_len
END
RETURN
END
Since your issue is mostly stylistic (not wanting to fill up the constructor with a bunch of declarations) it can be solved stylistically as well.
The way I view it, many class based languages have the constructor be a function named after the class name itself. Stylistically we could use that that to make an ES6 class that stylistically still makes sense but does not group the typical actions taking place in the constructor with all the property declarations we're doing. We simply use the actual JS constructor as the "declaration area", then make a class named function that we otherwise treat as the "other constructor stuff" area, calling it at the end of the true constructor.
"use strict"; class MyClass { // only declare your properties and then call this.ClassName(); from here constructor(){ this.prop1 = 'blah 1'; this.prop2 = 'blah 2'; this.prop3 = 'blah 3'; this.MyClass(); } // all sorts of other "constructor" stuff, no longer jumbled with declarations MyClass() { doWhatever(); } }
Both will be called as the new instance is constructed.
Sorta like having 2 constructors where you separate out the declarations and the other constructor actions you want to take, and stylistically makes it not too hard to understand that's what is going on too.
I find it's a nice style to use when dealing with a lot of declarations and/or a lot of actions needing to happen on instantiation and wanting to keep the two ideas distinct from each other.
NOTE: I very purposefully do not use the typical idiomatic ideas of "initializing" (like an init()
or initialize()
method) because those are often used differently. There is a sort of presumed difference between the idea of constructing and initializing. Working with constructors people know that they're called automatically as part of instantiation. Seeing an init
method many people are going to assume without a second glance that they need to be doing something along the form of var mc = MyClass(); mc.init();
, because that's how you typically initialize. I'm not trying to add an initialization process for the user of the class, I'm trying to add to the construction process of the class itself.
While some people may do a double-take for a moment, that's actually the bit of the point: it communicates to them that the intent is part of construction, even if that makes them do a bit of a double take and go "that's not how ES6 constructors work" and take a second looking at the actual constructor to go "oh, they call it at the bottom, I see", that's far better than NOT communicating that intent (or incorrectly communicating it) and probably getting a lot of people using it wrong, trying to initialize it from the outside and junk. That's very much intentional to the pattern I suggest.
For those that don't want to follow that pattern, the exact opposite can work too. Farm the declarations out to another function at the beginning. Maybe name it "properties" or "publicProperties" or something. Then put the rest of the stuff in the normal constructor.
"use strict"; class MyClass { properties() { this.prop1 = 'blah 1'; this.prop2 = 'blah 2'; this.prop3 = 'blah 3'; } constructor() { this.properties(); doWhatever(); } }
Note that this second method may look cleaner but it also has an inherent problem where properties
gets overridden as one class using this method extends another. You'd have to give more unique names to properties
to avoid that. My first method does not have this problem because its fake half of the constructor is uniquely named after the class.
You just need to divide each element by the sum of the values in its column.
Doing this should suffice:
data.perc <- apply(data, 2, function(x){x/sum(x)})
Note that the second parameter tells apply
to apply the provided function to columns (using 1 you would apply it to rows). The anonymous function, then, gets passed each data column, one at a time.
I had the same error message. In my case I had inadvertently mixed the ES6 export default function myFunc
syntax with const myFunc = require('./myFunc');
.
Using module.exports = myFunc;
instead solved the issue.
Check the lib of your project. It may be that you have include two such jar files in which same class is available or say one class in code can be refrenced in two jar files. In such case also eclipse stops assisting code as it is totally confused.
Better way to check this is go to the file where assist is not working and comment all imports there, than add imports one by one and check at each import if code-assist is working or not.You can easily find the class with duplicate refrences.
You can replace those in your Manifest application tag:
<application
tools:replace="android:icon, android:label, android:theme, android:name,android:allowBackup"
android:allowBackup="false"...>
and will work for you.
you can use background-origin:padding-box; and then add some padding where you want, for example: #logo {background-image: url(your/image.jpg); background-origin:padding-box; padding-left: 15%;}
This way you attach the image to the div padding box that contains it so you can position it wherever you want.
Most popular answers here with BaseController didn't worked for me on Laravel 5.4, but they have worked on 5.3. No idea why.
I have found a way which works on Laravel 5.4 and gives variables even for views which are skipping controllers. And, of course, you can get variables from the database.
add in your app/Providers/AppServiceProvider.php
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
// Using view composer to set following variables globally
view()->composer('*',function($view) {
$view->with('user', Auth::user());
$view->with('social', Social::all());
// if you need to access in controller and views:
Config::set('something', $something);
});
}
}
credit: http://laraveldaily.com/global-variables-in-base-controller/
You can bulk import all aliases from one keystore to another:
keytool -importkeystore -srckeystore source.jks -destkeystore dest.jks
Use the --force
(-f
) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.
For example:
mysql -u userName -p -f -D dbName < script.sql
More than likely your method declaration is incorrect. Make sure the methods parameter is of type String array (String[]) and not simply String and that you use double quotes around your strings in the array declaration.
private String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k"};
public void myMethod(String[] myArray) {}
Reflection is slower, but works for a situation when you want to know whether that is of type Dog or a Cat and not an instance of Animal. So you'd do something like:
if(null != items.elementAt(1) && items.elementAt(1).getClass().toString().equals("Cat"))
{
//do whatever with cat.. not any other instance of animal.. eg. hideClaws();
}
Not saying the answer above does not work, except the null checking part is necessary.
Another way to answer that is use generics and you are guaranteed to have Double as any element of items.
List<Double> items = new ArrayList<Double>();
You can return json in PHP this way:
header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;
function _modulename_getData($field, $table) {
try {
if (empty($field)) {
throw new Exception("The field is undefined.");
}
// rest of code here...
}
catch (Exception $e) {
/*
Here you can either echo the exception message like:
echo $e->getMessage();
Or you can throw the Exception Object $e like:
throw $e;
*/
}
}
If you are using laragon open the php.ini
In the interface of laragon menu-> php-> php.ini
when you open the file look for ; extension_dir = "./"
create another one without **; ** with the path of your php version to the folder ** ext ** for example
extension_dir = "C: \ laragon \ bin \ php \ php-7.3.11-Win32-VC15-x64 \ ext"
change it save it
let vs var. It's all about scope.
var variables are global and can be accessed basically everywhere, while let variables are not global and only exist until a closing parenthesis kills them.
See my example below, and note how the lion (let) variable acts differently in the two console.logs; it becomes out of scope in the 2nd console.log.
var cat = "cat";
let dog = "dog";
var animals = () => {
var giraffe = "giraffe";
let lion = "lion";
console.log(cat); //will print 'cat'.
console.log(dog); //will print 'dog', because dog was declared outside this function (like var cat).
console.log(giraffe); //will print 'giraffe'.
console.log(lion); //will print 'lion', as lion is within scope.
}
console.log(giraffe); //will print 'giraffe', as giraffe is a global variable (var).
console.log(lion); //will print UNDEFINED, as lion is a 'let' variable and is now out of scope.
A little late but this could help: http://webdesign.tutsplus.com/tutorials/how-to-make-responsive-scrollable-panels-with-flexbox--cms-23269
Basically you need to put html
,body
to height: 100%;
and wrap all your content into a <div class="wrap"> <!-- content --> </div>
CSS:
html, body {
height: 100%;
}
.wrap {
height: 100vh;
display: flex;
}
Worked for me. Hope it helps
Use HashBytes
SELECT HashBytes('MD5', '[email protected]')
That will give you 0xF53BD08920E5D25809DF2563EF9C52B6
-
SELECT CONVERT(NVARCHAR(32),HashBytes('MD5', '[email protected]'),2)
That will give you F53BD08920E5D25809DF2563EF9C52B6
If it happens, then it means you have to upgrade your node.js. Simply uninstall your current node from your pc or mac and download the latest version from https://nodejs.org/en/
>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])
For implementing the timeout on the function, this stackoverflow thread has answers on that.
Use insert
if you want to insert a new element. insert
will not
overwrite an existing element, and you can verify that there was no
previously exising element:
if ( !myMap.insert( std::make_pair( key, value ) ).second ) {
// Element already present...
}
Use []
if you want to overwrite a possibly existing element:
myMap[ key ] = value;
assert( myMap.find( key )->second == value ); // post-condition
This form will overwrite any existing entry.
I would try one of the following:
import numpy as np
X1 = np.random.randint(low=0, high=10, size=(15,))
print (X1)
>>> array([3, 0, 9, 0, 5, 7, 6, 9, 6, 7, 9, 6, 6, 9, 8])
import numpy as np
X2 = np.random.uniform(low=0, high=10, size=(15,)).astype(int)
print (X2)
>>> array([8, 3, 6, 9, 1, 0, 3, 6, 3, 3, 1, 2, 4, 0, 4])
import numpy as np
X3 = np.random.choice(a=10, size=15 )
print (X3)
>>> array([1, 4, 0, 2, 5, 2, 7, 5, 0, 0, 8, 4, 4, 0, 9])
4.> random.randrange
from random import randrange
X4 = [randrange(10) for i in range(15)]
print (X4)
>>> [2, 1, 4, 1, 2, 8, 8, 6, 4, 1, 0, 5, 8, 3, 5]
5.> random.randint
from random import randint
X5 = [randint(0, 9) for i in range(0, 15)]
print (X5)
>>> [6, 2, 6, 9, 5, 3, 2, 3, 3, 4, 4, 7, 4, 9, 6]
Speed:
? np.random.uniform and np.random.randint are much faster (~10 times faster) than np.random.choice, random.randrange, random.randint .
%timeit np.random.randint(low=0, high=10, size=(15,))
>> 1.64 µs ± 7.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit np.random.uniform(low=0, high=10, size=(15,)).astype(int)
>> 2.15 µs ± 38.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit np.random.choice(a=10, size=15 )
>> 21 µs ± 629 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit [randrange(10) for i in range(15)]
>> 12.9 µs ± 60.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit [randint(0, 9) for i in range(0, 15)]
>> 20 µs ± 386 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Notes:
1.> np.random.randint generates random integers over the half-open interval [low, high).
2.> np.random.uniform generates uniformly distributed numbers over the half-open interval [low, high).
3.> np.random.choice generates a random sample over the half-open interval [low, high) as if the argument
a
was np.arange(n).4.> random.randrange(stop) generates a random number from range(start, stop, step).
5.> random.randint(a, b) returns a random integer N such that a <= N <= b.
6.> astype(int) casts the numpy array to int data type.
7.> I have chosen size = (15,). This will give you a numpy array of length = 15.
If by "use internet", you mean you can not access the internet from an activity while testing on the emulator, make sure you have set the internet permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
If you are using the web browser, refer to Donal's post
I found a solution for converting the files to a .sql
file (you can then import the .sql
file to a server and recover the database), without needing to access the /var
directory, therefore you do not need to be a server admin to do this either.
It does require XAMPP or MAMP installed on your computer.
C:\XAMPP
), and the the sub-directory mysql\data
. The full path should be C:\XAMPP\mysql\data
Inside you will see folders of any other databases you have created. Copy & Paste the folder full of .myd
, .myi
and .frm
files into there. The path to that folder should be
C:\XAMPP\mysql\data\foldername\.mydfiles
Then visit localhost/phpmyadmin
in a browser. Select the database you have just pasted into the mysql\data
folder, and click on Export in the navigation bar. Chooses the export it as a .sql
file. It will then pop up asking where the save the file
And that is it! You (should) now have a .sql
file containing the database that was originally .myd
, .myi
and .frm
files. You can then import it to another server through phpMyAdmin by creating a new database and pressing 'Import' in the navigation bar, then following the steps to import it
Using C# 7 (.NET Framework 4.6.2) you can write an IsNumeric function as a one-liner:
public bool IsNumeric(string val) => int.TryParse(val, out int result);
Note that the function above will only work for integers (Int32). But you can implement corresponding functions for other numeric data types, like long, double, etc.
MySQL account names consist of a user name and a host name, The name 'localhost' in host name indicates the local host also You can use the wildcard characters “%” and “_” in host name or IP address values. These have the same meaning as for pattern-matching operations performed with the LIKE operator. For example, a host value of '%' matches any host name, whereas a value of '%.mysql.com' matches any host in the mysql.com domain. '192.168.1.%' matches any host in the 192.168.1 class C network.
Above was just introduction:
actually both users 'bill'@'localhost'
and 'bill'@'%'
are different MySQL accounts, hence both should use their own authentication details like password.
For more information refer http://dev.mysql.com/doc/refman//5.5/en/account-names.html
It's just a namespace definition to avoid collision of class names. The com.domain.package.Class
is an established Java convention wherein the namespace is qualified with the company domain in reverse.
You could use dplyr::mutate_if()
to convert all character columns or dplyr::mutate_at()
for select named character columns to factors:
library(dplyr)
# all character columns to factor:
df <- mutate_if(df, is.character, as.factor)
# select character columns 'char1', 'char2', etc. to factor:
df <- mutate_at(df, vars(char1, char2), as.factor)
You might try passing actual types instead of strings.
import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = [datetime, datetime, str, float]
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)
But it's going to be really hard to diagnose this without any of your data to tinker with.
And really, you probably want pandas to parse the the dates into TimeStamps, so that might be:
pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=True)
First of all my Search query value is from a user's input. I have tried all the answers on this one and all the results Google have given me, 90% of the answers says put '%''%' and the other 10% says a more complicated answers.
For some reason all of those did not work for me.
How ever I remembered that in MySQL (phpmyadmin) there is this built in search function so I tried it just to see how MySQL handles a search with an apostrophe, turns out MySQL just escaping apostrophe with a backslash LIKE '%\'%'
so why just I replace apostrophe with a \'
in every user's query.
This is what I come up with:
if(!empty($user_search)) {
$r_user_search = str_ireplace("'","\'","$user_search");
$find_it = "SELECT * FROM table WHERE column LIKE '%$r_user_search%'";
$results = $pdo->prepare($find_it);
$results->execute();
This solves my problem. Also please correct me if this is still has security issues.
System.Diagnostics.Process.Start("PathToExe.exe");
Upgrade your SQL Server to SP3
You can install it from: http://www.microsoft.com/en-us/download/details.aspx?id=27594
import sys
sys.exit()
details from the sys
module documentation:
sys.exit([arg])
Exit from Python. This is implemented by raising the
SystemExit
exception, so cleanup actions specified by finally clauses oftry
statements are honored, and it is possible to intercept the exit attempt at an outer level.The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to
stderr
and results in an exit code of 1. In particular,sys.exit("some error message")
is a quick way to exit a program when an error occurs.Since
exit()
ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.
Note that this is the 'nice' way to exit. @glyphtwistedmatrix below points out that if you want a 'hard exit', you can use os._exit(*errorcode*)
, though it's likely os-specific to some extent (it might not take an errorcode under windows, for example), and it definitely is less friendly since it doesn't let the interpreter do any cleanup before the process dies. On the other hand, it does kill the entire process, including all running threads, while sys.exit()
(as it says in the docs) only exits if called from the main thread, with no other threads running.
This is my favorite use of 112 and 114
select (convert(varchar, getdate(), 112)+ replace(convert(varchar, getdate(), 114),':','')) as 'Getdate()
112 + 114 or YYYYMMDDHHMMSSMSS'
Result:
Getdate() 112 + 114 or YYYYMMDDHHMMSSMSS
20171016083349100
Numerical_variables <- which(sapply(df, is.numeric))
# then extract column names
Names <- names(Numerical_variables)
//if passed exMins=0 it will delete as soon as it creates it.
function setCookie(cname, cvalue, exMins) {
var d = new Date();
d.setTime(d.getTime() + (exMins*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
setCookie('cookieNameToDelete','',0) // this will delete the cookie.
Thats really insane, i tried everything, synced with Gradle files, invalidated and restarted android studio. Still the problem persisted. Last resort was deleting .idea/libraries folder and it worked as charm.
If you are using jquery you might want to consider their data method.
I have used something similar to what you are trying in your response but like this:
<script src="http://path.to/widget.js" param_a = "2" param_b = "5" param_c = "4">
</script>
You could also create a function that lets you grab the GET params directly (this is what I frequently use):
function $_GET(q,s) {
s = s || window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}
// Grab the GET param
var param_a = $_GET('param_a');
As I started to update my old project to Swift 3.2, I just needed to change the method from
respondsToSelector(selector)
to:
responds(to: selector)
In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.
So register the ChildComponent in Shared Module manually.
What do they do:
What's the difference:
Use which when:
try this code sample, I tested it, source: http://www.makelinux.net/alp/035
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main ()
{
int segment_id;
char* shared_memory;
struct shmid_ds shmbuffer;
int segment_size;
const int shared_segment_size = 0x6400;
/* Allocate a shared memory segment. */
segment_id = shmget (IPC_PRIVATE, shared_segment_size,
IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
/* Attach the shared memory segment. */
shared_memory = (char*) shmat (segment_id, 0, 0);
printf ("shared memory attached at address %p\n", shared_memory);
/* Determine the segment's size. */
shmctl (segment_id, IPC_STAT, &shmbuffer);
segment_size = shmbuffer.shm_segsz;
printf ("segment size: %d\n", segment_size);
/* Write a string to the shared memory segment. */
sprintf (shared_memory, "Hello, world.");
/* Detach the shared memory segment. */
shmdt (shared_memory);
/* Reattach the shared memory segment, at a different address. */
shared_memory = (char*) shmat (segment_id, (void*) 0x5000000, 0);
printf ("shared memory reattached at address %p\n", shared_memory);
/* Print out the string from shared memory. */
printf ("%s\n", shared_memory);
/* Detach the shared memory segment. */
shmdt (shared_memory);
/* Deallocate the shared memory segment. */
shmctl (segment_id, IPC_RMID, 0);
return 0;
}
The MySQL function describe table should get you where you want to go (put your table name in for "table"). You'll have to parse the output some, but it's pretty easy. As I recall, if you execute that query, the PHP query result accessing functions that would normally give you a key-value pair will have the column names as the keys. But it's been a while since I used PHP so don't hold me to that. :)
If you are looking for a form reset:
<input type="reset" value="Reset Form Values"/>
or to reset other aspects of the form not handled by the browser
<input type="reset" onclick="doFormReset();" value="Reset Form Values"/>
Using jQuery
function doFormReset(){
$(".invalid").removeClass("invalid");
}
$('#multiselect1').on('change', function(){
var selected = $(this).find("option:selected");
var arrSelected = [];
selected.each(function(){
arrSelected.push($(this).val());
});
});
If a TestRestTemplate is a valid option in your unit test, this documentation might be relevant
Short answer: if using
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
then @Autowired
will work. If using
@SpringBootTest(webEnvironment=WebEnvironment.MOCK)
then create a TestRestTemplate like this
private TestRestTemplate template = new TestRestTemplate();
Firstly create app.js
file in the directory you want to publish.
var http = require('http');
var fs = require('fs');
var mime = require('mime');
http.createServer(function(req,res){
if (req.url != '/app.js') {
var url = __dirname + req.url;
fs.stat(url,function(err,stat){
if (err) {
res.writeHead(404,{'Content-Type':'text/html'});
res.end('Your requested URI('+req.url+') wasn\'t found on our server');
} else {
var type = mime.getType(url);
var fileSize = stat.size;
var range = req.headers.range;
if (range) {
var parts = range.replace(/bytes=/, "").split("-");
var start = parseInt(parts[0], 10);
var end = parts[1] ? parseInt(parts[1], 10) : fileSize-1;
var chunksize = (end-start)+1;
var file = fs.createReadStream(url, {start, end});
var head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': type
}
res.writeHead(206, head);
file.pipe(res);
} else {
var head = {
'Content-Length': fileSize,
'Content-Type': type
}
res.writeHead(200, head);
fs.createReadStream(url).pipe(res);
}
}
});
} else {
res.writeHead(403,{'Content-Type':'text/html'});
res.end('Sorry, access to that file is Forbidden');
}
}).listen(8080);
Simply run node app.js
and your server shall be running on port 8080. Besides video it can stream all kinds of files.
For those who are on SunOS which is non-GNU, the following code will help:
sed '1d' test.dat > tmp.dat
$this
to refers to the current object.static
refers to the current object.self
refers to the exact class it was defined in.parent
refers to the parent of the exact class it was defined in.See the following example which shows overloading.
<?php
class A {
public static function newStaticClass()
{
return new static;
}
public static function newSelfClass()
{
return new self;
}
public function newThisClass()
{
return new $this;
}
}
class B extends A
{
public function newParentClass()
{
return new parent;
}
}
$b = new B;
var_dump($b::newStaticClass()); // B
var_dump($b::newSelfClass()); // A because self belongs to "A"
var_dump($b->newThisClass()); // B
var_dump($b->newParentClass()); // A
class C extends B
{
public static function newSelfClass()
{
return new self;
}
}
$c = new C;
var_dump($c::newStaticClass()); // C
var_dump($c::newSelfClass()); // C because self now points to "C" class
var_dump($c->newThisClass()); // C
var_dump($b->newParentClass()); // A because parent was defined *way back* in class "B"
Most of the time you want to refer to the current class which is why you use static
or $this
. However, there are times when you need self
because you want the original class regardless of what extends it. (Very, Very seldom)
If not working in any case...then delete your project from the Eclipse workspace and again import as a Maven project if that is a Maven project. Else import as an existing project.
I tried all the previous given solutions, but they didn't work, but it works for me.
Probably your item.photo
is undefined
if you don't have a photo attribute on item in the first place and thus undefined != ''
. But if you'd put some code to show how you provide values to item
, it would help.
PS: Sorry to post this as an answer (I rather think it's more of a comment), but I don't have enough reputation yet.
You can use the below code on your string and you will get the complete string without html part.
string title = "<b> Hulk Hogan's Celebrity Championship Wrestling <font color=\"#228b22\">[Proj # 206010]</font></b> (Reality Series, )".Replace(" ",string.Empty);
string s = Regex.Replace(title, "<.*?>", String.Empty);
Another method utilizing the dplyr package:
library(dplyr)
df <- mtcars %>%
filter(mpg > 25)
Without the chain (%>%) operator:
library(dplyr)
df <- filter(mtcars, mpg > 25)
Now in 2017 with ASP.Net Core you can do it as explained here.
The Microsoft.AspNetCore.Session package provides middleware for managing session state.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Adds a default in-memory implementation of IDistributedCache.
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
}
From the Docs: Introduction to session and application state in ASP.NET Core
Already tested on a working project
Thanks @Joey. It's what I am looking for.
I just bring some improvements:
function Stop-Processes {
param(
[parameter(Mandatory=$true)] $processName,
$timeout = 5
)
$processList = Get-Process $processName -ErrorAction SilentlyContinue
if ($processList) {
# Try gracefully first
$processList.CloseMainWindow() | Out-Null
# Wait until all processes have terminated or until timeout
for ($i = 0 ; $i -le $timeout; $i ++){
$AllHaveExited = $True
$processList | % {
$process = $_
If (!$process.HasExited){
$AllHaveExited = $False
}
}
If ($AllHaveExited){
Return
}
sleep 1
}
# Else: kill
$processList | Stop-Process -Force
}
}
I solved it by setting valid archs to armv7 armv7s and setting build active architectures only to YES in release and then doing a new "pod install" from the command line
I tried installing and got the same error (using the new "marketplace"). I tried the typical Help->install new software... then where it says "Work with:" I entered:
http://dl-ssl.google.com/android/eclipse/
followed all the prompts and everything seems to be working fine now.
LDPI should be 36 x 36.
MDPI 48 x 48.
TVDPI 64 x 64.
HDPI 72 x 72.
XHDPI 96 x 96.
XXHDPI 144 x 144.
XXXHDPI 192 x 192.
How to easily throttle to a specific FPS:
// timestamps are ms passed since document creation.
// lastTimestamp can be initialized to 0, if main loop is executed immediately
var lastTimestamp = 0,
maxFPS = 30,
timestep = 1000 / maxFPS; // ms for each frame
function main(timestamp) {
window.requestAnimationFrame(main);
// skip if timestep ms hasn't passed since last frame
if (timestamp - lastTimestamp < timestep) return;
lastTimestamp = timestamp;
// draw frame here
}
window.requestAnimationFrame(main);
Source: A Detailed Explanation of JavaScript Game Loops and Timing by Isaac Sukin
select ROUND(CASE
WHEN CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then CONVERT( float, REPLACE( isnull( value3,''),',',''))
WHEN CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))!='' then CONVERT( float, REPLACE( isnull( value3,''),',',''))
WHEN CONVERT( float, REPLACE( isnull( value1,''),',',''))!='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then CONVERT( float, REPLACE( isnull( value3,''),',',''))
else CONVERT( float, REPLACE(isnull( value1,''),',','')) end,0) from Tablename where ID="123"
If you want to modify the original array instead of returning a new array, use .push()
...
array1.push.apply(array1, array2);
array1.push.apply(array1, array3);
I used .apply
to push the individual members of arrays 2
and 3
at once.
or...
array1.push.apply(array1, array2.concat(array3));
To deal with large arrays, you can do this in batches.
for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}
If you do this a lot, create a method or function to handle it.
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
and use it like this:
array1.pushArrayMembers(array2, array3);
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
value: function() {_x000D_
for (var i = 0; i < arguments.length; i++) {_x000D_
var to_add = arguments[i];_x000D_
for (var n = 0; n < to_add.length; n+=300) {_x000D_
push_apply(this, slice_call(to_add, n, n+300));_x000D_
}_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
You can use the below simple method of sorting:
datatable.DefaultView.Sort = "Col2 ASC,Col3 ASC,Col4 ASC";
By the above method, you will be able to sort N number of columns.
DONE=false
until $DONE
do
read line || DONE=true
echo $line
done < blah.txt
As stated in @John's answer, the fact that there is already a 0.1.2-SNAPSHOT
, interfered with my new non-SNAPSHOT version 0.1.2
. Since the 401 Unauthorized
error is nebulous and unhelpful--and is normally associated to user/pass problems--it's no surprise that I was unable to figure this out on my own.
Changing the version to 0.1.3
brings me back to my original error:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.4:install (default-install) on project xbnjava: Failed to install artifact com.github.aliteralmind:xbnjava:jar:0.1.3: R:\jeffy\programming\build\xbnjava-0.1.3\download\xbnjava-0.1.3-all.jar (The system cannot find the path specified) -> [Help 1].
A sonatype support person also recommended that I remove the <parent>
block from my POM (it's only there because it's in the one from ez-vcard, which is what I started with) and replace my <distributionManagement>
block with
<distributionManagement>
<snapshotRepository>
<id>ossrh</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
<repository>
<id>ossrh</id>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
and then make sure that lines up with what's in your settings.xml:
<settings>
<servers>
<server>
<id>ossrh</id>
<username>your-jira-id</username>
<password>your-jira-pwd</password>
</server>
</servers>
</settings>
After doing this, running mvn deploy
actually uploaded one of my jars for the very first time!!!
Output:
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building XBN-Java 0.1.3
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- build-helper-maven-plugin:1.8:attach-artifact (attach-artifacts) @ xbnjava ---
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ xbnjava ---
[INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\pom.xml to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.3\xbnjava-0.1.3.pom
[INFO] Installing R:\jeffy\programming\build\xbnjava-0.1.3\download\xbnjava-0.1.3.jar to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.3\xbnjava-0.1.3.jar
[INFO]
[INFO] --- maven-deploy-plugin:2.7:deploy (default-deploy) @ xbnjava ---
Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.3/xbnjava-0.1.3.pom
2/6 KB
4/6 KB
6/6 KB
Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.3/xbnjava-0.1.3.pom (6 KB at 4.6 KB/sec)
Downloading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml
310/310 B
Downloaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml (310 B at 1.6 KB/sec)
Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml
310/310 B
Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml (310 B at 1.4 KB/sec)
Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.3/xbnjava-0.1.3.jar
2/630 KB
4/630 KB
6/630 KB
8/630 KB
10/630 KB
12/630 KB
14/630 KB
...
618/630 KB
620/630 KB
622/630 KB
624/630 KB
626/630 KB
628/630 KB
630/630 KB
(Success portion:)
Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.3/xbnjava-0.1.3.jar (630 KB at 474.7 KB/sec)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.632 s
[INFO] Finished at: 2014-07-18T15:09:25-04:00
[INFO] Final Memory: 6M/19M
[INFO] ------------------------------------------------------------------------
Here's the full updated POM:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.github.aliteralmind</groupId>
<artifactId>xbnjava</artifactId>
<packaging>pom</packaging>
<version>0.1.3</version>
<name>XBN-Java</name>
<url>https://github.com/aliteralmind/xbnjava</url>
<inceptionYear>2014</inceptionYear>
<organization>
<name>Jeff Epstein</name>
</organization>
<description>XBN-Java is a collection of generically-useful backend (server side, non-GUI) programming utilities, featuring RegexReplacer and FilteredLineIterator. XBN-Java is the foundation of Codelet (http://codelet.aliteralmind.com).</description>
<licenses>
<license>
<name>Lesser General Public License (LGPL) version 3.0</name>
<url>https://www.gnu.org/licenses/lgpl-3.0.txt</url>
</license>
<license>
<name>Apache Software License (ASL) version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
</license>
</licenses>
<developers>
<developer>
<name>Jeff Epstein</name>
<email>[email protected]</email>
<roles>
<role>Lead Developer</role>
</roles>
</developer>
</developers>
<issueManagement>
<system>GitHub Issue Tracker</system>
<url>https://github.com/aliteralmind/xbnjava/issues</url>
</issueManagement>
<distributionManagement>
<snapshotRepository>
<id>ossrh</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
<repository>
<id>ossrh</id>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
<scm>
<connection>scm:git:[email protected]:aliteralmind/xbnjava.git</connection>
<url>scm:git:[email protected]:aliteralmind/xbnjava.git</url>
<developerConnection>scm:git:[email protected]:aliteralmind/xbnjava.git</developerConnection>
</scm>
<properties>
<java.version>1.7</java.version>
<jarprefix>R:\jeffy\programming\build\/${project.artifactId}-${project.version}/download/${project.artifactId}-${project.version}</jarprefix>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.8</version>
<executions>
<execution>
<id>attach-artifacts</id>
<phase>package</phase>
<goals>
<goal>attach-artifact</goal>
</goals>
<configuration>
<artifacts>
<artifact>
<file>${jarprefix}.jar</file>
<type>jar</type>
</artifact>
</artifacts>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<!--
This profile will sign the JAR file, sources file, and javadocs file using the GPG key on the local machine.
See: https://docs.sonatype.org/display/Repository/How+To+Generate+PGP+Signatures+With+Maven
-->
<profile>
<id>release-sign-artifacts</id>
<activation>
<property>
<name>release</name>
<value>true</value>
</property>
</activation>
</profile>
</profiles>
</project>
That's one big Maven problem out of the way. Only 627 more to go.
If you are not using the transferTo feature or non-blocking features you will not notice a difference between traditional IO and NIO(2) because the traditional IO maps to NIO.
But if you can use the NIO features like transferFrom/To or want to use Buffers, then of course NIO is the way to go.