I got a simple fix to this by casting the lists into strings and performing string operations to get the proper print out of the matrix.
By creating a function, it saves you the trouble of writing the for
loop every time you want to print out a matrix.
def print_matrix(matrix):
for row in matrix:
new_row = str(row)
new_row = new_row.replace(',','')
new_row = new_row.replace('[','')
new_row = new_row.replace(']','')
print(new_row)
Example of a 5x5 matrix with 0
as every entry:
>>> test_matrix = [[0] * 5 for i in range(5)]
>>> print_matrix(test_matrix)
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Example of a 2x3 matrix with 0
as every entry:
>>> test_matrix = [[0] * 3 for i in range(2)]
>>> print_matrix(test_matrix)
0 0 0
0 0 0
If you want to make it print:
A A A A A
B B B B B
C C C C C
D D D D D
E E E E E
I suggest you just change the way you enter your data into your lists within lists. In my method, each list within the larger list represents a line in the matrix, not columns.
Here is maybe a bit more readable form on the original approved answer.
const getSeconds = (hms: string) : number => {
const [hours, minutes, seconds] = hms.split(':');
return (+hours) * 60 * 60 + (+minutes) * 60 + (+seconds);
};
I enjoy the classic "what's the difference between a LinkedList and an ArrayList (or between a linked list and an array/vector) and why would you choose one or the other?"
The kind of answer I hope for is one that includes discussion of:
In your Service
class, add this:
@Override
public void onCreate(){
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
private void startMyOwnForeground(){
String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.icon_1)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
UPDATE: ANDROID 9.0 PIE (API 28)
Add this permission to your AndroidManifest.xml
file:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Just for completeness, you can get a list of kernels with jupyter kernelspec list
, but I ran into a case where one of the kernels did not show up in this list. You can find all kernel names by opening a Jupyter notebook and selecting Kernel -> Change kernel
. If you do not see everything in this list when you run jupyter kernelspec list
, try looking in common Jupyter folders:
ls ~/.local/share/jupyter/kernels # usually where local kernels go
ls /usr/local/share/jupyter/kernels # usually where system-wide kernels go
ls /usr/share/jupyter/kernels # also where system-wide kernels can go
Also, you can delete a kernel with jupyter kernelspec remove
or jupyter kernelspec uninstall
. The latter is an alias for remove
. From the in-line help text for the command:
uninstall
Alias for remove
remove
Remove one or more Jupyter kernelspecs by name.
Can't get much simpler than this :)
ssh host "test -e /path/to/file"
if [ $? -eq 0 ]; then
# your file exists
fi
As suggested by dimo414, this can be collapsed to:
if ssh host "test -e /path/to/file"; then
# your file exists
fi
If app is in the background mode or inactive(killed), and you click on Notification, you should check for the payload in LaunchScreen(in my case launch screen is MainActivity.java).
So in MainActivity.java on onCreate check for Extras:
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
Object value = getIntent().getExtras().get(key);
Log.d("MainActivity: ", "Key: " + key + " Value: " + value);
}
}
The collation is how SQL server decides on how to sort and compare text.
See MSDN.
I had a similar but it was dealing with dates. Query to show all items for the last month, works great without conditions until Jan. In order for it work correctly, needed to add a year and month variable
declare @yr int
declare @mth int
set @yr=(select case when month(getdate())=1 then YEAR(getdate())-1 else YEAR(getdate())end)
set @mth=(select case when month(getdate())=1 then month(getdate())+11 else month(getdate())end)
Now I just add the variable into condition: ...
(year(CreationTime)=@yr and MONTH(creationtime)=@mth)
No, you need to wrap your TextBlock in a Border. Example:
<Border BorderThickness="1" BorderBrush="Black">
<TextBlock ... />
</Border>
Of course, you can set these properties (BorderThickness
, BorderBrush
) through styles as well:
<Style x:Key="notCalledBorder" TargetType="{x:Type Border}">
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="Black" />
</Style>
<Border Style="{StaticResource notCalledBorder}">
<TextBlock ... />
</Border>
null
is a legal value (and reserved word) in JSON, but some environments do not have a "NULL" object (as opposed to a NULL
value) and hence cannot accurately represent the JSON null
. So they will sometimes represent it as an empty array.
Whether null
is a legal value in that particular element of that particular API is entirely up to the API designer.
This worked for me.
header = ['row1', 'row2', 'row3']
some_list = [1, 2, 3]
with open('test.csv', 'wt', newline ='') as file:
writer = csv.writer(file, delimiter=',')
writer.writerow(i for i in header)
for j in some_list:
writer.writerow(j)
You must not change the UI offside the main thread! UIKit is not thread safe, so that above problem and also some other weird problems will arise if you do that. The app can even crash.
So, to do the UIKit operations, you need to define block and let it be executed on the main queue: such as,
NSOperationQueue.mainQueue().addOperationWithBlock {
}
The hash is because the asset pipeline and server Optimize caching http://guides.rubyonrails.org/asset_pipeline.html
Try something like this:
background-image: url(image_path('check.png'));
Goodluck
There are some limitations with close()
that can be avoided if one uses shutdown()
instead.
close()
will terminate both directions on a TCP connection. Sometimes you want to tell the other endpoint that you are finished with sending data, but still want to receive data.
close()
decrements the descriptors reference count (maintained in file table entry and counts number of descriptors currently open that are referring to a file/socket) and does not close the socket/file if the descriptor is not 0. This means that if you are forking, the cleanup happens only after reference count drops to 0. With shutdown()
one can initiate normal TCP close sequence ignoring the reference count.
Parameters are as follows:
int shutdown(int s, int how); // s is socket descriptor
int how
can be:
SHUT_RD
or 0
Further receives are disallowed
SHUT_WR
or 1
Further sends are disallowed
SHUT_RDWR
or 2
Further sends and receives are disallowed
I see Federico you've found solution by yourself. The problem was in two places. Assignations need proper quoting, in your case
SOME_PATH="/$COMPANY/someProject/some path"
is one of possible solutions.
But in shell those quotes are not stored in a memory, so when you want to use this variable, you need to quote it again, for example:
NEW_VAR="$SOME_PATH"
because if not, space will be expanded to command level, like this:
NEW_VAR=/YourCompany/someProject/some path
which is not what you want.
For more info you can check out my article about it http://www.cofoh.com/white-shell
After installing the Office PIA (primary interop assemblies), add a reference to your project -> its on the .NET tab - component name "Office"
Button edit = (Button) view.findViewById(R.id.yourButton);
edit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(this, YourMainActivity.class);
startActivity(intent);
finish();
}
});
In CMake, you can add the following to your CMakelists
:
# install boost by apt-get method
include_directories(BEFORE SYSTEM "/usr/include")
# or install by building from src
# include_directories(BEFORE SYSTEM "/usr/local/include")
This method saved my serveral months. you can try it. By the way, as a temporary solution, you can rename directories you don't expect to find as below:
sudo mv /usr/local/include/boost /usr/local/include/boost_bak
Hopefully, it will help people who are in deep trouble like me.
Dont use a foreach then. Use a 'for loop'. Your code is a bit messed up but you could do something like...
for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)
{
double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;
}
Note you would have to take into account during the last row there will be no 'i+1' so you will have to use an if statement to catch that.
Use hashlib as hash()
was designed to be used to:
quickly compare dictionary keys during a dictionary lookup
and therefore does not guarantee that it will be the same across Python implementations.
Because apt-cache policy
will list all the matches available, even if not installed, I would suggest using this command for a more manageable shortlist of GTK-related packages installed on your system:
apt list --installed libgtk*
int i = 65;
char c = Convert.ToChar(i);
On OSX and VSCode 1.50.0 all I had to do was to close and restart VSCode and the problem went away.
My two cents here:
myvariable=$(mysql database -u $user -p$password -sse "SELECT A, B, C FROM table_a" 2>&1 \
| grep -v "Using a password")
Removes both the column names and the annoying (but necessary) password warning. Thanks @Dominic Bartl and John for this answer.
I had many issues involving C# and SqlServer. I ended up doing the following:
Also make sure that all your machines run on the same timezone.
Regarding the different result sets you get, your first example is "July First" while the second is "4th of July" ...
Also, the second example can be also interpreted as "April 7th", it depends on your server localization configuration (my solution doesn't suffer from this issue).
EDIT: hh was replaced with HH, as it doesn't seem to capture the correct hour on systems with AM/PM as opposed to systems with 24h clock. See the comments below.
You can use Path.GetFileName
to get the filename from the full path
private string[] pdfFiles = Directory.GetFiles("C:\\Documents", "*.pdf")
.Select(Path.GetFileName)
.ToArray();
EDIT: the solution above uses LINQ, so it requires .NET 3.5 at least. Here's a solution that works on earlier versions:
private string[] pdfFiles = GetFileNames("C:\\Documents", "*.pdf");
private static string[] GetFileNames(string path, string filter)
{
string[] files = Directory.GetFiles(path, filter);
for(int i = 0; i < files.Length; i++)
files[i] = Path.GetFileName(files[i]);
return files;
}
I agree that versioning the resource representation better follows the REST approach...but, one big problem with custom MIME types (or MIME types that append a version parameter) is the poor support to write to Accept and Content-Type headers in HTML and JavaScript.
For example, it is not possible IMO to POST with the following headers in HTML5 forms, in order to create a resource:
Accept: application/vnd.company.myapp-v3+json
Content-Type: application/vnd.company.myapp-v3+json
This is because the HTML5 enctype
attribute is an enumeration, therefore anything other than the usual application/x-www-formurlencoded
, multipart/form-data
and text/plain
are invalid.
...nor am I sure it is supported across all browsers in HTML4 (which has a more lax encytpe attribute, but would be a browser implementation issue as to whether the MIME type was forwarded)
Because of this I now feel the most appropriate way to version is via the URI, but I accept that it is not the 'correct' way.
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radio"
android:buttonTint="@color/my_color"/>
All button will change color, the circle box and the central check.
Use jQuery....I know you say you're trying to teach someone javascript, but teach him a cleaner technique... for instance, I could:
<select id="navigation">
<option value="unit_01.htm">Unit 1</option>
<option value="#5.2">Bookmark 2</option>
</select>
And with a little jQuery, you could do:
$("#navigation").change(function()
{
document.location.href = $(this).val();
});
Unobtrusive, and with clean separation of logic and UI.
Facebook Developer Wiki (unofficial) contain not only list of FQL error codes but others too it's somehow updated but not contain full list of possible error codes.
There is no any official or updated (I mean really updated) list of error codes returned by Graph API. Every list that can be found online is outdated and not help that much...
There is official list describing some of API Errors and basic recovery tactics. Also there is couple of offcial lists for specific codes:
I had the same problem and was solved by running the following in run
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
First off all I would like to thanks @MaximShoustin.
Thanks of you I have really nice table.
I provide some small modification in $scope.range
and $scope.setPage
.
In this way I have now possibility to go to the last page or come back to the first page.
Also when I'm going to next or prev page the navigation is changing when $scope.gap
is crossing. And the current page is not always on first position. For me it's looking more nicer.
Here is the new fiddle example: http://jsfiddle.net/qLBRZ/3/
Netflix also implements this feature
(function() {
try {
var $_console$$ = console;
Object.defineProperty(window, "console", {
get: function() {
if ($_console$$._commandLineAPI)
throw "Sorry, for security reasons, the script console is deactivated on netflix.com";
return $_console$$
},
set: function($val$$) {
$_console$$ = $val$$
}
})
} catch ($ignore$$) {
}
})();
They just override console._commandLineAPI
to throw security error.
To uninstall Ionic and Cordova:
sudo npm uninstall -g cordova
sudo npm uninstall -g ionic
To install:
sudo npm install -g cordova
You can use merge to combine two dataframes into one:
import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')
where on specifies field name that exists in both dataframes to join on, and how
defines whether its inner/outer/left/right join, with outer using 'union of keys from both frames (SQL: full outer join).' Since you have 'star' column in both dataframes, this by default will create two columns star_x and star_y in the combined dataframe. As @DanAllan mentioned for the join method, you can modify the suffixes for merge by passing it as a kwarg. Default is suffixes=('_x', '_y')
. if you wanted to do something like star_restaurant_id
and star_restaurant_review
, you can do:
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer', suffixes=('_restaurant_id', '_restaurant_review'))
The parameters are explained in detail in this link.
If you're using Maven 3, one option to work around this problem is to use the versions plugin http://www.mojohaus.org/versions-maven-plugin/
Specifically the commands,
mvn versions:set -DnewVersion=2.0-RELEASE
mvn versions:commit
This will update the parent and child poms to 2.0-RELEASE. You can run this as a build step before.
Unlike the release plugin, it doesn't try to talk to your source control
If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy and paste the filtered rows into your new worksheet?
Merge squash merges a tree (a sequence of commits) into a single commit. That is, it squashes all changes made in n commits into a single commit.
Rebasing is re-basing, that is, choosing a new base (parent commit) for a tree. Maybe the mercurial term for this is more clear: they call it transplant because it's just that: picking a new ground (parent commit, root) for a tree.
When doing an interactive rebase, you're given the option to either squash, pick, edit or skip the commits you are going to rebase.
Hope that was clear!
pgcrypto
ExtensionAs of Postgres 9.4, the pgcrypto
module includes the gen_random_uuid()
function. This function generates one of the random-number based Version 4 type of UUID.
Get contrib modules, if not already available.
sudo apt-get install postgresql-contrib-9.4
Use pgcrypto
module.
CREATE EXTENSION "pgcrypto";
The gen_random_uuid()
function should now available;
Example usage.
INSERT INTO items VALUES( gen_random_uuid(), 54.321, 31, 'desc 1', 31.94 ) ;
Quote from Postgres doc on uuid-ossp
module.
Note: If you only need randomly-generated (version 4) UUIDs, consider using the gen_random_uuid() function from the pgcrypto module instead.
There are many ways to nullify session in ASP.NET. Session in essence is a cookie, set on client's browser and in ASP.NET, its name is usually ASP.NET_SessionId
. So, theoretically if you delete that cookie (which in terms of browser means that you set its expiration date to some date in past, because cookies can't be deleted by developers), then you loose the session in server. Another way as you said is to use Session.Clear()
method. But the best way is to set another irrelevant object (usually null
value) in the session in correspondance to a key. For example, to nullify Session["FirstName"]
, simply set it to Session["FirstName"] = null
.
name = "John" // your variable
result = (name+" ")[:15] # this adds 15 spaces to the "name"
# but cuts it at 15 characters
It is very dependent of the engine that you use for generating html files. If you are using Hugo for generating htmls you have to write down like this:
<a href="https://example.com" target="_blank" rel="noopener"><span>Example Text</span> </a>.
You could use PIL to create (and display) an image:
from PIL import Image
import numpy as np
w, h = 512, 512
data = np.zeros((h, w, 3), dtype=np.uint8)
data[0:256, 0:256] = [255, 0, 0] # red patch in upper left
img = Image.fromarray(data, 'RGB')
img.save('my.png')
img.show()
Find out from netstat which process is running mongodb port (27017)
command:
sudo netstat -tulpn | grep :27017
Output will be:
tcp 0 0 0.0.0.0:27017 0.0.0.0:*
LISTEN 6432/mongod
In my case "6432" is the pid, it may be different in your case. Then kill that process using following command:
sudo kill <pid>
Thats it!
I'm surprised that nobody suggested guava solution yet:
com.google.common.collect.Iterables.get(collection, 0)
// or
com.google.common.collect.Iterables.get(collection, 0, defaultValue)
// or
com.google.common.collect.Iterables.getFirst(collection, defaultValue)
or if you expect single element:
com.google.common.collect.Iterables.getOnlyElement(collection, defaultValue)
// or
com.google.common.collect.Iterables.getOnlyElement(collection)
Be aware when using fileInputStream.available()
the returned integer does not have to represent the actual file size, but rather the guessed amount of bytes the system should be able to read from the stream without blocking IO. A safe and simple way could look like this
public String readStringFromInputStream(FileInputStream fileInputStream) {
StringBuffer stringBuffer = new StringBuffer();
try {
byte[] buffer;
while (fileInputStream.available() > 0) {
buffer = new byte[fileInputStream.available()];
fileInputStream.read(buffer);
stringBuffer.append(new String(buffer, "ISO-8859-1"));
}
} catch (FileNotFoundException e) {
} catch (IOException e) { }
return stringBuffer.toString();
}
It should be considered that this approach is not suitable for multi-byte character encodings like UTF-8.
put this to applog.sh
#!/bin/sh
PACKAGE=$1
APPPID=`adb -d shell ps | grep "${PACKAGE}" | cut -c10-15 | sed -e 's/ //g'`
adb -d logcat -v long \
| tr -d '\r' | sed -e '/^\[.*\]/ {N; s/\n/ /}' | grep -v '^$' \
| grep " ${APPPID}:"
then:
applog.sh com.example.my.package
I too had the same issue, but for me it was happening because I had a button with type "submit" within the modal form. I changed
<input type='submit' name='submitname' id="partyBtn" value='Submit' title='Click to submit.'/>
to
<input type='button' name='submitname' id="partyBtn" value='Submit' title='Click to submit.'/>
And that fixed the disappearance issue.
Just a word of caution. If you are trying to open an existing JKS keystore in Java 9 onwards, you need to make sure you mention the following properties too with value as "JKS":
javax.net.ssl.keyStoreType
javax.net.ssl.trustStoreType
The reason being that the default keystore type as prescribed in java.security file has been changed to pkcs12 from jks from Java 9 onwards.
I know this is an old post but I got the same error recently so for what it's worth, here's another solution:
This is usually a connection string error, please check the format of your connection string, you can look up 'entity framework connectionstring' or follow the suggestions above.
However, in my case my connection string was fine and the error was caused by something completely different so I hope this helps someone:
First I had an EDMX error: there was a new database table in the EDMX and the table did not exist in my database (funny thing is the error the error was not very obvious because it was not shown in my EDMX or output window, instead it was tucked away in visual studio in the 'Error List' window under the 'Warnings'). I resolved this error by adding the missing table to my database. But, I was actually busy trying to add a stored procedure and still getting the 'datasource' error so see below how i resolved it:
Stored procedure error: I was trying to add a stored procedure and everytime I added it via the EDMX design window I got a 'datasource' error. The solution was to add the stored procedure as blank (I kept the stored proc name and declaration but deleted the contents of the stored proc and replaced it with 'select 1' and retried adding it to the EDMX). It worked! Presumably EF didn't like something inside my stored proc. Once I'd added the proc to EF I was then able to update the contents of the proc on my database to what I wanted it to be and it works, 'datasource' error resolved.
weirdness
1. If you want to remove a marker you can do it as marker.remove();
alternatively you can also hide the marker instead of removing it as
marker.setVisible(false);
and make it visible later whenever needed.
2. However if you want to remove all markers from the map Use map.clear();
Note: map.clear();
will also remove Polylines, Circles
etc.
3. If you not want to remove Polylines, Circles
etc. than use a loop to the length of marker (if you have multiple markers) to remove those Check out the Example here OR set them Visible false And do not use map.clear();
in such case.
Please read this: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
You should set indicies for your html elements "name" attributes like planCompareViewModel[0].PlanId
, planCompareViewModel[1].PlanId
to make binder able to parse them into IEnumerable.
Instead of @foreach (var planVM in Model)
use for
loop and render names with indexes.
Using the Python boto3 SDK (and assuming credentials are setup for AWS), the following will delete a specified object in a bucket:
import boto3
client = boto3.client('s3')
client.delete_object(Bucket='mybucketname', Key='myfile.whatever')
The CP1 means 'Code Page 1' - technically this translates to code page 1252
Imports Newtonsoft.Json.Linq
Dim json As JObject = JObject.Parse(Me.TextBox1.Text)
MsgBox(json.SelectToken("Venue").SelectToken("ID"))
The best bet with these types of questions is to see exactly what python does. The dis
module is incredibly informative:
>>> import dis
>>> dis.dis("val != None")
1 0 LOAD_NAME 0 (val)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 3 (!=)
6 RETURN_VALUE
>>> dis.dis("not (val is None)")
1 0 LOAD_NAME 0 (val)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE
>>> dis.dis("val is not None")
1 0 LOAD_NAME 0 (val)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE
Notice that the last two cases reduce to the same sequence of operations, Python reads not (val is None)
and uses the is not
operator. The first uses the !=
operator when comparing with None
.
As pointed out by other answers, using !=
when comparing with None
is a bad idea.
I found the reason why the connection was not working, it was because the connection was trying to connect to port 8888, when it needed to connect to port 8889.
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
This fixed the problem, although changing the server name to localhost still gives the error.
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
But it connects successfully when the IP address is entered for the server name.
Echoing Data If It Exists
Sometimes you may wish to echo a variable, but you aren't sure if the variable has been set. We can express this in verbose PHP code like so:
{{ isset($name) ? $name : 'Default' }}
However, instead of writing a ternary statement, Blade provides you with the following convenient short-cut:
{{ $name or 'Default' }}
In this example, if the $name variable exists, its value will be displayed. However, if it does not exist, the word Default will be displayed.
The parser is having trouble concatenating your string. Try this:
write-host 'value is : '$i' '$($ds.Tables[1].Rows[$i][0])
Edit: Using double quotes might also be clearer since you can include the expressions within the quoted string:
write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
Solution for busybox, macOS bash, and non-bash shells
The accepted answer is certainly the best choice for bash. I'm working in a Busybox environment without access to bash, and it does not understand the exec > >(tee log.txt)
syntax. It also does not do exec >$PIPE
properly, trying to create an ordinary file with the same name as the named pipe, which fails and hangs.
Hopefully this would be useful to someone else who doesn't have bash.
Also, for anyone using a named pipe, it is safe to rm $PIPE
, because that unlinks the pipe from the VFS, but the processes that use it still maintain a reference count on it until they are finished.
Note the use of $* is not necessarily safe.
#!/bin/sh
if [ "$SELF_LOGGING" != "1" ]
then
# The parent process will enter this branch and set up logging
# Create a named piped for logging the child's output
PIPE=tmp.fifo
mkfifo $PIPE
# Launch the child process with stdout redirected to the named pipe
SELF_LOGGING=1 sh $0 $* >$PIPE &
# Save PID of child process
PID=$!
# Launch tee in a separate process
tee logfile <$PIPE &
# Unlink $PIPE because the parent process no longer needs it
rm $PIPE
# Wait for child process, which is running the rest of this script
wait $PID
# Return the error code from the child process
exit $?
fi
# The rest of the script goes here
Recent sdk-manager's download does not contain android-support-v7-appcompat.jar But the following dir contains aar file C:\Users\madan\android-sdks\extras\android\m2repository\com\ android\support\appcompat-v7\24.2.1\appcompat-v7-24.2.1.aar This file can be imported by right-click project, import, select general, select archieve and finally select aar file. Even this does not solve the problem. Later remove 'import android.R' and add 'import android.support.v7.appcompat.*;' Follow this tutorial for other details: http://www.srccodes.com/p/article/22/android-hello-world-example-using-eclipse-ide-and-android-development-tools-adt-plugin
Recently it became possible (but with an odd workaround).
To do this you must first create text with the desired hyperlink in an editor that supports rich text formatting. This can be an advanced text editor, web browser, email client, web-development IDE, etc.). Then copypaste the text from the editor or rendered HTML from browser (or other). E.g. in the example below I copypasted the head of this StackOverflow page. As you may see, the hyperlink have been copied correctly and is clickable in the message (checked on Mac Desktop, browser, and iOS apps).
On Mac
I was able to compose the desired link in the native Pages app as shown below. When you are done, copypaste your text into Slack app. This is the probably easiest way on Mac OS.
On Windows
I have a strong suspicion that MS Word will do the same trick, but unfortunately I don't have an installed instance to check.
Universal
Create text in an online editor, such as Google Documents. Use Insert -> Link, modify the text and web URL, then copypaste into Slack.
Try this:
Spinner popupSpinner = new Spinner(context, Spinner.MODE_DIALOG);
See this link for more details.
Despite there being loads of answers here, none of the suggestions for linking to the developers apps seem to work anymore.
When I last visited I was able to get it working using the format:
itms-apps://itunes.apple.com/developer/developer-name/id123456789
This no longer works, but removing the developer name does:
itms-apps://itunes.apple.com/developer/id123456789
I had same problem,
docker-compose down --rmi all
(in the same directory where you run docker-compose up)
helps
UPD: CAUTION - this will also delete the local docker images you've pulled (from comment)
Just came acreoss this, and since I had the same issue, I'd just post the results I came up with
when parsing, you could update the offset (ie I am parsing a data (1.1.2014) and I only want the date, 1st Jan 2014. On GMT+1 I'd get 31.12.2013. So I offset the value first.
moment(moment.utc('1.1.2014').format());
Well, came in handy for me to support across timezones
B
Set id for the textbox. ie,
<input type="text" name="txtJob" value="software engineer" id="txtJob">
In javascript
var jobValue = document.getElementById('txtJob').value
In Jquery
var jobValue = $("#txtJob").val();
If you'd like to capture all monitors, you can use the following code:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = ge.getScreenDevices();
Rectangle allScreenBounds = new Rectangle();
for (GraphicsDevice screen : screens) {
Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();
allScreenBounds.width += screenBounds.width;
allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);
}
Robot robot = new Robot();
BufferedImage screenShot = robot.createScreenCapture(allScreenBounds);
Using JQuery would take care of that browser inconsistency. With the jquery library included in your project simply write:
$('#yourDivName').html('yourtHTML');
You may also consider using:
$('#yourDivName').append('yourtHTML');
This will add your gallery as the last item in the selected div. Or:
$('#yourDivName').prepend('yourtHTML');
This will add it as the first item in the selected div.
See the JQuery docs for these functions:
public static function getCurrentUrl($withQuery = true)
{
$protocol = (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off')
or (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https')
or (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off')
or (isset($_SERVER['SERVER_PORT']) && intval($_SERVER['SERVER_PORT']) === 443) ? 'https' : 'http';
$uri = $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
return $withQuery ? $uri : str_replace('?' . $_SERVER['QUERY_STRING'], '', $uri);
}
I believe that, as stated above, using d2.update(d1)
is the best approach and that you can also copy d2
first if you still need it.
Although, I want to point out that dict(d1, **d2)
is actually a bad way to merge dictionnaries in general since keyword arguments need to be strings, thus it will fail if you have a dict
such as:
{
1: 'foo',
2: 'bar'
}
A simple solution to this console.log problem is to define the following at the beginning of your JS code:
if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };
This works for me in all browsers. This creates a dummy function for console.log when the debugger is not active. When the debugger is active, the method console.log is defined and executes normally.
Self-referencing as example
public class Employee {
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int ManagerId { get; set; }
public virtual Employee Manager { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
public Employee() {
Employees = new HashSet<Employee>();
}
}
HasMany(e => e.Employees)
.WithRequired(e => e.Manager)
.HasForeignKey(e => e.ManagerId)
.WillCascadeOnDelete(false);
I experienced this while trying to clone from an enterprise repository, and simply restarting the terminal solved it for me.
Does your script reference /bin/bash
or /bin/sh
in its hash bang line? The default system shell in Ubuntu is dash, not bash, so if you have #!/bin/sh
then your script will be using a different shell than you expect. Dash does not have the <<<
redirection operator.
Using this code to multiple order by in single query.
$this->db->from($this->table_name);
$this->db->order_by("column1 asc,column2 desc");
$query = $this->db->get();
return $query->result();
If you want to do the redirection within the Python script, setting sys.stdout
to a file object does the trick:
import sys
sys.stdout = open('file', 'w')
print('test')
sys.stdout.close()
A far more common method is to use shell redirection when executing (same on Windows and Linux):
$ python foo.py > file
I found this was caused by my JDK version.
I was having this problem with 'ant' and it was due to this CAUTION mentioned in the documentation:
http://developer.android.com/guide/publishing/app-signing.html#signapp
Caution: As of JDK 7, the default signing algorithim has changed, requiring you to specify the signature and digest algorithims (-sigalg and -digestalg) when you sign an APK.
I have JDK 7. In my Ant log, I used -v for verbose and it showed
$ ant -Dadb.device.arg=-d -v release install
[signjar] Executing 'C:\Program Files\Java\jdk1.7.0_03\bin\jarsigner.exe' with arguments:
[signjar] '-keystore'
[signjar] 'C:\cygwin\home\Chloe\pairfinder\release.keystore'
[signjar] '-signedjar'
[signjar] 'C:\cygwin\home\Chloe\pairfinder\bin\PairFinder-release-unaligned.apk'
[signjar] 'C:\cygwin\home\Chloe\pairfinder\bin\PairFinder-release-unsigned.apk'
[signjar] 'mykey'
[exec] pkg: /data/local/tmp/PairFinder-release.apk
[exec] Failure [INSTALL_PARSE_FAILED_NO_CERTIFICATES]
I signed the JAR manually and zipaligned it, but it gave a slightly different error:
$ "$JAVA_HOME"/bin/jarsigner -sigalg MD5withRSA -digestalg SHA1 -keystore release.keystore -signedjar bin/PairFinder-release-unaligned.apk bin/PairFinder-release-unsigned.apk mykey
$ zipalign -v -f 4 bin/PairFinder-release-unaligned.apk bin/PairFinder-release.apk
$ adb -d install -r bin/PairFinder-release.apk
pkg: /data/local/tmp/PairFinder-release.apk
Failure [INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES]
641 KB/s (52620 bytes in 0.080s)
I found that answered here.
How to deal with INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES without uninstallation
I only needed to uninstall it and then it worked!
$ adb -d uninstall com.kizbit.pairfinder
Success
$ adb -d install -r bin/PairFinder-release.apk
pkg: /data/local/tmp/PairFinder-release.apk
Success
641 KB/s (52620 bytes in 0.080s)
Now I only need modify the build.xml to use those options when signing!
Ok here it is: C:\Program Files\Java\android-sdk\tools\ant\build.xml
<signjar
sigalg="MD5withRSA"
digestalg="SHA1"
jar="${out.packaged.file}"
signedjar="${out.unaligned.file}"
keystore="${key.store}"
storepass="${key.store.password}"
alias="${key.alias}"
keypass="${key.alias.password}"
verbose="${verbose}" />
Using nginx/1.14.0
i have a websocket-server running on port 8097 and users connect from to wss on port 8098, nginx just decrypts the content and forwards it to the websocket server
So i have this config file (in my case /etc/nginx/conf.d/default.conf
)
server {
listen 8098;
ssl on;
ssl_certificate /etc/ssl/certs/domain.crt;
ssl_certificate_key /root/domain.key;
location / {
proxy_pass http://hostname:8097;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400;
}
}
dummy.xml (drawable should be of very less size. i have taken 24dp)
<?xml version="1.0" encoding="utf-8"?>
<layer-list android:opacity="transparent" xmlns:android="http://schemas.android.com/apk/res/android">
<item android:width="100dp" android:gravity="right" android:start="300dp">
<bitmap android:src="@drawable/down_button_dummy_dummy" android:gravity="center"/>
</item>
</layer-list>
layout file snippet
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardUseCompatPadding="true"
app:cardElevation="5dp"
>
<Spinner
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="@drawable/dummy">
</Spinner>
</android.support.v7.widget.CardView>
You can pass the inline handler the this
keyword, obtaining the element which fired the event.
like,
onclick="confirmSubmit(this);"
If you want to extract a raw-ish value from a HSSF cell, you can use something like this code fragment:
CellBase base = (CellBase) cell;
CellType cellType = cell.getCellType();
base.setCellType(CellType.STRING);
String result = cell.getStringCellValue();
base.setCellType(cellType);
At least for strings that are completely composed of digits (and automatically converted to numbers by Excel), this returns the original string (e.g. "12345"
) instead of a fractional value (e.g. "12345.0"
). Note that setCellType
is available in interface Cell
(as of v. 4.1) but deprecated and announced to be eliminated in v 5.x, whereas this method is still available in class CellBase
. Obviously, it would be nicer either to have getRawValue
in the Cell
interface or at least to be able use getStringCellValue
on non STRING cell types. Unfortunately, all replacements of setCellType
mentioned in the description won't cover this use case (maybe a member of the POI dev team reads this answer).
Both answers given worked for the problem I stated -- Thanks!
In my real application though, I was trying to constrain a panel inside of a ScrollViewer and Kent's method didn't handle that very well for some reason I didn't bother to track down. Basically the controls could expand beyond the MaxWidth setting and defeated my intent.
Nir's technique worked well and didn't have the problem with the ScrollViewer, though there is one minor thing to watch out for. You want to be sure the right and left margins on the TextBox are set to 0 or they'll get in the way. I also changed the binding to use ViewportWidth instead of ActualWidth to avoid issues when the vertical scrollbar appeared.
I couldn't find a direct GDrive/DropBox solution. I'm also surprised there's no lazy solution for a free ftp host. Windows azure offers a ftp server "FTP connector" that's fairly easy to turn on at: https://portal.azure.com
You can get a free 1 GB account by selecting "View All" machine types during your deployment.
SELECT SUBSTR(thatColumn, 1, 1) As NewColumn from student
You can get the same error in Asp.net MVC5 if you have a class name and a folder with a matching name Example : If you have class lands where when you want to see view/lands/index.cshtml file, if you also have a folder with name 'lands' you get the error as it first try the lands folder
Very few people realize the power of css positioning. To set the map to occupy 100% height of it's parent container do following:
#map_canvas_container {position: relative;}
#map_canvas {position: absolute; top: 0; right: 0; bottom: 0; left: 0;}
If you have any non absolutely positioned elements inside #map_canvas_container they will set the height of it and the map will take the exact available space.
Check this out on MSDN. It does not appear that you can do this with the implemented properties in the Socket class.
The poster on MSDN actually solved his problem using threading. He had a main thread which called out to other threads which run the connection code for a couple seconds and then check the Connected property of the socket:
I created another method wich actually connected the socket ... had the main thread sleep for 2 seconds and then check on the connecting method (wich is run in a separate thread) if the socket was connected good otherwise throw an exception "Timed out " and that;s all. Thanks again for the repleies.
What are you trying to do, and why can't it wait for 15-30 seconds before timing out?
I think what you're looking for is:
textBox1.Select();
in the constructor. (This is in C#. Maybe in VB that would be the same but without the semicolon.)
From http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx :
Focus is a low-level method intended primarily for custom control authors. Instead, application programmers should use the Select method or the ActiveControl property for child controls, or the Activate method for forms.
If you want to get a sub list including the last element, you leave blank after colon:
>>> ll=range(10)
>>> ll
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ll[5:]
[5, 6, 7, 8, 9]
>>> ll[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
When calling super()
to resolve to a parent's version of a classmethod, instance method, or staticmethod, we want to pass the current class whose scope we are in as the first argument, to indicate which parent's scope we're trying to resolve to, and as a second argument the object of interest to indicate which object we're trying to apply that scope to.
Consider a class hierarchy A
, B
, and C
where each class is the parent of the one following it, and a
, b
, and c
respective instances of each.
super(B, b)
# resolves to the scope of B's parent i.e. A
# and applies that scope to b, as if b was an instance of A
super(C, c)
# resolves to the scope of C's parent i.e. B
# and applies that scope to c
super(B, c)
# resolves to the scope of B's parent i.e. A
# and applies that scope to c
super
with a staticmethode.g. using super()
from within the __new__()
method
class A(object):
def __new__(cls, *a, **kw):
# ...
# whatever you want to specialize or override here
# ...
return super(A, cls).__new__(cls, *a, **kw)
Explanation:
1- even though it's usual for __new__()
to take as its first param a reference to the calling class, it is not implemented in Python as a classmethod, but rather a staticmethod. That is, a reference to a class has to be passed explicitly as the first argument when calling __new__()
directly:
# if you defined this
class A(object):
def __new__(cls):
pass
# calling this would raise a TypeError due to the missing argument
A.__new__()
# whereas this would be fine
A.__new__(A)
2- when calling super()
to get to the parent class we pass the child class A
as its first argument, then we pass a reference to the object of interest, in this case it's the class reference that was passed when A.__new__(cls)
was called. In most cases it also happens to be a reference to the child class. In some situations it might not be, for instance in the case of multiple generation inheritances.
super(A, cls)
3- since as a general rule __new__()
is a staticmethod, super(A, cls).__new__
will also return a staticmethod and needs to be supplied all arguments explicitly, including the reference to the object of insterest, in this case cls
.
super(A, cls).__new__(cls, *a, **kw)
4- doing the same thing without super
class A(object):
def __new__(cls, *a, **kw):
# ...
# whatever you want to specialize or override here
# ...
return object.__new__(cls, *a, **kw)
super
with an instance methode.g. using super()
from within __init__()
class A(object):
def __init__(self, *a, **kw):
# ...
# you make some changes here
# ...
super(A, self).__init__(*a, **kw)
Explanation:
1- __init__
is an instance method, meaning that it takes as its first argument a reference to an instance. When called directly from the instance, the reference is passed implicitly, that is you don't need to specify it:
# you try calling `__init__()` from the class without specifying an instance
# and a TypeError is raised due to the expected but missing reference
A.__init__() # TypeError ...
# you create an instance
a = A()
# you call `__init__()` from that instance and it works
a.__init__()
# you can also call `__init__()` with the class and explicitly pass the instance
A.__init__(a)
2- when calling super()
within __init__()
we pass the child class as the first argument and the object of interest as a second argument, which in general is a reference to an instance of the child class.
super(A, self)
3- The call super(A, self)
returns a proxy that will resolve the scope and apply it to self
as if it's now an instance of the parent class. Let's call that proxy s
. Since __init__()
is an instance method the call s.__init__(...)
will implicitly pass a reference of self
as the first argument to the parent's __init__()
.
4- to do the same without super
we need to pass a reference to an instance explicitly to the parent's version of __init__()
.
class A(object):
def __init__(self, *a, **kw):
# ...
# you make some changes here
# ...
object.__init__(self, *a, **kw)
super
with a classmethodclass A(object):
@classmethod
def alternate_constructor(cls, *a, **kw):
print "A.alternate_constructor called"
return cls(*a, **kw)
class B(A):
@classmethod
def alternate_constructor(cls, *a, **kw):
# ...
# whatever you want to specialize or override here
# ...
print "B.alternate_constructor called"
return super(B, cls).alternate_constructor(*a, **kw)
Explanation:
1- A classmethod can be called from the class directly and takes as its first parameter a reference to the class.
# calling directly from the class is fine,
# a reference to the class is passed implicitly
a = A.alternate_constructor()
b = B.alternate_constructor()
2- when calling super()
within a classmethod to resolve to its parent's version of it, we want to pass the current child class as the first argument to indicate which parent's scope we're trying to resolve to, and the object of interest as the second argument to indicate which object we want to apply that scope to, which in general is a reference to the child class itself or one of its subclasses.
super(B, cls_or_subcls)
3- The call super(B, cls)
resolves to the scope of A
and applies it to cls
. Since alternate_constructor()
is a classmethod the call super(B, cls).alternate_constructor(...)
will implicitly pass a reference of cls
as the first argument to A
's version of alternate_constructor()
super(B, cls).alternate_constructor()
4- to do the same without using super()
you would need to get a reference to the unbound version of A.alternate_constructor()
(i.e. the explicit version of the function). Simply doing this would not work:
class B(A):
@classmethod
def alternate_constructor(cls, *a, **kw):
# ...
# whatever you want to specialize or override here
# ...
print "B.alternate_constructor called"
return A.alternate_constructor(cls, *a, **kw)
The above would not work because the A.alternate_constructor()
method takes an implicit reference to A
as its first argument. The cls
being passed here would be its second argument.
class B(A):
@classmethod
def alternate_constructor(cls, *a, **kw):
# ...
# whatever you want to specialize or override here
# ...
print "B.alternate_constructor called"
# first we get a reference to the unbound
# `A.alternate_constructor` function
unbound_func = A.alternate_constructor.im_func
# now we call it and pass our own `cls` as its first argument
return unbound_func(cls, *a, **kw)
Try this
ImageView img
Bitmap bmp;
int width=100;
int height=100;
img=(ImageView)findViewById(R.id.imgView);
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.image);//image is your image
bmp=Bitmap.createScaledBitmap(bmp, width,height, true);
img.setImageBitmap(bmp);
Or If you want to load complete image size in memory then you can use
<ImageView
android:id="@+id/img"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/image"
android:scaleType="fitXY"/>
Maybe the easiest way is. Get the DeviceId Nuget package
And use it like
string deviceId = new DeviceIdBuilder()
.AddMachineName()
.AddMacAddress()
.AddProcessorId()
.AddMotherboardSerialNumber()
.ToString();
You can personalize the info used to generate the ID
From the manual, pathinfo:
<?php
$path_parts = pathinfo('/www/htdocs/index.html');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // Since PHP 5.2.0
?>
It doesn't have to be a complete path to operate properly. It will just as happily parse file.jpg
as /path/to/my/file.jpg
.
Greetings if i get you right you need a JavaScript function that doing it
function report(v) {
//To Do
switch(v) {
case "daily":
//Do something
break;
case "monthly":
//Do somthing
break;
}
}
Regards
This works for displaying purposes:
set(gca(), 'LooseInset', get(gca(), 'TightInset'));
Should work for printing as well.
Java 8 implementation (List initialized with 60
zeroes):
List<Integer> list = IntStream.of(new int[60])
.boxed()
.collect(Collectors.toList());
new int[N]
- creates an array filled with zeroes & length N boxed()
- each element boxed to an Integercollect(Collectors.toList())
- collects elements of streamSolved! The call build job: project, parameters: params
fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List
when params = [:]
. Replacing it with params = null
solved the issue.
Here the working code below.
def doCopyMibArtefactsHere(projectName) {
step ([
$class: 'CopyArtifact',
projectName: projectName,
filter: '**/**.mib',
fingerprintArtifacts: true,
flatten: true
]);
}
def BuildAndCopyMibsHere(projectName, params = null) {
build job: project, parameters: params
doCopyMibArtefactsHere(projectName)
}
node {
stage('Prepare Mib'){
BuildAndCopyMibsHere('project1')
}
}
If that is the entire line, it very well might be because you are missing a ;
at the end of the line.
According to the doc about Run tests by node ids
since you have all node ids in foo.txt, just run
pytest `cat foo.txt | tr '\n' ' '`
this is same with below command (with file content in the question)
pytest tests_directory/foo.py::test_001 tests_directory/bar.py::test_some_other_test
For future visitors: In the new HttpClient
(Angular 4.3+), the response
object is JSON by default, so you don't need to do response.json().data
anymore. Just use response
directly.
Example (modified from the official documentation):
import { HttpClient } from '@angular/common/http';
@Component(...)
export class YourComponent implements OnInit {
// Inject HttpClient into your component or service.
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.http.get('https://api.github.com/users')
.subscribe(response => console.log(response));
}
}
Don't forget to import it and include the module under imports in your project's app.module.ts:
...
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// Include it under 'imports' in your application module after BrowserModule.
HttpClientModule,
...
],
...
For center or positioning the background image you should use background-position
property .
The background-position property sets the starting position of a background image from top
and left
sides of the element .
The CSS Syntax is background-position : xvalue yvalue;
.
"xvalue" and "yvalue" supported values are length units like px
and percentage and direction names like left, right and etc .
The "xvalue" is the horizontal position of the background and starts from top of the element . It means if you use 50px
it will be "50px" away from top of the elements . And "yvalue" is the vertical position that has the same condition .
So if you use background-position: center;
your background image will be centered .
But I always use this code :
.yourclass {_x000D_
background: url(image.png) no-repeat center /cover;_x000D_
}
_x000D_
I know it is so confusing but it means :
.yourclass {_x000D_
background-image: url(image.png);_x000D_
background-position: center;_x000D_
background-size: cover;_x000D_
background-repeat: no-repeat;_x000D_
}
_x000D_
And I know that too the background-size
is a new property and in the compressed code what is /cover
but these codes means fill
background sizing and positioning in windows desktop background .
You can see more details about background-position
in here and background-size
in here .
IMPORTANT: It is safe to remove the workspace for a given Jenkins job as long as the job is not currently running!
NOTE: I am assuming your $JENKINS_HOME
is set to the default: /var/jenkins_home
.
rm -rf /var/jenkins_home/workspaces/<workspace>
rm -rf /var/jenkins_home/workspaces/*
This one uses grep to create a whitelist:
ls /var/jenkins_home/workspace \
| grep -v -E '(job-to-skip|another-job-to-skip)$' \
| xargs -I {} rm -rf /var/jenkins_home/workspace/{}
This one uses du and sort to list workspaces in order of largest to smallest. Then, it uses head to grab the first 10:
du -d 1 /var/jenkins_home/workspace \
| sort -n -r \
| head -n 10 \
| xargs -I {} rm -rf /var/jenkins_home/workspace/{}
In my case I don't have issues with ~/.composer
.
So being inside Laravel app root folder, I did sudo chown -R $USER composer.lock
and it was helpful.
Yes, just delete the branch by running git push origin :branchname
. To fix a new issue later, branch off from master again.
I adapted a PHP script I found to do just this. You can use it to find the corners of a box around a point (say, 20 km out). My specific example is for Google Maps API:
You can do like this
sqlcmd -S <server Name> -U sa -P sapassword -i inputquery_file_name -o outputfile_name
From your command prompt run sqlcmd /?
to get all the options you can use with sqlcmd
utility
Use DATE_FORMAT
select DATE_FORMAT(date,'%d') from tablename =>Date only
example:
select DATE_FORMAT(`date_column`,'%d') from `database_name`.`table_name`;
If you want to change background color, try this:
plt.rcParams['figure.facecolor'] = 'white'
Put a single quote before the field. Excel will treat it as text, even if it looks like a number.
...,`005,...
EDIT: This is wrong. The apostrophe trick only works when entering data directly into Excel. When you use it in a CSV file, the apostrophe appears in the field, which you don't want.
For Visual Studio Express 2013 to get rid of these problem you have to do the following.
Right click on your project click Properties. In properties window from left menus select Configuration Properties->C/C++->General
In right side select
Treat Warning As Errors NO
and
SDL Checks NO
Use this class in your layout :
public class ActionEditText extends EditText
{
public ActionEditText(Context context)
{
super(context);
}
public ActionEditText(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public ActionEditText(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs)
{
InputConnection conn = super.onCreateInputConnection(outAttrs);
outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
return conn;
}
}
In xml:
<com.test.custom.ActionEditText
android:id="@+id/postED"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:color/transparent"
android:gravity="top|left"
android:hint="@string/msg_type_message_here"
android:imeOptions="actionSend"
android:inputType="textMultiLine"
android:maxLines="5"
android:padding="5dip"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:textColor="@color/white"
android:textSize="20sp" />
You may try with below query :
INSERT INTO errortable (dateupdated,table1id)
VALUES (to_date(to_char(sysdate,'dd/mon/yyyy hh24:mi:ss'), 'dd/mm/yyyy hh24:mi:ss' ),1083 );
To view the result of it:
SELECT to_char(hire_dateupdated, 'dd/mm/yyyy hh24:mi:ss')
FROM errortable
WHERE table1id = 1083;
You should not be repeating the string
part when sending parameters.
int wordLength = wordLengthFunction(word); //you do not put string word here.
1) For me that's the most simple way passing parameters to async task is like this
// To call the async task do it like this
Boolean[] myTaskParams = { true, true, true };
myAsyncTask = new myAsyncTask ().execute(myTaskParams);
Declare and use the async task like here
private class myAsyncTask extends AsyncTask<Boolean, Void, Void> {
@Override
protected Void doInBackground(Boolean...pParams)
{
Boolean param1, param2, param3;
//
param1=pParams[0];
param2=pParams[1];
param3=pParams[2];
....
}
2) Passing methods to async-task In order to avoid coding the async-Task infrastructure (thread, messagenhandler, ...) multiple times you might consider to pass the methods which should be executed in your async-task as a parameter. Following example outlines this approach. In addition you might have the need to subclass the async-task to pass initialization parameters in the constructor.
/* Generic Async Task */
interface MyGenericMethod {
int execute(String param);
}
protected class testtask extends AsyncTask<MyGenericMethod, Void, Void>
{
public String mParam; // member variable to parameterize the function
@Override
protected Void doInBackground(MyGenericMethod... params) {
// do something here
params[0].execute("Myparameter");
return null;
}
}
// to start the asynctask do something like that
public void startAsyncTask()
{
//
AsyncTask<MyGenericMethod, Void, Void> mytest = new testtask().execute(new MyGenericMethod() {
public int execute(String param) {
//body
return 1;
}
});
}
I think this should work no?
ViewData["currentIndex"] = index;
From http://ora-01438.ora-code.com/ (the definitive resource outside of Oracle Support):
ORA-01438: value larger than specified precision allowed for this column
Cause: When inserting or updating records, a numeric value was entered that exceeded the precision defined for the column.
Action: Enter a value that complies with the numeric column's precision, or use the MODIFY option with the ALTER TABLE command to expand the precision.
http://ora-06512.ora-code.com/:
ORA-06512: at stringline string
Cause: Backtrace message as the stack is unwound by unhandled exceptions.
Action: Fix the problem causing the exception or write an exception handler for this condition. Or you may need to contact your application administrator or DBA.
I had this error when trying to convert a pdf to jpg and solved it using this method: sudo vi /etc/ImageMagick*/policy.xml
change:
policy domain="coder" rights="none" pattern="PDF"
to:
policy domain="coder" rights="read|write" pattern="PDF"
Source: http://realtechtalk.com/ImageMagick_Convert_PDF_Not_Authorized-2217-articles
Support for downloading binary files in using ajax is not great, it is very much still under development as working drafts.
You can have the browser download the requested file simply by using the code below, and this is supported in all browsers, and will obviously trigger the WebApi request just the same.
$scope.downloadFile = function(downloadPath) {
window.open(downloadPath, '_blank', '');
}
Using ajax to download the binary file can be done in some browsers and below is an implementation that will work in the latest flavours of Chrome, Internet Explorer, FireFox and Safari.
It uses an arraybuffer
response type, which is then converted into a JavaScript blob
, which is then either presented to save using the saveBlob
method - though this is only currently present in Internet Explorer - or turned into a blob data URL which is opened by the browser, triggering the download dialog if the mime type is supported for viewing in the browser.
Note: Internet Explorer 11 did not like using the msSaveBlob
function if it had been aliased - perhaps a security feature, but more likely a flaw, So using var saveBlob = navigator.msSaveBlob || navigator.webkitSaveBlob ... etc.
to determine the available saveBlob
support caused an exception; hence why the code below now tests for navigator.msSaveBlob
separately. Thanks? Microsoft
// Based on an implementation here: web.student.tuwien.ac.at/~e0427417/jsdownload.html
$scope.downloadFile = function(httpPath) {
// Use an arraybuffer
$http.get(httpPath, { responseType: 'arraybuffer' })
.success( function(data, status, headers) {
var octetStreamMime = 'application/octet-stream';
var success = false;
// Get the headers
headers = headers();
// Get the filename from the x-filename header or default to "download.bin"
var filename = headers['x-filename'] || 'download.bin';
// Determine the content type from the header or default to "application/octet-stream"
var contentType = headers['content-type'] || octetStreamMime;
try
{
// Try using msSaveBlob if supported
console.log("Trying saveBlob method ...");
var blob = new Blob([data], { type: contentType });
if(navigator.msSaveBlob)
navigator.msSaveBlob(blob, filename);
else {
// Try using other saveBlob implementations, if available
var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
if(saveBlob === undefined) throw "Not supported";
saveBlob(blob, filename);
}
console.log("saveBlob succeeded");
success = true;
} catch(ex)
{
console.log("saveBlob method failed with the following exception:");
console.log(ex);
}
if(!success)
{
// Get the blob url creator
var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
if(urlCreator)
{
// Try to use a download link
var link = document.createElement('a');
if('download' in link)
{
// Try to simulate a click
try
{
// Prepare a blob URL
console.log("Trying download link method with simulated click ...");
var blob = new Blob([data], { type: contentType });
var url = urlCreator.createObjectURL(blob);
link.setAttribute('href', url);
// Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
link.setAttribute("download", filename);
// Simulate clicking the download link
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);
console.log("Download link method with simulated click succeeded");
success = true;
} catch(ex) {
console.log("Download link method with simulated click failed with the following exception:");
console.log(ex);
}
}
if(!success)
{
// Fallback to window.location method
try
{
// Prepare a blob URL
// Use application/octet-stream when using window.location to force download
console.log("Trying download link method with window.location ...");
var blob = new Blob([data], { type: octetStreamMime });
var url = urlCreator.createObjectURL(blob);
window.location = url;
console.log("Download link method with window.location succeeded");
success = true;
} catch(ex) {
console.log("Download link method with window.location failed with the following exception:");
console.log(ex);
}
}
}
}
if(!success)
{
// Fallback to window.open method
console.log("No methods worked for saving the arraybuffer, using last resort window.open");
window.open(httpPath, '_blank', '');
}
})
.error(function(data, status) {
console.log("Request failed with status: " + status);
// Optionally write the error out to scope
$scope.errorDetails = "Request failed with status: " + status;
});
};
var downloadPath = "/files/instructions.pdf";
$scope.downloadFile(downloadPath);
You should modify your WebApi method to return the following headers:
I have used the x-filename
header to send the filename. This is a custom header for convenience, you could however extract the filename from the content-disposition
header using regular expressions.
You should set the content-type
mime header for your response too, so the browser knows the data format.
I hope this helps.
Please try this. This query can be used for date comparison
select * from [User] U where convert(varchar(10),U.DateCreated, 120) = '2014-02-07'
in web application in .cs page
txtbox.Style.Add("background-color","black");
in css specify it by using backcolor property
I know this post is realy old but now that some time and ant versions passed there is a way to do this with basic ant features and i thought i should share it.
It's done via a recursive macrodef that calls nested tasks (even other macros may be called). The only convention is to use a fixed variable name (element here).
<project name="iteration-test" default="execute" xmlns="antlib:org.apache.tools.ant" xmlns:if="ant:if" xmlns:unless="ant:unless">
<macrodef name="iterate">
<attribute name="list" />
<element name="call" implicit="yes" />
<sequential>
<local name="element" />
<local name="tail" />
<local name="hasMoreElements" />
<!-- unless to not get a error on empty lists -->
<loadresource property="element" unless:blank="@{list}" >
<concat>@{list}</concat>
<filterchain>
<replaceregex pattern="([^;]*).*" replace="\1" />
</filterchain>
</loadresource>
<!-- call the tasks that handle the element -->
<call />
<!-- recursion -->
<condition property="hasMoreElements">
<contains string="@{list}" substring=";" />
</condition>
<loadresource property="tail" if:true="${hasMoreElements}">
<concat>@{list}</concat>
<filterchain>
<replaceregex pattern="[^;]*;(.*)" replace="\1" />
</filterchain>
</loadresource>
<iterate list="${tail}" if:true="${hasMoreElements}">
<call />
</iterate>
</sequential>
</macrodef>
<target name="execute">
<fileset id="artifacts.fs" dir="build/lib">
<include name="*.jar" />
<include name="*.war" />
</fileset>
<pathconvert refid="artifacts.fs" property="artifacts.str" />
<echo message="$${artifacts.str}: ${artifacts.str}" />
<!-- unless is required for empty lists to not call the enclosed tasks -->
<iterate list="${artifacts.str}" unless:blank="${artifacts.str}">
<echo message="I see:" />
<echo message="${element}" />
</iterate>
<!-- local variable is now empty -->
<echo message="${element}" />
</target>
</project>
The key features needed where:
I didnt manage to make the delimiter variabel, but this may not be a major downside.
When generating CSR is possible to specify -ext attribute again to have it inserted in the CSR
keytool -certreq -file test.csr -keystore test.jks -alias testAlias -ext SAN=dns:test.example.com
complete example here: How to create CSR with SANs using keytool
I rewrote c++ solution in first answer in powershell script. Script can determine this types of .exe and .dll files:
#Description C# compiler switch PE type machine corflags
#MSIL /platform:anycpu (default) PE32 x86 ILONLY
#MSIL 32 bit pref /platform:anycpu32bitpreferred PE32 x86 ILONLY | 32BITREQUIRED | 32BITPREFERRED
#x86 managed /platform:x86 PE32 x86 ILONLY | 32BITREQUIRED
#x86 mixed n/a PE32 x86 32BITREQUIRED
#x64 managed /platform:x64 PE32+ x64 ILONLY
#x64 mixed n/a PE32+ x64
#ARM managed /platform:arm PE32 ARM ILONLY
#ARM mixed n/a PE32 ARM
this solution has some advantages over corflags.exe and loading assembly via Assembly.Load in C# - you will never get BadImageFormatException or message about invalid header.
function GetActualAddressFromRVA($st, $sec, $numOfSec, $dwRVA)
{
[System.UInt32] $dwRet = 0;
for($j = 0; $j -lt $numOfSec; $j++)
{
$nextSectionOffset = $sec + 40*$j;
$VirtualSizeOffset = 8;
$VirtualAddressOffset = 12;
$SizeOfRawDataOffset = 16;
$PointerToRawDataOffset = 20;
$Null = @(
$curr_offset = $st.BaseStream.Seek($nextSectionOffset + $VirtualSizeOffset, [System.IO.SeekOrigin]::Begin);
[System.UInt32] $VirtualSize = $b.ReadUInt32();
[System.UInt32] $VirtualAddress = $b.ReadUInt32();
[System.UInt32] $SizeOfRawData = $b.ReadUInt32();
[System.UInt32] $PointerToRawData = $b.ReadUInt32();
if ($dwRVA -ge $VirtualAddress -and $dwRVA -lt ($VirtualAddress + $VirtualSize)) {
$delta = $VirtualAddress - $PointerToRawData;
$dwRet = $dwRVA - $delta;
return $dwRet;
}
);
}
return $dwRet;
}
function Get-Bitness2([System.String]$path, $showLog = $false)
{
$Obj = @{};
$Obj.Result = '';
$Obj.Error = $false;
$Obj.Log = @(Split-Path -Path $path -Leaf -Resolve);
$b = new-object System.IO.BinaryReader([System.IO.File]::Open($path,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read, [System.IO.FileShare]::Read));
$curr_offset = $b.BaseStream.Seek(0x3c, [System.IO.SeekOrigin]::Begin)
[System.Int32] $peOffset = $b.ReadInt32();
$Obj.Log += 'peOffset ' + "{0:X0}" -f $peOffset;
$curr_offset = $b.BaseStream.Seek($peOffset, [System.IO.SeekOrigin]::Begin);
[System.UInt32] $peHead = $b.ReadUInt32();
if ($peHead -ne 0x00004550) {
$Obj.Error = $true;
$Obj.Result = 'Bad Image Format';
$Obj.Log += 'cannot determine file type (not x64/x86/ARM) - exit with error';
};
if ($Obj.Error)
{
$b.Close();
Write-Host ($Obj.Log | Format-List | Out-String);
return $false;
};
[System.UInt16] $machineType = $b.ReadUInt16();
$Obj.Log += 'machineType ' + "{0:X0}" -f $machineType;
[System.UInt16] $numOfSections = $b.ReadUInt16();
$Obj.Log += 'numOfSections ' + "{0:X0}" -f $numOfSections;
if (($machineType -eq 0x8664) -or ($machineType -eq 0x200)) { $Obj.Log += 'machineType: x64'; }
elseif ($machineType -eq 0x14c) { $Obj.Log += 'machineType: x86'; }
elseif ($machineType -eq 0x1c0) { $Obj.Log += 'machineType: ARM'; }
else{
$Obj.Error = $true;
$Obj.Log += 'cannot determine file type (not x64/x86/ARM) - exit with error';
};
if ($Obj.Error) {
$b.Close();
Write-Output ($Obj.Log | Format-List | Out-String);
return $false;
};
$curr_offset = $b.BaseStream.Seek($peOffset+20, [System.IO.SeekOrigin]::Begin);
[System.UInt16] $sizeOfPeHeader = $b.ReadUInt16();
$coffOffset = $peOffset + 24;#PE header size is 24 bytes
$Obj.Log += 'coffOffset ' + "{0:X0}" -f $coffOffset;
$curr_offset = $b.BaseStream.Seek($coffOffset, [System.IO.SeekOrigin]::Begin);#+24 byte magic number
[System.UInt16] $pe32 = $b.ReadUInt16();
$clr20headerOffset = 0;
$flag32bit = $false;
$Obj.Log += 'pe32 magic number: ' + "{0:X0}" -f $pe32;
$Obj.Log += 'size of optional header ' + ("{0:D0}" -f $sizeOfPeHeader) + " bytes";
#COMIMAGE_FLAGS_ILONLY =0x00000001,
#COMIMAGE_FLAGS_32BITREQUIRED =0x00000002,
#COMIMAGE_FLAGS_IL_LIBRARY =0x00000004,
#COMIMAGE_FLAGS_STRONGNAMESIGNED =0x00000008,
#COMIMAGE_FLAGS_NATIVE_ENTRYPOINT =0x00000010,
#COMIMAGE_FLAGS_TRACKDEBUGDATA =0x00010000,
#COMIMAGE_FLAGS_32BITPREFERRED =0x00020000,
$COMIMAGE_FLAGS_ILONLY = 0x00000001;
$COMIMAGE_FLAGS_32BITREQUIRED = 0x00000002;
$COMIMAGE_FLAGS_32BITPREFERRED = 0x00020000;
$offset = 96;
if ($pe32 -eq 0x20b) {
$offset = 112;#size of COFF header is bigger for pe32+
}
$clr20dirHeaderOffset = $coffOffset + $offset + 14*8;#clr directory header offset + start of section number 15 (each section is 8 byte long);
$Obj.Log += 'clr20dirHeaderOffset ' + "{0:X0}" -f $clr20dirHeaderOffset;
$curr_offset = $b.BaseStream.Seek($clr20dirHeaderOffset, [System.IO.SeekOrigin]::Begin);
[System.UInt32] $clr20VirtualAddress = $b.ReadUInt32();
[System.UInt32] $clr20Size = $b.ReadUInt32();
$Obj.Log += 'clr20VirtualAddress ' + "{0:X0}" -f $clr20VirtualAddress;
$Obj.Log += 'clr20SectionSize ' + ("{0:D0}" -f $clr20Size) + " bytes";
if ($clr20Size -eq 0) {
if ($machineType -eq 0x1c0) { $Obj.Result = 'ARM native'; }
elseif ($pe32 -eq 0x10b) { $Obj.Result = '32-bit native'; }
elseif($pe32 -eq 0x20b) { $Obj.Result = '64-bit native'; }
$b.Close();
if ($Obj.Result -eq '') {
$Obj.Error = $true;
$Obj.Log += 'Unknown type of file';
}
else {
if ($showLog) { Write-Output ($Obj.Log | Format-List | Out-String); };
return $Obj.Result;
}
};
if ($Obj.Error) {
$b.Close();
Write-Host ($Obj.Log | Format-List | Out-String);
return $false;
};
[System.UInt32]$sectionsOffset = $coffOffset + $sizeOfPeHeader;
$Obj.Log += 'sectionsOffset ' + "{0:X0}" -f $sectionsOffset;
$realOffset = GetActualAddressFromRVA $b $sectionsOffset $numOfSections $clr20VirtualAddress;
$Obj.Log += 'real IMAGE_COR20_HEADER offset ' + "{0:X0}" -f $realOffset;
if ($realOffset -eq 0) {
$Obj.Error = $true;
$Obj.Log += 'cannot find COR20 header - exit with error';
$b.Close();
return $false;
};
if ($Obj.Error) {
$b.Close();
Write-Host ($Obj.Log | Format-List | Out-String);
return $false;
};
$curr_offset = $b.BaseStream.Seek($realOffset + 4, [System.IO.SeekOrigin]::Begin);
[System.UInt16] $majorVer = $b.ReadUInt16();
[System.UInt16] $minorVer = $b.ReadUInt16();
$Obj.Log += 'IMAGE_COR20_HEADER version ' + ("{0:D0}" -f $majorVer) + "." + ("{0:D0}" -f $minorVer);
$flagsOffset = 16;#+16 bytes - flags field
$curr_offset = $b.BaseStream.Seek($realOffset + $flagsOffset, [System.IO.SeekOrigin]::Begin);
[System.UInt32] $flag32bit = $b.ReadUInt32();
$Obj.Log += 'CorFlags: ' + ("{0:X0}" -f $flag32bit);
#Description C# compiler switch PE type machine corflags
#MSIL /platform:anycpu (default) PE32 x86 ILONLY
#MSIL 32 bit pref /platform:anycpu32bitpreferred PE32 x86 ILONLY | 32BITREQUIRED | 32BITPREFERRED
#x86 managed /platform:x86 PE32 x86 ILONLY | 32BITREQUIRED
#x86 mixed n/a PE32 x86 32BITREQUIRED
#x64 managed /platform:x64 PE32+ x64 ILONLY
#x64 mixed n/a PE32+ x64
#ARM managed /platform:arm PE32 ARM ILONLY
#ARM mixed n/a PE32 ARM
$isILOnly = ($flag32bit -band $COMIMAGE_FLAGS_ILONLY) -eq $COMIMAGE_FLAGS_ILONLY;
$Obj.Log += 'ILONLY: ' + $isILOnly;
if ($machineType -eq 0x1c0) {#if ARM
if ($isILOnly) { $Obj.Result = 'ARM managed'; }
else { $Obj.Result = 'ARM mixed'; }
}
elseif ($pe32 -eq 0x10b) {#pe32
$is32bitRequired = ($flag32bit -band $COMIMAGE_FLAGS_32BITREQUIRED) -eq $COMIMAGE_FLAGS_32BITREQUIRED;
$is32bitPreffered = ($flag32bit -band $COMIMAGE_FLAGS_32BITPREFERRED) -eq $COMIMAGE_FLAGS_32BITPREFERRED;
$Obj.Log += '32BIT: ' + $is32bitRequired;
$Obj.Log += '32BIT PREFFERED: ' + $is32bitPreffered
if ($is32bitRequired -and $isILOnly -and $is32bitPreffered) { $Obj.Result = 'AnyCpu 32bit-preffered'; }
elseif ($is32bitRequired -and $isILOnly -and !$is32bitPreffered){ $Obj.Result = 'x86 managed'; }
elseif (!$is32bitRequired -and !$isILOnly -and $is32bitPreffered) { $Obj.Result = 'x86 mixed'; }
elseif ($isILOnly) { $Obj.Result = 'AnyCpu'; }
}
elseif ($pe32 -eq 0x20b) {#pe32+
if ($isILOnly) { $Obj.Result = 'x64 managed'; }
else { $Obj.Result = 'x64 mixed'; }
}
$b.Close();
if ($showLog) { Write-Host ($Obj.Log | Format-List | Out-String); }
if ($Obj.Result -eq ''){ return 'Unknown type of file';};
$flags = '';
if ($isILOnly) {$flags += 'ILONLY';}
if ($is32bitRequired) {
if ($flags -ne '') {$flags += ' | ';}
$flags += '32BITREQUIRED';
}
if ($is32bitPreffered) {
if ($flags -ne '') {$flags += ' | ';}
$flags += '32BITPREFERRED';
}
if ($flags -ne '') {$flags = ' (' + $flags +')';}
return $Obj.Result + $flags;
}
usage example:
#$filePath = "C:\Windows\SysWOW64\regedit.exe";#32 bit native on 64bit windows
$filePath = "C:\Windows\regedit.exe";#64 bit native on 64bit windows | should be 32 bit native on 32bit windows
Get-Bitness2 $filePath $true;
you can omit second parameter if you don't need to see details
It passes control to the next matching route. In the example you give, for instance, you might look up the user in the database if an id
was given, and assign it to req.user
.
Below, you could have a route like:
app.get('/users', function(req, res) {
// check for and maybe do something with req.user
});
Since /users/123 will match the route in your example first, that will first check and find user 123
; then /users
can do something with the result of that.
Route middleware is a more flexible and powerful tool, though, in my opinion, since it doesn't rely on a particular URI scheme or route ordering. I'd be inclined to model the example shown like this, assuming a Users
model with an async findOne()
:
function loadUser(req, res, next) {
if (req.params.userId) {
Users.findOne({ id: req.params.userId }, function(err, user) {
if (err) {
next(new Error("Couldn't find user: " + err));
return;
}
req.user = user;
next();
});
} else {
next();
}
}
// ...
app.get('/user/:userId', loadUser, function(req, res) {
// do something with req.user
});
app.get('/users/:userId?', loadUser, function(req, res) {
// if req.user was set, it's because userId was specified (and we found the user).
});
// Pretend there's a "loadItem()" which operates similarly, but with itemId.
app.get('/item/:itemId/addTo/:userId', loadItem, loadUser, function(req, res) {
req.user.items.append(req.item.name);
});
Being able to control flow like this is pretty handy. You might want to have certain pages only be available to users with an admin flag:
/**
* Only allows the page to be accessed if the user is an admin.
* Requires use of `loadUser` middleware.
*/
function requireAdmin(req, res, next) {
if (!req.user || !req.user.admin) {
next(new Error("Permission denied."));
return;
}
next();
}
app.get('/top/secret', loadUser, requireAdmin, function(req, res) {
res.send('blahblahblah');
});
Hope this gave you some inspiration!
Data
a=[0 3 0 0 7 10 3 0 1 0 7 7 1 7 4]
Do
aa=nonzeros(a)'
Result
aa=[3 7 10 3 1 7 7 1 7 4]
According to the documentation for that plugin, .visible()
returns a boolean indicating if the element is visible. So you'd use it like this:
if ($('#element').visible(true)) {
// The element is visible, do something
} else {
// The element is NOT visible, do something else
}
The admin and manager apps are two separate things. Here's a snapshot of a tomcat-users.xml file that works, try this:
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="tomcat"/>
<role rolename="role1"/>
<role rolename="manager"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="both" password="tomcat" roles="tomcat,role1"/>
<user username="role1" password="tomcat" roles="role1"/>
<user username="USERNAME" password="PASSWORD" roles="manager,tomcat,role1"/>
</tomcat-users>
It works for me very well
Unlike C++, Java does not support user defined operator overloading. The overloading is done internally in java.
We can take +
(plus) for example:
int a = 2 + 4;
string = "hello" + "world";
Here, plus adds two integer numbers and concatenates two strings. So we can say that Java supports internal operator overloading but not user defined.
Well Curl could be a better option for json representation but in that case it would be difficult to understand the structure of json because its in command line. if you want to get your json on browser you simply remove all the XML Annotations like -
@XmlRootElement(name="person")
@XmlAccessorType(XmlAccessType.NONE)
@XmlAttribute
@XmlElement
from your model class and than run the same url, you have used for xml representation.
Make sure that you have jacson-databind dependency in your pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1</version>
</dependency>
if [ [[ $HOST == user1 ]] -o [[ $HOST == node* ]] ];
then
echo yes
fi
doesn't work, because all of [
, [[
, and test
recognize the same nonrecursive grammar. See section CONDITIONAL EXPRESSIONS on your Bash man page.
As an aside, the SUSv3 says
The KornShell-derived conditional command (double bracket [[]]) was removed from the shell command language description in an early proposal. Objections were raised that the real problem is misuse of the test command ([), and putting it into the shell is the wrong way to fix the problem. Instead, proper documentation and a new shell reserved word (!) are sufficient.
Tests that require multiple test operations can be done at the shell level using individual invocations of the test command and shell logicals, rather than using the error-prone -o flag of test.
You'd need to write it this way, but test doesn't support it:
if [ $HOST == user1 -o $HOST == node* ];
then
echo yes
fi
test uses = for string equality, and more importantly it doesn't support pattern matching.
case
/ esac
has good support for pattern matching:
case $HOST in
user1|node*) echo yes ;;
esac
It has the added benefit that it doesn't depend on Bash, and the syntax is portable. From the Single Unix Specification, The Shell Command Language:
case word in
[(]pattern1) compound-list;;
[[(]pattern[ | pattern] ... ) compound-list;;] ...
[[(]pattern[ | pattern] ... ) compound-list]
esac
Canvas element doesn't support such characters as newline '\n', tab '\t' or < br /> tag.
Try it:
var newrow = mheight + 30;
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.font = "bold 24px 'Verdana'";
ctx.textAlign = "center";
ctx.fillText("Game Over", mwidth, mheight); //first line
ctx.fillText("play again", mwidth, newrow); //second line
or perhaps multiple lines:
var textArray = new Array('line2', 'line3', 'line4', 'line5');
var rows = 98;
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.font = "bold 24px 'Verdana'";
ctx.textAlign = "center";
ctx.fillText("Game Over", mwidth, mheight); //first line
for(var i=0; i < textArray.length; ++i) {
rows += 30;
ctx.fillText(textArray[i], mwidth, rows);
}
Have you tried using the WebClient class?
you should be able to use
string result = "";
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);
Documentation at
http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspx
http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx
input.name()
needs to be inside a function; classes contain declarations, not random code.
You have multiple options, each with different general use cases.
The first would be to use a for
loop, as you described, but in the following way.
for value in array:
print(value, end=' ')
You could also use str.join
for a simple, readable one-liner using comprehension. This method would be good for storing this value to a variable.
print(' '.join(str(value) for value in array))
My favorite method, however, would be to pass array
as *args
, with a sep
of ' '
. Note, however, that this method will only produce a print
ed output, not a value that may be stored to a variable.
print(*array, sep=' ')
Mark Reed suggested a very good solution for 2D arrays (matrix)! They always can be converted in a 1D array (vector). Although Bash doesn't have a native support for 2D arrays, it's not that hard to create a simple ADT around the mentioned principle.
Here is a barebone example with no argument checks, etc, just to keep the solution clear: the array's size is set as two first elements in the instance (documentation for the Bash module that implements a matrix ADT, https://github.com/vorakl/bash-libs/blob/master/src.docs/content/pages/matrix.rst )
#!/bin/bash
matrix_init() {
# matrix_init instance x y data ...
declare -n self=$1
declare -i width=$2 height=$3
shift 3;
self=(${width} ${height} "$@")
}
matrix_get() {
# matrix_get instance x y
declare -n self=$1
declare -i x=$2 y=$3
declare -i width=${self[0]} height=${self[1]}
echo "${self[2+y*width+x]}"
}
matrix_set() {
# matrix_set instance x y data
declare -n self=$1
declare -i x=$2 y=$3
declare data="$4"
declare -i width=${self[0]} height=${self[1]}
self[2+y*width+x]="${data}"
}
matrix_destroy() {
# matrix_destroy instance
declare -n self=$1
unset self
}
# my_matrix[3][2]=( (one, two, three), ("1 1" "2 2" "3 3") )
matrix_init my_matrix \
3 2 \
one two three \
"1 1" "2 2" "3 3"
# print my_matrix[2][0]
matrix_get my_matrix 2 0
# print my_matrix[1][1]
matrix_get my_matrix 1 1
# my_matrix[1][1]="4 4 4"
matrix_set my_matrix 1 1 "4 4 4"
# print my_matrix[1][1]
matrix_get my_matrix 1 1
# remove my_matrix
matrix_destroy my_matrix
Just in case you want to try something else. This is what worked for me:
Based on Ternary Operator which has following structure:
condition ? value-if-true : value-if-false
As result:
{{gallery.date?(gallery.date | date:'mediumDate'):"Various" }}
Don't Return Empty Json
In My Case I was returning Empty Json
String in .Net Core Web API
Project.
So I Changed My Code
From
return Ok();
To
return Ok("Done");
It seems you have to return some string or object.
Hope this helps.
You can use the LinearProgressIndicator
provided by the Material Components Library and the app:trackThickness
attribute:
<com.google.android.material.progressindicator.LinearProgressIndicator
android:indeterminate="true"
app:trackThickness="xxdp"
../>
With 12dp
:
With 4dp
:
Note: it requires at least the version 1.3.0-alpha04
.
@DSM's answer is perfectly fine in almost any normal scenario. But if you're the type of programmer who wants to go a little deeper than the surface level, you might be interested to know that it is a little faster to call numpy functions on the underlying .to_numpy()
(or .values
for <0.24) array instead of directly calling the (cythonized) functions defined on the DataFrame/Series objects.
For example, you can use ndarray.max()
along the first axis.
# Data borrowed from @DSM's post.
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
df
A B
0 1 -2
1 2 8
2 3 1
df['C'] = df[['A', 'B']].values.max(1)
# Or, assuming "A" and "B" are the only columns,
# df['C'] = df.values.max(1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
If your data has NaN
s, you will need numpy.nanmax
:
df['C'] = np.nanmax(df.values, axis=1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
You can also use numpy.maximum.reduce
. numpy.maximum
is a ufunc (Universal Function), and every ufunc has a reduce
:
df['C'] = np.maximum.reduce(df['A', 'B']].values, axis=1)
# df['C'] = np.maximum.reduce(df[['A', 'B']], axis=1)
# df['C'] = np.maximum.reduce(df, axis=1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
np.maximum.reduce
and np.max
appear to be more or less the same (for most normal sized DataFrames)—and happen to be a shade faster than DataFrame.max
. I imagine this difference roughly remains constant, and is due to internal overhead (indexing alignment, handling NaNs, etc).
The graph was generated using perfplot. Benchmarking code, for reference:
import pandas as pd
import perfplot
np.random.seed(0)
df_ = pd.DataFrame(np.random.randn(5, 1000))
perfplot.show(
setup=lambda n: pd.concat([df_] * n, ignore_index=True),
kernels=[
lambda df: df.assign(new=df.max(axis=1)),
lambda df: df.assign(new=df.values.max(1)),
lambda df: df.assign(new=np.nanmax(df.values, axis=1)),
lambda df: df.assign(new=np.maximum.reduce(df.values, axis=1)),
],
labels=['df.max', 'np.max', 'np.maximum.reduce', 'np.nanmax'],
n_range=[2**k for k in range(0, 15)],
xlabel='N (* len(df))',
logx=True,
logy=True)
#ifdef 0
...
#endif
#ifdef expect a macro rather than expression when using constant or expression
#if 0
...
#endif
or
#if !defined(PP_CHECK) || defined(PP_CHECK_OTHER)
..
#endif
if #ifdef is used the it reports this error
#ifdef !defined(PP_CHECK) || defined(PP_CHECK_OTHER)
..
#endif
Where #ifdef expect a macro rather than macro expresssion
For better understanding why wait() and notify() method belongs to Object class, I'll give you a real life example: Suppose a gas station has a single toilet, the key for which is kept at the service desk. The toilet is a shared resource for passing motorists. To use this shared resource the prospective user must acquire a key to the lock on the toilet. The user goes to the service desk and acquires the key, opens the door, locks it from the inside and uses the facilities.
Meanwhile, if a second prospective user arrives at the gas station he finds the toilet locked and therefore unavailable to him. He goes to the service desk but the key is not there because it is in the hands of the current user. When the current user finishes, he unlocks the door and returns the key to the service desk. He does not bother about waiting customers. The service desk gives the key to the waiting customer. If more than one prospective user turns up while the toilet is locked, they must form a queue waiting for the key to the lock. Each thread has no idea who is in the toilet.
Obviously in applying this analogy to Java, a Java thread is a user and the toilet is a block of code which the thread wishes to execute. Java provides a way to lock the code for a thread which is currently executing it using the synchronized keyword, and making other threads that wish to use it wait until the first thread is finished. These other threads are placed in the waiting state. Java is NOT AS FAIR as the service station because there is no queue for waiting threads. Any one of the waiting threads may get the monitor next, regardless of the order they asked for it. The only guarantee is that all threads will get to use the monitored code sooner or later.
Finally the answer to your question: the lock could be the key object or the service desk. None of which is a Thread.
However, these are the objects that currently decide whether the toilet is locked or open. These are the objects that are in a position to notify that the bathroom is open (“notify”) or ask people to wait when it is locked wait.
You can also achieve this effect using XML, as seen here, which removes the limitation of the answers provided which all seem to include recursion in some fashion. The particular use I've made here allows for up to a 32-character delimiter, but that could be increased however large it needs to be.
create FUNCTION [dbo].[Split] (@sep VARCHAR(32), @s VARCHAR(MAX))
RETURNS TABLE
AS
RETURN
(
SELECT r.value('.','VARCHAR(MAX)') as Item
FROM (SELECT CONVERT(XML, N'<root><r>' + REPLACE(REPLACE(REPLACE(@s,'& ','& '),'<','<'), @sep, '</r><r>') + '</r></root>') as valxml) x
CROSS APPLY x.valxml.nodes('//root/r') AS RECORDS(r)
)
Then you can invoke it using:
SELECT * FROM dbo.Split(' ', 'I hate bunnies')
Which returns:
-----------
|I |
|---------|
|hate |
|---------|
|bunnies |
-----------
CREATE FUNCTION [dbo].[Split] (@sep VARCHAR(32), @s VARCHAR(MAX))
RETURNS TABLE
AS
RETURN
(
SELECT r.value('.','VARCHAR(MAX)') as Item
FROM (SELECT CONVERT(XML, N'<root><r>' + REPLACE(@s, @sep, '</r><r>') + '</r></root>') as valxml) x
CROSS APPLY x.valxml.nodes('//root/r') AS RECORDS(r)
)
You can have the iterator be a call to a function that is performed on each iteration through the loop.
See here: http://www.cplusplus.com/reference/algorithm/for_each/
Could someone explain to me, how to call the move method with the variable RIGHT
>>> myMissile = MissileDevice(myBattery) # looks like you need a battery, don't know what that is, you figure it out.
>>> myMissile.move(MissileDevice.RIGHT)
If you have programmed in any other language with classes, besides python, this sort of thing
class Foo:
bar = "baz"
is probably unfamiliar. In python, the class is a factory for objects, but it is itself an object; and variables defined in its scope are attached to the class, not the instances returned by the class. to refer to bar
, above, you can just call it Foo.bar
; you can also access class attributes through instances of the class, like Foo().bar
.
Im utterly baffled about what 'self' refers too,
>>> class Foo:
... def quux(self):
... print self
... print self.bar
... bar = 'baz'
...
>>> Foo.quux
<unbound method Foo.quux>
>>> Foo.bar
'baz'
>>> f = Foo()
>>> f.bar
'baz'
>>> f
<__main__.Foo instance at 0x0286A058>
>>> f.quux
<bound method Foo.quux of <__main__.Foo instance at 0x0286A058>>
>>> f.quux()
<__main__.Foo instance at 0x0286A058>
baz
>>>
When you acecss an attribute on a python object, the interpreter will notice, when the looked up attribute was on the class, and is a function, that it should return a "bound" method instead of the function itself. All this does is arrange for the instance to be passed as the first argument.
I come across this problem when I tried to convert to Australian date format in excel. I split the cell with delimiter and used the following code from split cells then altered the issue areas.
=date(dd,mm,yy)
2021 Update
Bootstrap 5 also has a flexbox Navbar, and introduces new RTL support. For this reason the concept of "left" and "right" has been replaced with "start" and "end". Therefore the margin utilities changed for Bootstrap 5 beta:
ml-auto
=> ms-auto
mr-auto
=> me-auto
Now that Bootstrap 4 has flexbox, Navbar alignment is much easier. Here are updated examples for left, right and center in the Bootstrap 4 Navbar, and many other alignment scenarios demonstrated here.
The flexbox, auto-margins, and ordering utility classes can be used to align Navbar content as needed. There are many things to consider including the order and alignment of Navbar items (brand, links, toggler) on both large screens and the mobile/collapsed views. Don't use the grid classes (row,col) for the Navbar.
Here are various examples...
Left, center(brand) and right links:
<nav class="navbar navbar-expand-md navbar-dark bg-dark">
<div class="navbar-collapse collapse w-100 order-1 order-md-0 dual-collapse2">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Left</a>
</li>
<li class="nav-item">
<a class="nav-link" href="//codeply.com">Codeply</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
<div class="mx-auto order-0">
<a class="navbar-brand mx-auto" href="#">Navbar 2</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".dual-collapse2">
<span class="navbar-toggler-icon"></span>
</button>
</div>
<div class="navbar-collapse collapse w-100 order-3 dual-collapse2">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#">Right</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
</nav>
http://codeply.com/go/qhaBrcWp3v
Another BS4 Navbar option with center links and overlay logo image:
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="navbar-collapse collapse w-100 dual-collapse2 order-1 order-md-0">
<ul class="navbar-nav ml-auto text-center">
<li class="nav-item active">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
<div class="mx-auto my-2 order-0 order-md-1 position-relative">
<a class="mx-auto" href="#">
<img src="//placehold.it/120/ccff00" class="rounded-circle">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".dual-collapse2">
<span class="navbar-toggler-icon"></span>
</button>
</div>
<div class="navbar-collapse collapse w-100 dual-collapse2 order-2 order-md-2">
<ul class="navbar-nav mr-auto text-center">
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
</nav>
Or, these other Bootstrap 4 alignment scenarios:
brand left, dead center links, (empty right)
brand and links center, icons left and right
More Bootstrap 4 examples:
toggler left on mobile, brand right
center brand and links on mobile
right align links on desktop, center links on mobile
left links & toggler, center brand, search right
Also see: Bootstrap 4 align navbar items to the right
Bootstrap 4 navbar right align with button that doesn't collapse on mobile
Center an element in Bootstrap 4 Navbar
Option 1 - Brand center, with left/right nav links:
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<a class="navbar-brand" href="#">Brand</a>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-left">
<li><a href="#">Left</a></li>
<li><a href="#about">Left</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#about">Right</a></li>
<li><a href="#contact">Right</a></li>
</ul>
</div>
</nav>
.navbar-brand
{
position: absolute;
width: 100%;
left: 0;
text-align: center;
margin:0 auto;
}
.navbar-toggle {
z-index:3;
}
http://bootply.com/98314 (3.x)
Option 2 - Left, center and right nav links:
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="#">Left</a></li>
</ul>
<ul class="nav navbar-nav navbar-center">
<li><a href="#">Center</a></li>
<li><a href="#">Center</a></li>
<li><a href="#">Center</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Right</a></li>
</ul>
</div>
</nav>
@media (min-width: 768px) {
.navbar-nav.navbar-center {
position: absolute;
left: 50%;
transform: translatex(-50%);
}
}
Option 3 - Center both brand and links
.navbar .navbar-header,
.navbar-collapse {
float:none;
display:inline-block;
vertical-align: top;
}
@media (max-width: 768px) {
.navbar-collapse {
display: block;
}
}
http://codeply.com/go/1lrdvNH9GI
More examples:
Left brand, center links
Left toggler, center brand
For 3.x also see nav-justified: Bootstrap center navbar
Center Navbar in Bootstrap
Bootstrap 4 align navbar items to the right
replace ListView by RecycleView inside ScrollView. it runs smoothly without additional source code:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.hung.recycleviewtest.MainActivityFragment"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycle_view"
android:layout_width="match_parent"
android:layout_height="400dp"
android:background="@android:color/darker_gray"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycle_view_a"
android:layout_marginTop="40dp"
android:layout_below="@id/recycle_view"
android:layout_width="match_parent"
android:layout_height="400dp"
android:background="@android:color/darker_gray"/>
</RelativeLayout>
</ScrollView>
You can get the DOM element, and set the disabled property directly.
$(".shownextrow").click(function() {
$(this).closest("tr").next().show()
.find('.longboxsmall').hide()[0].disabled = 'disabled';
});
or if there's more than one, you can use each()
to set all of them:
$(".shownextrow").click(function() {
$(this).closest("tr").next().show()
.find('.longboxsmall').each(function() {
this.style.display = 'none';
this.disabled = 'disabled';
});
});
The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.
IF you are checking one variable against multiple condition then you would use something like this Here the block of code where the condition is true will be executed and other blocks will be ignored.
IF(@Var1 Condition1)
BEGIN
/*Your Code Goes here*/
END
ELSE IF(@Var1 Condition2)
BEGIN
/*Your Code Goes here*/
END
ELSE --<--- Default Task if none of the above is true
BEGIN
/*Your Code Goes here*/
END
If you are checking conditions against multiple variables then you would have to go for multiple IF Statements, Each block of code will be executed independently from other blocks.
IF(@Var1 Condition1)
BEGIN
/*Your Code Goes here*/
END
IF(@Var2 Condition1)
BEGIN
/*Your Code Goes here*/
END
IF(@Var3 Condition1)
BEGIN
/*Your Code Goes here*/
END
After every IF statement if there are more than one statement being executed you MUST put them in BEGIN..END Block. Anyway it is always best practice to use BEGIN..END blocks
Update
Found something in your code some BEGIN END you are missing
ELSE IF(@ID IS NOT NULL AND @ID in (SELECT ID FROM Places)) -- Outer Most Block ELSE IF
BEGIN
SELECT @MyName = Name ...
...Some stuff....
IF(SOMETHNG_1) -- IF
--BEGIN
BEGIN TRY
UPDATE ....
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE() AS 'Message'
RETURN -1
END CATCH
-- END
ELSE IF(SOMETHNG_2) -- ELSE IF
-- BEGIN
BEGIN TRY
UPDATE ...
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE() AS 'Message'
RETURN -1
END CATCH
-- END
ELSE -- ELSE
BEGIN
BEGIN TRY
UPDATE ...
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE() AS 'Message'
RETURN -1
END CATCH
END
--The above works I then insert this below and these if statement become nested----
IF(@A!= @SA)
BEGIN
exec Store procedure
@FIELD = 15,
... more params...
END
IF(@S!= @SS)
BEGIN
exec Store procedure
@FIELD = 10,
... more params...
N.B.: As per the UILabel class reference, as of iOS 6 this approach is now deprecated.
Simply use the textAlignment
property to see the required alignment using one of the UITextAlignment
values. (UITextAlignmentLeft
, UITextAlignmentCenter
or UITextAlignmentRight
.)
e.g.: [myUILabel setTextAlignment:UITextAlignmentCenter];
See the UILabel Class Reference for more information.
There's a difference between an empty string ""
and an undefined variable. You should be checking whether or not theHref contains a defined string, rather than its lenght:
if(theHref){
// ---
}
If you still want to check for the length, then do this:
if(theHref && theHref.length){
// ...
}
A convenient solution in your case would be to include the configs in a yaml file named
**your_config_name.yml**
which would look like this:
path1: "D:\test1\first"
path2: "D:\test2\second"
path3: "D:\test2\third"
In your python code you can then load the config params into a dictionary by doing this:
import yaml
with open('your_config_name.yml') as stream:
config = yaml.safe_load(stream)
You then access e.g. path1 like this from your dictionary config:
config['path1']
To import yaml you first have to install the package as such: pip install pyyaml
into your chosen virtual environment.
My Image name was 21.jpg. I renamed it as abc.jpg and it worked. So Make sure your image name not starting with a number. However all above answers are also accepted.
Below code is using com.google.gson.JsonArray
.
I have printed the number of element in list as well as the elements in List
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
static String str = "{ "+
"\"client\":\"127.0.0.1\"," +
"\"servers\":[" +
" \"8.8.8.8\"," +
" \"8.8.4.4\"," +
" \"156.154.70.1\"," +
" \"156.154.71.1\" " +
" ]" +
"}";
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(str);
JsonArray jsonArr = jo.getAsJsonArray("servers");
//jsonArr.
Gson googleJson = new Gson();
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
System.out.println("List size is : "+jsonObjList.size());
System.out.println("List Elements are : "+jsonObjList.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OUTPUT
List size is : 4
List Elements are : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]
Like that we can do....
int main(int argc, char *argv[]) {
int a, b, c;
*// Converting string type to integer type
// using function "atoi( argument)"*
a = atoi(argv[1]);
b = atoi(argv[2]);
c = atoi(argv[3]);
}
The solution is the binding of variables through closure.
As a more basic example, here is an example function that receives and calls a callback function, as well as an example callback function:
function callbackReceiver(callback) {
callback("Hello World");
}
function callback(value1, value2) {
console.log(value1, value2);
}
This calls the callback and supplies a single argument. Now you want to supply an additional argument, so you wrap the callback in closure.
callbackReceiver(callback); // "Hello World", undefined
callbackReceiver(function(value) {
callback(value, "Foo Bar"); // "Hello World", "Foo Bar"
});
Or, more simply using ES6 Arrow Functions:
callbackReceiver(value => callback(value, "Foo Bar")); // "Hello World", "Foo Bar"
As for your specific example, I haven't used the .post
function in jQuery, but a quick scan of the documentation suggests the call back should be a function pointer with the following signature:
function callBack(data, textStatus, jqXHR) {};
Therefore I think the solution is as follows:
var doSomething = function(extraStuff) {
return function(data, textStatus, jqXHR) {
// do something with extraStuff
};
};
var clicked = function() {
var extraStuff = {
myParam1: 'foo',
myParam2: 'bar'
}; // an object / whatever extra params you wish to pass.
$.post("someurl.php", someData, doSomething(extraStuff), "json");
};
What is happening?
In the last line, doSomething(extraStuff)
is invoked and the result of that invocation is a function pointer.
Because extraStuff
is passed as an argument to doSomething
it is within scope of the doSomething
function.
When extraStuff
is referenced in the returned anonymous inner function of doSomething
it is bound by closure to the outer function's extraStuff
argument. This is true even after doSomething
has returned.
I haven't tested the above, but I've written very similar code in the last 24 hours and it works as I've described.
You can of course pass multiple variables instead of a single 'extraStuff' object depending on your personal preference/coding standards.
You can create a custom layout and apply it to the actionBar.
To do so, follow those 2 simple steps:
Java Code
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.actionbar);
Where R.layout.actionbar
is the following layout.
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/action_bar_title"
android:text="YOUR ACTIVITY TITLE"
android:textColor="#ffffff"
android:textSize="24sp" />
</LinearLayout>
It can be as complex as you want. Try it out!
EDIT:
To set the background
you can use the property android:background
in the container layout (LinearLayout in that case). You may need to set the layout height android:layout_height
to match_parent
instead of wrap_content
.
Moreover, you can also add a LOGO / ICON to it. To do so, simply add an ImageView inside your layout, and set layout orientation property android:orientation
to horizontal (or simply use a RelativeLayout and manage it by yourself).
To change the title of above custom action bar dynamically, do this:
TextView title=(TextView)findViewById(getResources().getIdentifier("action_bar_title", "id", getPackageName()));
title.setText("Your Text Here");
If you want to display the name of the employee who is getting the second highest salary then use this:
SELECT employee_name
FROM employee
WHERE salary = (SELECT max(salary)
FROM employee
WHERE salary < (SELECT max(salary)
FROM employee);
One simple way can be the use of assign()
function that is pre-defined in vector
class.
e.g.
array[5]={1,2,3,4,5};
vector<int> v;
v.assign(array, array+5); // 5 is size of array.
UPDATED: Using prop instead of attr
<input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE"/>
$('#vehicleChkBox').change(function(){
cb = $(this);
cb.val(cb.prop('checked'));
});
OUT OF DATE:
Here is the jsfiddle
<input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE" />
$('#vehicleChkBox').change(function(){
if($(this).attr('checked')){
$(this).val('TRUE');
}else{
$(this).val('FALSE');
}
});
you can change your port in app.js or in ur project configuration file.
default('port', 80)
and to see if port 80 is already in use you can do
netstat -antp |grep 80
netstat -antp |grep node
you might wanna see if node process is already running or not.
ps -ef |grep node
and if you find its already running, you can kill it using
killall node
Here is a slightly different style recursion solution:
public static int countOccurrences(String haystack, char needle)
{
return countOccurrences(haystack, needle, 0);
}
private static int countOccurrences(String haystack, char needle, int accumulator)
{
if (haystack.length() == 0) return accumulator;
return countOccurrences(haystack.substring(1), needle, haystack.charAt(0) == needle ? accumulator + 1 : accumulator);
}
A very simple but unsafe implementation to read line for static allocation:
char line[1024];
scanf("%[^\n]", line);
A safer implementation, without the possibility of buffer overflow, but with the possibility of not reading the whole line, is:
char line[1024];
scanf("%1023[^\n]", line);
Not the 'difference by one' between the length specified declaring the variable and the length specified in the format string. It is a historical artefact.
Ok, here's what I've got in my app. It includes a hack to prevent ListView
s from going black while scrolling.
drawable/app_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/actual_pattern_image"
android:tileMode="repeat" />
values/styles.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="app_theme" parent="android:Theme">
<item name="android:windowBackground">@drawable/app_background</item>
<item name="android:listViewStyle">@style/TransparentListView</item>
<item name="android:expandableListViewStyle">@style/TransparentExpandableListView</item>
</style>
<style name="TransparentListView" parent="@android:style/Widget.ListView">
<item name="android:cacheColorHint">@android:color/transparent</item>
</style>
<style name="TransparentExpandableListView" parent="@android:style/Widget.ExpandableListView">
<item name="android:cacheColorHint">@android:color/transparent</item>
</style>
</resources>
AndroidManifest.xml:
//
<application android:theme="@style/app_theme">
//
They don't have the same structure... I can guarantee they are different
I know you've already created it... There is already an object named ‘tbltable1’ in the database
What you may want is this (which also fixes your other issue):
Drop table tblTable1
select * into tblTable1 from tblTable1_Link
You can try to use TCPView utility.
Try to find in the localport column is there any process worked on "busy" port. Right click and end the process. Then try to start the Tomcat.
Its really works for me.
Here is a working example in both Javascript and jQuery:
http://jsfiddle.net/GuLYN/312/
//In jQuery
$("#calculate").click(function() {
var num = parseFloat($("#textbox").val());
var new_num = $("#textbox").val(num.toFixed(2));
});
// In javascript
document.getElementById('calculate').onclick = function() {
var num = parseFloat(document.getElementById('textbox').value);
var new_num = num.toFixed(2);
document.getElementById('textbox').value = new_num;
};
?
Here is the detailed explanation of why "Random.nextInt(n)
is both more efficient and less biased than Math.random() * n
" from the Sun forums post that Gili linked to:
Math.random() uses Random.nextDouble() internally.
Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its mantissa, so it is uniformly distributed in the range 0 to 1-(2^-53).
Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.
Prior to scaling by 6, the output of Math.random() is one of 2^53 possible values drawn from a uniform distribution.
Scaling by 6 doesn't alter the number of possible values, and casting to an int then forces these values into one of six 'buckets' (0, 1, 2, 3, 4, 5), each bucket corresponding to ranges encompassing either 1501199875790165 or 1501199875790166 of the possible values (as 6 is not a disvisor of 2^53). This means that for a sufficient number of dice rolls (or a die with a sufficiently large number of sides), the die will show itself to be biased towards the larger buckets.
You will be waiting a very long time rolling dice for this effect to show up.
Math.random() also requires about twice the processing and is subject to synchronization.
Though this question already has sufficient answers, I thought somebody would want to know why this flag works in this peculiar manner, This is what I found in Android documentation
The currently running instance of activity B in the above example will either receive the new intent you are starting here in its onNewIntent() method, or be itself finished and restarted with the new intent.
If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent().
So, Either,
1. Change the launchMode
of the Activity A to something else from standard (ie. singleTask
or something). Then your flag FLAG_ACTIVITY_CLEAR_TOP
will not restart your Activity A.
or,
2. Use Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP
as your flag. Then it will work the way you desire.
Since you may have more than one legends in a plot, a way to selectively remove just one of the titles without leaving an empty space is to set the name
argument of the scale_
function to NULL
, i.e.
scale_fill_discrete(name = NULL)
(kudos to @pascal for a comment on another thread)
Answer is to add a having clause:
SELECT [columns]
FROM table t1
WHERE value= (select max(value) from table)
AND date = (select MIN(date) from table t2 where t1.value = t2.value)
this should work and gets rid of the neccesity of having an extra sub select in the date clause.
Building on other's answers and personal experience:
Predicate<String> blank = String::isEmpty;
content.stream()
.filter(blank.negate())
This problem can occur not only due to permissions, but also due to event source key missing because it wasn't registered successfully (you need admin privileges to do it - if you just open Visual Studio as usual and run the program normally it won't be enough). Make sure that your event source "MyApp" is actually registered, i.e. that it appears in the registry under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application
.
From MSDN EventLog.CreateEventSource():
To create an event source in Windows Vista and later or Windows Server 2003, you must have administrative privileges.
So you must either run the event source registration code as an admin (also, check if the source already exists before - see the above MSDN example) or you can manually add the key to the registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\MyApp
;EventMessageFile
and set its value to e.g. C:\Windows\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll
Had the same problem in Linux. This solved it. (I'm on Debian 9 derived Bunsen Helium)
$ sudo apt-get install python3-tk
I will use CXF also you can think of AXIS 2 .
The best way to do it may be using JAX RS Refer this example
Example:
wsimport -p stockquote http://stockquote.xyz/quote?wsdl
This will generate the Java artifacts and compile them by importing the http://stockquote.xyz/quote?wsdl.
I
If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using broadcasting.
Starting with your example array:
import numpy as np
x = np.array([[1000, 10, 0.5],
[ 765, 5, 0.35],
[ 800, 7, 0.09]])
x_normed = x / x.max(axis=0)
print(x_normed)
# [[ 1. 1. 1. ]
# [ 0.765 0.5 0.7 ]
# [ 0.8 0.7 0.18 ]]
x.max(0)
takes the maximum over the 0th dimension (i.e. rows). This gives you a vector of size (ncols,)
containing the maximum value in each column. You can then divide x
by this vector in order to normalize your values such that the maximum value in each column will be scaled to 1.
If x
contains negative values you would need to subtract the minimum first:
x_normed = (x - x.min(0)) / x.ptp(0)
Here, x.ptp(0)
returns the "peak-to-peak" (i.e. the range, max - min) along axis 0. This normalization also guarantees that the minimum value in each column will be 0.
I bet (no language specified) size()
method returns length
property.
However valid for
loop should looks like:
for (int i = 0; i < values.length; i++) {}
$arr = array('key1'=>'value1','key2'=>'value2','key3'=>'value3');
list($last_key) = each(array_reverse($arr));
print $last_key;
// key3
Create a class and give it an __init__
method:
class Student:
def __init__(self, name, age, major):
self.name = name
self.age = age
self.major = major
def is_old(self):
return self.age > 100
Now, you can initialize an instance of the Student
class:
>>> s = Student('John', 88, None)
>>> s.name
'John'
>>> s.age
88
Although I'm not sure why you need a make_student
student function if it does the same thing as Student.__init__
.
Thank you, user374559 and reneD -- that code and description is very helpful.
My stab at some Python to parse and print out the information in a Unix ls-l like format:
#!/usr/bin/env python
import sys
def getint(data, offset, intsize):
"""Retrieve an integer (big-endian) and new offset from the current offset"""
value = 0
while intsize > 0:
value = (value<<8) + ord(data[offset])
offset = offset + 1
intsize = intsize - 1
return value, offset
def getstring(data, offset):
"""Retrieve a string and new offset from the current offset into the data"""
if data[offset] == chr(0xFF) and data[offset+1] == chr(0xFF):
return '', offset+2 # Blank string
length, offset = getint(data, offset, 2) # 2-byte length
value = data[offset:offset+length]
return value, (offset + length)
def process_mbdb_file(filename):
mbdb = {} # Map offset of info in this file => file info
data = open(filename).read()
if data[0:4] != "mbdb": raise Exception("This does not look like an MBDB file")
offset = 4
offset = offset + 2 # value x05 x00, not sure what this is
while offset < len(data):
fileinfo = {}
fileinfo['start_offset'] = offset
fileinfo['domain'], offset = getstring(data, offset)
fileinfo['filename'], offset = getstring(data, offset)
fileinfo['linktarget'], offset = getstring(data, offset)
fileinfo['datahash'], offset = getstring(data, offset)
fileinfo['unknown1'], offset = getstring(data, offset)
fileinfo['mode'], offset = getint(data, offset, 2)
fileinfo['unknown2'], offset = getint(data, offset, 4)
fileinfo['unknown3'], offset = getint(data, offset, 4)
fileinfo['userid'], offset = getint(data, offset, 4)
fileinfo['groupid'], offset = getint(data, offset, 4)
fileinfo['mtime'], offset = getint(data, offset, 4)
fileinfo['atime'], offset = getint(data, offset, 4)
fileinfo['ctime'], offset = getint(data, offset, 4)
fileinfo['filelen'], offset = getint(data, offset, 8)
fileinfo['flag'], offset = getint(data, offset, 1)
fileinfo['numprops'], offset = getint(data, offset, 1)
fileinfo['properties'] = {}
for ii in range(fileinfo['numprops']):
propname, offset = getstring(data, offset)
propval, offset = getstring(data, offset)
fileinfo['properties'][propname] = propval
mbdb[fileinfo['start_offset']] = fileinfo
return mbdb
def process_mbdx_file(filename):
mbdx = {} # Map offset of info in the MBDB file => fileID string
data = open(filename).read()
if data[0:4] != "mbdx": raise Exception("This does not look like an MBDX file")
offset = 4
offset = offset + 2 # value 0x02 0x00, not sure what this is
filecount, offset = getint(data, offset, 4) # 4-byte count of records
while offset < len(data):
# 26 byte record, made up of ...
fileID = data[offset:offset+20] # 20 bytes of fileID
fileID_string = ''.join(['%02x' % ord(b) for b in fileID])
offset = offset + 20
mbdb_offset, offset = getint(data, offset, 4) # 4-byte offset field
mbdb_offset = mbdb_offset + 6 # Add 6 to get past prolog
mode, offset = getint(data, offset, 2) # 2-byte mode field
mbdx[mbdb_offset] = fileID_string
return mbdx
def modestr(val):
def mode(val):
if (val & 0x4): r = 'r'
else: r = '-'
if (val & 0x2): w = 'w'
else: w = '-'
if (val & 0x1): x = 'x'
else: x = '-'
return r+w+x
return mode(val>>6) + mode((val>>3)) + mode(val)
def fileinfo_str(f, verbose=False):
if not verbose: return "(%s)%s::%s" % (f['fileID'], f['domain'], f['filename'])
if (f['mode'] & 0xE000) == 0xA000: type = 'l' # symlink
elif (f['mode'] & 0xE000) == 0x8000: type = '-' # file
elif (f['mode'] & 0xE000) == 0x4000: type = 'd' # dir
else:
print >> sys.stderr, "Unknown file type %04x for %s" % (f['mode'], fileinfo_str(f, False))
type = '?' # unknown
info = ("%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" %
(type, modestr(f['mode']&0x0FFF) , f['userid'], f['groupid'], f['filelen'],
f['mtime'], f['atime'], f['ctime'], f['fileID'], f['domain'], f['filename']))
if type == 'l': info = info + ' -> ' + f['linktarget'] # symlink destination
for name, value in f['properties'].items(): # extra properties
info = info + ' ' + name + '=' + repr(value)
return info
verbose = True
if __name__ == '__main__':
mbdb = process_mbdb_file("Manifest.mbdb")
mbdx = process_mbdx_file("Manifest.mbdx")
for offset, fileinfo in mbdb.items():
if offset in mbdx:
fileinfo['fileID'] = mbdx[offset]
else:
fileinfo['fileID'] = "<nofileID>"
print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
print fileinfo_str(fileinfo, verbose)
I know everybody is ethically against this, but I understand there are reasons of practical joking where this is desired. I think Chrome took a solid stance on this by enforcing a mandatory one second separation time between alert messages. This gives the visitor just enough time to close the page or refresh if they're stuck on an annoying prank site.
So to answer your question, it's all a matter of timing. If you alert more than once per second, Chrome will create that checkbox. Here's a simple example of a workaround:
var countdown = 99;
function annoy(){
if(countdown>0){
alert(countdown+" bottles of beer on the wall, "+countdown+" bottles of beer! Take one down, pass it around, "+(countdown-1)+" bottles of beer on the wall!");
countdown--;
// Time must always be 1000 milliseconds, 999 or less causes the checkbox to appear
setTimeout(function(){
annoy();
}, 1000);
}
}
// Don't alert right away or Chrome will catch you
setTimeout(function(){
annoy();
}, 1000);
I feel your pain. I've tried every answer above, including the setIncludeFontPadding
to false, which did nothing for me.
My solution? layout_marginBottom="-3dp"
on the TextView
gives you a solution for the bottom,
BAM!
Although, -3dp on layout_marginTop
fails....ugh.
Selenium has so many options to perform drag and drop.
In Action class we have couple of method which will perform the same task.
I have listed the possible solution please have a look.
http://learn-automation.com/drag-and-drop-in-selenium-webdriver-using-actions-class/
With Postgres, you may use
select * from users where active
or
select * from users where active = 't'
If you want to use integer value, you have to consider it as a string. You can't use integer value.
select * from users where active = 1 -- Does not work
select * from users where active = '1' -- Works
found one interesting cheat sheet here.. http://introcs.cs.princeton.edu/java/11cheatsheet/
If this is what you want ...simply add button inside the Fragment.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.LocationChooser">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|top"
android:text="Demo Button"
android:padding="10dp"
android:layout_marginTop="20dp"
android:paddingRight="10dp"/>
</fragment>
Gson is also good for it: http://code.google.com/p/google-gson/
" Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. "
Check the API examples: https://sites.google.com/site/gson/gson-user-guide#TOC-Overview More examples: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
Just add remove_button_css as class to your button tag. You can verify the code for Link 1
.remove_button_css {
outline: none;
padding: 5px;
border: 0px;
box-sizing: none;
background-color: transparent;
}
Extra Styles Edit
Add color: #337ab7;
and :hover
and :focus
to match OOTB (bootstrap3)
.remove_button_css:focus,
.remove_button_css:hover {
color: #23527c;
text-decoration: underline;
}
You tried to start Tomcat and got the following error:
Could not load the Tomcat server configuration at /Servers/Tomcat v7.0 Server at localhost-config. The configuration may be corrupt or incomplete
How to solve:
I have used both R and MATLAB to solve problems and construct models related to Environmental Engineering and there is a lot of overlap between the two systems. In my opinion, the advantages of MATLAB lie in specialized domain-specific applications. Some examples are:
Functions such as streamline that aid in fluid dynamics investigations.
Toolboxes such as the image processing toolset. I have not found a R package that provides an equivalent implementation of tools like the watershed algorithm.
In my opinion MATLAB provides far better interactive graphics capabilities. However, I think R produces better static print-quality graphics, depending on the application. MATLAB's symbolic math toolbox is also better integrated and more capable than R equivalents such as Ryacas or rSymPy. The existence of the MATLAB compiler also allows systems based on MATLAB code to be deployed independently of the MATLAB environment-- although it's availability will depend on how much money you have to throw around.
Another thing I should note is that the MATLAB debugger is one of the best I have worked with.
The principle advantage I see with R is the openness of the system and the ease with which it can be extended. This has resulted in an incredible diversity of packages on CRAN. I know Mathworks also maintains a repository of user-contributed toolboxes and I can't make a fair comparison as I have not used it that much.
The openness of R also extends to linking in compiled code. A while back I had a model written in Fortran and I was trying to decide between using R or MATLAB as a front-end to help prepare input and process results. I spent an hour reading about the MEX interface to compiled code. When I found that I would have to write and maintain a separate Fortran routine that did some intricate pointer juggling in order to manage the interface, I shelved MATLAB.
The R interface consists of calling .Fortran( [subroutine name], [argument list]) and is simply quicker and cleaner.
In visual studio, use the "Add Web Reference" feature and then enter in the URL of your web service.
By adding a reference to the DLL, you not referencing it as a web service, but simply as an assembly.
When you add a web reference it create a proxy class in your project that has the same or similar methods/arguments as your web service. That proxy class communicates with your web service via SOAP but hides all of the communications protocol stuff so you don't have to worry about it.
./
is the the folder that the working file is in:
So in /index.htm
./
is the root directory
but in /css/style.css
./
is the css folder.
This is important to remember because if you move CSS from /index.htm
to /css/style.css
the path will change.
In order to call this you will have to store a reference to your form and pass the reference to the run method. Then you can call this in an actionhandler.
public partial class Form1 : Form
{
public void ChangeSize(int width, int height)
{
this.Size = new Size(width, height);
}
}
Please check this css for ellipsis to multi-line text
body {_x000D_
margin: 0;_x000D_
padding: 50px;_x000D_
}_x000D_
_x000D_
/* mixin for multiline */_x000D_
.block-with-text {_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
line-height: 1.2em;_x000D_
max-height: 6em;_x000D_
text-align: justify;_x000D_
margin-right: -1em;_x000D_
padding-right: 1em;_x000D_
}_x000D_
.block-with-text:before {_x000D_
content: '...';_x000D_
position: absolute;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
}_x000D_
.block-with-text:after {_x000D_
content: '';_x000D_
position: absolute;_x000D_
right: 0;_x000D_
width: 1em;_x000D_
height: 1em;_x000D_
margin-top: 0.2em;_x000D_
background: white;_x000D_
}
_x000D_
<p class="block-with-text">The Hitch Hiker's Guide to the Galaxy has a few things to say on the subject of towels. A towel, it says, is about the most massivelyuseful thing an interstellar hitch hiker can have. Partly it has great practical value - you can wrap it around you for warmth as you bound across the cold moons of Jaglan Beta; you can lie on it on the brilliant marble-sanded beaches of Santraginus V, inhaling the heady sea vapours; you can sleep under it beneath the stars which shine so redly on the desert world of Kakrafoon; use it to sail a mini raft down the slow heavy river Moth; wet it for use in hand-to-hand-combat; wrap it round your head to ward off noxious fumes or to avoid the gaze of the Ravenous Bugblatter Beast of Traal (a mindboggingly stupid animal, it assumes that if you can't see it, it can't see you - daft as a bush, but very ravenous); you can wave your towel in emergencies as a distress signal, and of course dry yourself off with it if it still seems to be clean enough. More importantly, a towel has immense psychological value. For some reason, if a strag (strag: non-hitch hiker) discovers that a hitch hiker has his towel with him, he will automatically assume that he is also in possession of a toothbrush, face flannel, soap, tin of biscuits, flask, compass, map, ball of string, gnat spray, wet weather gear, space suit etc., etc. Furthermore, the strag will then happily lend the hitch hiker any of these or a dozen other items that the hitch hiker might accidentally have "lost". What the strag will think is that any man who can hitch the length and breadth of the galaxy, rough it, slum it, struggle against terrible odds, win through, and still knows where his towel is is clearly a man to be reckoned with.</p>
_x000D_