You just need to use the Gradle Application plugin:
apply plugin:'application'
mainClassName = "org.gradle.sample.Main"
And then simply gradle run
.
As Teresa points out, you can also configure mainClassName
as a system property and run with a command line argument.
So, something like the $_POST
array?
You can use http_build_query($_POST)
to get them in a var=xxx&var2=yyy
string again. Or just print_r($_POST)
to see what's there.
also.. try to "clean" your projects or solution and rebuild again!
I tried closing a modal window with a bootstrap CSS loaded. The close () method does not really close the modal window. So I added the display style to "none".
function closeDialog() {
let d = document.getElementById('d')
d.style.display = "none"
d.close()
}
The HTML code includes a button into the dialog window.
<input type="submit" value="Confirm" onclick="closeDialog()"/>
I think this is the most reliable way to get the desktop path which isn't always the same as the username.
MsgBox CreateObject("WScript.Shell").specialfolders("Desktop")
use nth-child(item number) EX
<div class="parent_class">
<div class="myclass">my text1</div>
some other code+containers...
<div class="myclass">my text2</div>
some other code+containers...
<div class="myclass">my text3</div>
some other code+containers...
</div>
.parent_class:nth-child(1) { };
.parent_class:nth-child(2) { };
.parent_class:nth-child(3) { };
OR
:nth-of-type(item number) same your code
.myclass:nth-of-type(1) { };
.myclass:nth-of-type(2) { };
.myclass:nth-of-type(3) { };
Declaring ng-app
on the html
element provides root scope for both the head
and body
.
Therefore in your controller inject $rootScope
and set a header property on this:
function Test1Ctrl($rootScope, $scope, $http) { $rootScope.header = "Test 1"; }
function Test2Ctrl($rootScope, $scope, $http) { $rootScope.header = "Test 2"; }
and in your page:
<title ng-bind="header"></title>
Fake IE10 to install Visual Studio 2013
Visual Studio 2013 requires Internet Explorer 10. If you try to install it on Windows 7 with IE8 you get the following error This version of Visual Studio requires Internet Explorer 10”. The value that the VS 2013 installer checks is svcVersion in the
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer
key on 32-bit Windows andHKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer
on 64-bit Windows. Any value >= 10.0.0.0 makes the installer happy.
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer]
"svcVersion"="10.0.0.0"
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer]
"svcVersion"="10.0.0.0"
This worked for me:
It starts showing compilation errors in the code.
After doing many tests in Litmus, i could not find a way to have perfect rendering in all emails readers, but here is the better solution i found :
<table width="100%" cellpadding="0" cellspacing="0" style="background-color:#333;color:#fff;border-radius:3px;border-spacing:0;" >
<tr>
<td style="width:12px;" > </td>
<td valign="middle" style="padding-top:6px;padding-bottom:6px;padding-right:0;padding-left:0;" >
<span style="color:#fff;" ><strong>Your text here</strong> and here</span></a>
</td>
<td style="width:12px;" > </td>
</tr>
</table>
In this piece of code, i aimed to emulate padding : 6px 12px;
There are 2 "12px table columns" that handles the right and left padding.
And I'm using "padding: 6px 0;" on my td content, to manage top and bottom padding : Outlook 2010 and 2013 will ignore this and will use their own padding.
The text won't be perfectly aligned in Outlook 2010 and Outlook 2013 (slightly too far from top) but it works with all other email readers i tried : Apple Mail, Gmail, Outlook 2011 (yes..), Hotmail, Yahoo and many more.
I haven't studied yet, when Maven does which look-up, but to get stable and reproducible builds, I strongly recommend not to access Maven Respositories directly but to use a Maven Repository Manager such as Nexus.
Here is the tutorial how to set up your settings file:
http://books.sonatype.com/nexus-book/reference/maven-sect-single-group.html
Project Rebuild solved my problem.
In Android studio in the toolbar.. Build>Rebuild Project.
System.Windows.Forms.Application.DoEvents();
Keyboard.Focus(tbxLastName);
first Set id attribute of dropdownlist like i do here than use that id to get value in jquery or javascrip.
dropdownlist:
@Html.DropDownList("CompanyId", ViewBag.CompanyList as SelectList, "Select Company", new { @id="ddlCompany" })
jquery:
var id = jQuery("#ddlCompany option:selected").val();
This works cross-browser, provides more accessibility and comes with less markup. ditch the div. Wrap the label
label{
display: block;
height: 35px;
line-height: 35px;
border: 1px solid #000;
}
input{margin-top:15px; height:20px}
<label for="name">Name: <input type="text" id="name" /></label>
The configuration seem alright, except that you should use excludeFilters
instead of excludes
:
@Configuration @EnableSpringConfigured
@ComponentScan(basePackages = {"com.example"}, excludeFilters={
@ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class)})
public class MySpringConfiguration {}
getJSONArray(attrname) will get you an array from the object of that given attribute name in your case what is happening is that for
{"abridged_cast":["name": blah...]}
^ its trying to search for a value "characters"
but you need to get into the array and then do a search for "characters"
try this
String json="{'abridged_cast':[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},{'name':'JessicaLange','id':'162653068','characters':['Dwan']},{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";
JSONObject jsonResponse;
try {
ArrayList<String> temp = new ArrayList<String>();
jsonResponse = new JSONObject(json);
JSONArray movies = jsonResponse.getJSONArray("abridged_cast");
for(int i=0;i<movies.length();i++){
JSONObject movie = movies.getJSONObject(i);
JSONArray characters = movie.getJSONArray("characters");
for(int j=0;j<characters.length();j++){
temp.add(characters.getString(j));
}
}
Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
checked it :)
Windows Runtime equivalent of a function object in standard C++. One can use the whole function as a parameter (actually that is a function pointer). It is mostly used in conjunction with events. The delegate represents a contract that event handlers much fulfill. It facilitate how a function pointer can work for.
I had to do one more thing than what Sijin said to get it to add quotes properly in SQL Server Management Studio 2005. Go to
Tools->Options->Query Results->Sql Server->Results To Grid
Put a check next to this option:
Quote strings containing list separators when saving .csv results
Note: the above method will not work for SSMS 2005 Express! As far as I know there's no way to quote the fields when exporting results to .csv using SSMS 2005 Express.
To cast a double to an int and have it be rounded to the nearest integer (i.e. unlike the typical (int)(1.8)
and (int)(1.2)
, which will both "round down" towards 0 and return 1
), simply add 0.5 to the double
that you will typecast to an int
.
For example, if we have
double a = 1.2;
double b = 1.8;
Then the following typecasting expressions for x and y and will return the rounded-down values (x = 1
and y = 1
):
int x = (int)(a); // This equals (int)(1.2) --> 1
int y = (int)(b); // This equals (int)(1.8) --> 1
But by adding 0.5 to each, we will obtain the rounded-to-closest-integer result that we may desire in some cases (x = 1
and y = 2
):
int x = (int)(a + 0.5); // This equals (int)(1.8) --> 1
int y = (int)(b + 0.5); // This equals (int)(2.3) --> 2
As a small note, this method also allows you to control the threshold at which the double
is rounded up or down upon (int)
typecasting.
(int)(a + 0.8);
to typecast. This will only round up to (int)a + 1
whenever the decimal values are greater than or equal to 0.2. That is, by adding 0.8 to the double
immediately before typecasting, 10.15 and 10.03 will be rounded down to 10 upon (int)
typecasting, but 10.23 and 10.7 will be rounded up to 11.
There are at least two ways for achieving this in base graph (my examples are for the x-axis, but work the same for the y-axis):
Use par(xaxp = c(x1, x2, n))
or plot(..., xaxp = c(x1, x2, n))
to define the position (x1
& x2
) of the extreme tick marks and the number of intervals between the tick marks (n
). Accordingly, n+1
is the number of tick marks drawn. (This works only if you use no logarithmic scale, for the behavior with logarithmic scales see ?par
.)
You can suppress the drawing of the axis altogether and add the tick marks later with axis()
.
To suppress the drawing of the axis use plot(... , xaxt = "n")
.
Then call axis()
with side
, at
, and labels
: axis(side = 1, at = v1, labels = v2)
. With side
referring to the side of the axis (1 = x-axis, 2 = y-axis), v1
being a vector containing the position of the ticks (e.g., c(1, 3, 5)
if your axis ranges from 0 to 6 and you want three marks), and v2
a vector containing the labels for the specified tick marks (must be of same length as v1
, e.g., c("group a", "group b", "group c")
). See ?axis
and my updated answer to a post on stats.stackexchange for an example of this method.
Another option if you can't get it working for some reason is to simply mount a logdir directory on your filesystem with sshfs:
sshfs user@host:/home/user/project/summary_logs ~/summary_logs
and then run Tensorboard locally.
find /PATH/TO/YOUR/FILES -name NAME.EXT -exec cp -rfp {} /DST_DIR \;
i think you are not pausing the program before it ended so the output you are putting after getting the inpus is not seeing on the screen right?
do:
getchar();
before the end of the program
Calling addView
is the correct answer, but you need to do a little more than that to get it to work.
If you create a View via a constructor (e.g., Button myButton = new Button();
), you'll need to call setLayoutParams
on the newly constructed view, passing in an instance of the parent view's LayoutParams inner class, before you add your newly constructed child to the parent view.
For example, you might have the following code in your onCreate()
function assuming your LinearLayout has id R.id.main
:
LinearLayout myLayout = findViewById(R.id.main);
Button myButton = new Button(this);
myButton.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
myLayout.addView(myButton);
Making sure to set the LayoutParams is important. Every view needs at least a layout_width and a layout_height parameter. Also getting the right inner class is important. I struggled with getting Views added to a TableRow to display properly until I figured out that I wasn't passing an instance of TableRow.LayoutParams to the child view's setLayoutParams.
You should just use "+" before $(this)
. That's going to convert the string to number, so:
var votevalue = +$(this).data('votevalue');
Oh and I recommend to use closest()
method just in case :)
var votevalue = +$(this).closest('.btn-group').data('votevalue');
I'm pretty sure the classpath and the shared library search path have little to do with each other. According to The JNI Book (which admittedly is old), on Windows if you do not use the java.library.path
system property, the DLL needs to be in the current working directory or in a directory listed in the Windows PATH
environment variable.
Update:
Looks like Oracle has removed the PDF from its website. I've updated the link above to point to an instance of the PDF living at University of Texas - Arlington.
Also, you can also read Oracle's HTML version of the JNI Specification. That lives in the Java 8 section of the Java website and so hopefully will be around for a while.
Update 2:
At least in Java 8 (I haven't checked earlier versions) you can do:
java -XshowSettings:properties -version
to find the shared library search path. Look for the value of the java.library.path
property in that output.
The underscore usually means a C module (i.e. DLL), and Python can't find it. Did you build python yourself? If so, you need to include SSL support.
Instead of writing it in your code directly I suggest you make use of the dedicated <connectionStrings>
element in the .config file and retrieve it from there.
Also make use of the using
statement so that after usage your connection automatically gets closed and disposed of.
A great reference for finding connection strings: connectionstrings.com/sql-server-2008.
I know this is a kind of old post, but I found myself in this same issue, and by investigating a bit I found out that the Height of a WinForms TextBox is actually calculated depending on the size of the font it contains, it's just not quite equal to it.
This guy explains how the calculation is done, and how you can set it on your TextBox to get the desired Height.
Cheers!
You just do an opposite comparison. if Col2 <= 1
. This will return a boolean Series with False
values for those greater than 1 and True
values for the other. If you convert it to an int64
dtype, True
becomes 1
and False
become 0
,
df['Col3'] = (df['Col2'] <= 1).astype(int)
If you want a more general solution, where you can assign any number to Col3
depending on the value of Col2
you should do something like:
df['Col3'] = df['Col2'].map(lambda x: 42 if x > 1 else 55)
Or:
df['Col3'] = 0
condition = df['Col2'] > 1
df.loc[condition, 'Col3'] = 42
df.loc[~condition, 'Col3'] = 55
You can call tail +[line number] [file]
and pipe it to grep -n
which shows the line number:
tail +[line number] [file] | grep -n /regex/
The only problem with this method is the line numbers reported by grep -n
will be [line number] - 1
less than the actual line number in [file]
.
I just came across this problem and have written a solution for those of you who are using Angular. You can write a custom directive composed of a container, a button, and an input element with type file. With CSS you then place the input over the custom button but with opacity 0. You set the containers height and width to exactly the offset width and height of the button and the input's height and width to 100% of the container.
the directive
angular.module('myCoolApp')
.directive('fileButton', function () {
return {
templateUrl: 'components/directives/fileButton/fileButton.html',
restrict: 'E',
link: function (scope, element, attributes) {
var container = angular.element('.file-upload-container');
var button = angular.element('.file-upload-button');
container.css({
position: 'relative',
overflow: 'hidden',
width: button.offsetWidth,
height: button.offsetHeight
})
}
};
});
a jade template if you are using jade
div(class="file-upload-container")
button(class="file-upload-button") +
input#file-upload(class="file-upload-input", type='file', onchange="doSomethingWhenFileIsSelected()")
the same template in html if you are using html
<div class="file-upload-container">
<button class="file-upload-button"></button>
<input class="file-upload-input" id="file-upload" type="file" onchange="doSomethingWhenFileIsSelected()" />
</div>
the css
.file-upload-button {
margin-top: 40px;
padding: 30px;
border: 1px solid black;
height: 100px;
width: 100px;
background: transparent;
font-size: 66px;
padding-top: 0px;
border-radius: 5px;
border: 2px solid rgb(255, 228, 0);
color: rgb(255, 228, 0);
}
.file-upload-input {
position: absolute;
top: 0;
left: 0;
z-index: 2;
width: 100%;
height: 100%;
opacity: 0;
cursor: pointer;
}
If I'm going to be using values()
a lot:
enum Suit {
Hearts, Diamonds, Spades, Clubs;
public static final Suit values[] = values();
}
Meanwhile wherever.java:
Suit suit = Suit.values[ordinal];
If you want the array to be private, be my guest:
private static final Suit values[] = values();
public static Suit get(int ordinal) { return values[ordinal]; }
...
Suit suit = Suit.get(ordinal);
Mind your array bounds.
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
$({jQueryCode:(url)=>location.replace(url)}).attr("jQueryCode")("http://example.com")
Please don't kill me, this is a joke. It's a joke. This is a joke.
This did "provide an answer to the question", in the sense that it asked for a solution "using jQuery" which in this case entails forcing it into the equation somehow.
Ferrybig apparently needs the joke explained (still joking, I'm sure there are limited options on the review form), so without further ado:
Other answers are using jQuery's attr()
on the location
or window
objects unnecessarily.
This answer also abuses it, but in a more ridiculous way. Instead of using it to set the location, this uses attr()
to retrieve a function that sets the location.
The function is named jQueryCode
even though there's nothing jQuery about it, and calling a function somethingCode
is just horrible, especially when the something is not even a language.
The "85 bytes" is a reference to Code Golf. Golfing is obviously not something you should do outside of code golf, and furthermore this answer is clearly not actually golfed.
Basically, cringe.
count of the contained lists in the outmost list
int count = data.size();
lambda to get the count of the contained inner lists
int count = data.stream().collect( summingInt(l -> l.size()) );
in Frag1:
Bundle b = new Bundle();
b.putStringArray("arrayname that use to retrive in frag2",StringArrayObject);
Frag2.setArguments(b);
in Frag2:
Bundle b = getArguments();
String[] stringArray = b.getStringArray("arrayname that passed in frag1");
It's that simple.
implementation
means what language was used to implement Python and not how python Code would be implemented. The advantage of using CPython is the availability of C Run-time as well as easy integration with C/C++.
So CPython was originally implemented using C
. There were other forks to the original implementation which enabled Python to lever-edge Java (JYthon) or .NET Runtime (IronPython).
Based on which Implementation you use, library availability might vary, for example Ctypes is not available in Jython, so any library which uses ctypes would not work in Jython. Similarly, if you want to use a Java Class, you cannot directly do so from CPython. You either need a glue (JEPP) or need to use Jython (The Java Implementation of Python)
I use eventbug plugin to firebug for this purpose.
Check to see if you are typing all the parameters correctly. It throws the same error if the amount of parameters defined and then passed to the function are different.
|checked|unchecked|crossed|
|---|---|---|
|✓|_|✗|
Where
? via HTML Entity Code
? via HTML Entity Code
_ via underscore character
and table via markdown table syntax.
try this
for i in *.png ; do mv "$i" "${i/remove_me*.png/.png}" ; done
Here is another way:
for file in Name*.png; do mv "$file" "01_$file"; done
I faced the same problem when trying to add the seaborn module in Spyder. I installed seaborn into my anaconda directory in ubuntu 14.04. The seaborn module would load if I added the entire anaconda/lib/python2.7/site-packages/ directory which contained the 'seaborn' and seaborn-0.5.1-py2.7.egg-info folders. The problem was this anaconda site-packages folder also contained many other modules which Spyder did not like.
My solution: I created a new directory in my personal Home folder that I named 'spyderlibs' where I placed seaborn and seaborn-0.5.1-py2.7.egg-info folders. Adding my new spyderlib directory in Spyder's PYTHONPATH manager worked!
Presumably you have it in a variable and are using JSON.parse(data);
. In which case, use:
JSON.parse(data.replace(/"/g,'"'));
You might want to fix your JSON-writing script though, because "
is not valid in a JSON object.
Let's keep it simple. Loved @digitaldreamer 's answer but it might leave the beginners confused. So, I am going to try and simplify it.
The only HTML comment is <!-- -->
It can be used as a single line comment or double, it is really up to the developer.
So, an HTML comment starts with <!--
and ends with -->
. It is really that simple. You should not use any other format, to avoid any compatibility issue even if the comment format is legit or not.
The Apple Tech Note also described you can restore the device to reset the Push Notification dialog.
It does not say that you can also use the option "General -> Reset -> Erase All Content And Settings" on the device itself (iOS 5.x).
According to the official documentation on sitemaps.org it needs to be a full URL:
You can specify the location of the Sitemap using a robots.txt file. To do this, simply add the following line including the full URL to the sitemap:
Sitemap: http://www.example.com/sitemap.xml
You could also try exectimer. It gives you feedback like:
var t = require("exectimer");
var myFunction() {
var tick = new t.tick("myFunction");
tick.start();
// do some processing and end this tick
tick.stop();
}
// Display the results
console.log(t.timers.myFunction.duration()); // total duration of all ticks
console.log(t.timers.myFunction.min()); // minimal tick duration
console.log(t.timers.myFunction.max()); // maximal tick duration
console.log(t.timers.myFunction.mean()); // mean tick duration
console.log(t.timers.myFunction.median()); // median tick duration
[edit] There is an even simpler way now to use exectime. Your code could be wrapped like this:
var t = require('exectimer'),
Tick = t.Tick;
for(var i = 1; i < LIMIT; i++){
Tick.wrap(function saveUsers(done) {
db.users.save({id : i, name : "MongoUser [" + i + "]"}, function(err, saved) {
if( err || !saved ) console.log("Error");
else console.log("Saved");
done();
});
});
}
// Display the results
console.log(t.timers.myFunction.duration()); // total duration of all ticks
console.log(t.timers.saveUsers.min()); // minimal tick duration
console.log(t.timers.saveUsers.max()); // maximal tick duration
console.log(t.timers.saveUsers.mean()); // mean tick duration
console.log(t.timers.saveUsers.median()); // median tick duration
Because you say
struct arg_struct *args = (struct arg_struct *)args;
instead of
struct arg_struct *args = arguments;
debug1: identity file /Users/tudouya/.ssh/vm/vm_id_rsa.pub type 1
It appears that you're trying to use the wrong key file. The file with the ".pub" extension contains the public portion of the key. The corresponding file without the ".pub" extension contains the private part of the key. When you run an ssh client to connect to a remote server, you have to provide the private key file to the ssh client.
You probably have a line in the your .ssh/config
file (or /etc/ssh_config
) which looks like this:
IdentityFile .../.ssh/vm/vm_id_rsa.pub
You need to remove the ".pub" extension from the filename:
IdentityFile .../.ssh/vm/vm_id_rsa
This is what I use:
private TextField textField;
textField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if(!newValue.matches("[0-9]*")){
textField.setText(oldValue);
}
}
});
The same in lambda notation would be:
private TextField textField;
textField.textProperty().addListener((observable, oldValue, newValue) -> {
if(!newValue.matches("[0-9]*")){
textField.setText(oldValue);
}
});
$ git rebase --abort
Run this code at any time if you want to undo the git rebase
$ git rebase -i HEAD~2
To reapply last two commits. The above command will open a code editor
After :wq you will be in active rebase mode
Note: You'll get another editor if no warning/error messages, If there is an error or warning another editor will not show, you may abort by runnning
$ git rebase --abort
if you see an error or warning else just continue by running $ git rebase --continue
You will see your 2 commit message. Choose one or write your own commit message, save and quit [:wq]
Note 2: You may need to force push your changes to the remote repo if you run rebase command
$ git push -f
$ git push -f origin master
For example summer
:
lblSummer.foreColor = color.Yellow;
In my opinion, two important scenarios other than stopping thread in which volatile keyword is used are:
Simply install the 32-bit version of the program, instead of the 64-bit version.
This is much safer than installing packages that are not intended for the distribution at hand.
I got this suggestion from the Google Earth installation instructions for Ubuntu 14.04.
Google Earth used to employ ia32-libs
under 64-bit Ubuntu 12.04.
Quoting webupd8.org:
The ia32-libs package is no longer available in Ubuntu, starting with Ubuntu 13.10. The package was superseded by multiarch support so you don't need it any more, but some 64bit packages (which are actually 32bit applications) still depend on this package and because of this, they can't be installed in Ubuntu 14.04 or 13.10, 64bit. [...]
The "fix" or more specifically the correct way of installing these apps which depend on ia32-libs is to simply install the 32bit package on Ubuntu 64bit. Of course, that will install quite a few 32bit packages, but that's how multiarch works.
The problem with some programs (like Google Earth) is that the 32-bit package does not support multiarch. Consequently, some 32-bit dependencies need to be installed manually to make the 32-bit version of the program run on Ubuntu 64-bit.
sudo dpkg --add-architecture i386 # only needed once
sudo apt-get update
sudo apt-get install libfontconfig1:i386 libx11-6:i386 libxrender1:i386 libxext6:i386 libgl1-mesa-glx:i386 libglu1-mesa:i386 libglib2.0-0:i386 libsm6:i386
You could use the System.Reflection
namespace with the Type.GetProperties()
mehod:
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public|BindingFlags.Static);
There is the way to safely removed system-image
Go in SDK Manager in toolbar :
Go in Android SDK :
In tab SDK Platforms, uncheck which platform you want unistall :
Click ok and confirm deletion :
Make sure that you are building your web app as "Any CPU". Right click your web project --> Properties --> Build --> and look for the "Platform Target". Choose "Any CPU" or play around with it.
Hope this helps!
You need to initialize the list first:
protected List<string> list = new List<string>();
You need to include the protocol scheme:
'http://192.168.1.61:8080/api/call'
Without the http://
part, requests
has no idea how to connect to the remote server.
Note that the protocol scheme must be all lowercase; if your URL starts with HTTP://
for example, it won’t find the http://
connection adapter either.
In New Xampp
All you have to do is to edit the file:
C:\xampp\apache\conf\extra\httpd-xampp.conf
and go to Directory tag as below:
<Directory "C:/xampp/phpMyAdmin">
and then change
Require local
To
Require all granted
in the Directory tag.
Restart the Xampp. That's it!
I had to run Visual Studio in Administrative Mode
to get rid of this error.
A better way to do a break line is using span with CSS style parameter white-space: nowrap;
span.nobreak {
white-space: nowrap;
}
or
span.nobreak {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
Example directly in your HTML
<span style='overflow:hidden; white-space: nowrap;'> YOUR EXTENSIVE TEXT THAT YOU CAN´T BREAK LINE ....</span>
Just adding this answer in case others are directed here by Google Search as I was.
I used the elevate
module in my Python script and the script executed with Administrator Privileges in Windows 10.
How about dropping the entire database and then creating it again? This works for me.
DROP DATABASE mydb;
CREATE DATABASE mydb;
You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.
sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module
If you add the module name to /etc/modules it will be loaded any time you boot.
Anyway I think that the proper configuration is to copy the module to the standard paths.
HTML5 number input doesn't have styles attributes like width or size, but you can style it easily with CSS.
input[type="number"] {
width:50px;
}
You can also use the drop_duplicates() instead of unique()
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].drop_duplicates()
a.sort()
print a
There are many articles about writing code to import an excel file, but this is a manual/shortcut version:
If you don't need to import your Excel file programmatically using code you can do it very quickly using the menu in SQL Management Studio.
The quickest way to get your Excel file into SQL is by using the import wizard:
The next window is 'Choose a Data Source', select Excel:
In the 'Data Source' dropdown list select Microsoft Excel (this option should appear automatically if you have excel installed).
Click the 'Browse' button to select the path to the Excel file you want to import.
On the 'Specify Table Copy or Query' window:
'Select Source Tables:' choose the worksheet(s) from your Excel file and specify a destination table for each worksheet. If you don't have a table yet the wizard will very kindly create a new table that matches all the columns from your spreadsheet. Click Next.
This post is just an observation for Python behaviour I encountered. Maybe the advices you read above don't work for you if you made the same thing I did below.
Namely, I have a module which contains global/shared variables (as suggested above):
#sharedstuff.py
globaltimes_randomnode=[]
globalist_randomnode=[]
Then I had the main module which imports the shared stuff with:
import sharedstuff as shared
and some other modules that actually populated these arrays. These are called by the main module. When exiting these other modules I can clearly see that the arrays are populated. But when reading them back in the main module, they were empty. This was rather strange for me (well, I am new to Python). However, when I change the way I import the sharedstuff.py in the main module to:
from globals import *
it worked (the arrays were populated).
Just sayin'
Solution from typescript interfaces reference:
interface ClockConstructor {
new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
tick();
}
function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
return new ctor(hour, minute);
}
class DigitalClock implements ClockInterface {
constructor(h: number, m: number) { }
tick() {
console.log("beep beep");
}
}
class AnalogClock implements ClockInterface {
constructor(h: number, m: number) { }
tick() {
console.log("tick tock");
}
}
let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);
So the previous example becomes:
interface AnimalConstructor {
new (): Animal;
}
class Animal {
constructor() {
console.log("Animal");
}
}
class Penguin extends Animal {
constructor() {
super();
console.log("Penguin");
}
}
class Lion extends Animal {
constructor() {
super();
console.log("Lion");
}
}
class Zoo {
AnimalClass: AnimalConstructor // AnimalClass can be 'Lion' or 'Penguin'
constructor(AnimalClass: AnimalConstructor) {
this.AnimalClass = AnimalClass
let Hector = new AnimalClass();
}
}
All these patterns, MVC, MVVM, MVP, and Presentation Model, can be applied to Android apps, but without a third-party framework, it is not easy to get well-organized structure and clean code.
MVVM is originated from PresentationModel. When we apply MVC, MVVM, and Presentation Model to an Android app, what we really want is to have a clear structured project and more importantly easier for unit tests.
At the moment, without an third-party framework, you usually have lots of code (like addXXListener(), findViewById(), etc.), which does not add any business value. What's more, you have to run Android unit tests instead of normal JUnit tests, which take ages to run and make unit tests somewhat impractical.
For these reasons, some years ago we started an open source project, RoboBinding - A data-binding Presentation Model framework for the Android platform. RoboBinding helps you write UI code that is easier to read, test, and maintain. RoboBinding removes the need of unnecessary code like addXXListener or so, and shifts UI logic to the Presentation Model, which is a POJO and can be tested via normal JUnit tests. RoboBinding itself comes with more than 300 JUnit tests to ensure its quality.
The internal storage is referred to as "external storage" in the API.
As mentioned in the Environment documentation
Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.
To distinguish whether "Environment.getExternalStorageDirectory()" actually returned physically internal or external storage, call Environment.isExternalStorageEmulated(). If it's emulated, than it's internal. On newer devices that have internal storage and sdcard slot Environment.getExternalStorageDirectory() will always return the internal storage. While on older devices that have only sdcard as a media storage option it will always return the sdcard.
There is no way to retrieve all storages using current Android API.
I've created a helper based on Vitaliy Polchuk's method in the answer below
How can I get the list of mounted external storage of android device
NOTE: starting KitKat secondary storage is accessible only as READ-ONLY, you may want to check for writability using the following method
/**
* Checks whether the StorageVolume is read-only
*
* @param volume
* StorageVolume to check
* @return true, if volume is mounted read-only
*/
public static boolean isReadOnly(@NonNull final StorageVolume volume) {
if (volume.mFile.equals(Environment.getExternalStorageDirectory())) {
// is a primary storage, check mounted state by Environment
return android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED_READ_ONLY);
} else {
if (volume.getType() == Type.USB) {
return volume.isReadOnly();
}
//is not a USB storagem so it's read-only if it's mounted read-only or if it's a KitKat device
return volume.isReadOnly() || Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
}
}
StorageHelper class
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import android.os.Environment;
public final class StorageHelper {
//private static final String TAG = "StorageHelper";
private StorageHelper() {
}
private static final String STORAGES_ROOT;
static {
final String primaryStoragePath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
final int index = primaryStoragePath.indexOf(File.separatorChar, 1);
if (index != -1) {
STORAGES_ROOT = primaryStoragePath.substring(0, index + 1);
} else {
STORAGES_ROOT = File.separator;
}
}
private static final String[] AVOIDED_DEVICES = new String[] {
"rootfs", "tmpfs", "dvpts", "proc", "sysfs", "none"
};
private static final String[] AVOIDED_DIRECTORIES = new String[] {
"obb", "asec"
};
private static final String[] DISALLOWED_FILESYSTEMS = new String[] {
"tmpfs", "rootfs", "romfs", "devpts", "sysfs", "proc", "cgroup", "debugfs"
};
/**
* Returns a list of mounted {@link StorageVolume}s Returned list always
* includes a {@link StorageVolume} for
* {@link Environment#getExternalStorageDirectory()}
*
* @param includeUsb
* if true, will include USB storages
* @return list of mounted {@link StorageVolume}s
*/
public static List<StorageVolume> getStorages(final boolean includeUsb) {
final Map<String, List<StorageVolume>> deviceVolumeMap = new HashMap<String, List<StorageVolume>>();
// this approach considers that all storages are mounted in the same non-root directory
if (!STORAGES_ROOT.equals(File.separator)) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("/proc/mounts"));
String line;
while ((line = reader.readLine()) != null) {
// Log.d(TAG, line);
final StringTokenizer tokens = new StringTokenizer(line, " ");
final String device = tokens.nextToken();
// skipped devices that are not sdcard for sure
if (arrayContains(AVOIDED_DEVICES, device)) {
continue;
}
// should be mounted in the same directory to which
// the primary external storage was mounted
final String path = tokens.nextToken();
if (!path.startsWith(STORAGES_ROOT)) {
continue;
}
// skip directories that indicate tha volume is not a storage volume
if (pathContainsDir(path, AVOIDED_DIRECTORIES)) {
continue;
}
final String fileSystem = tokens.nextToken();
// don't add ones with non-supported filesystems
if (arrayContains(DISALLOWED_FILESYSTEMS, fileSystem)) {
continue;
}
final File file = new File(path);
// skip volumes that are not accessible
if (!file.canRead() || !file.canExecute()) {
continue;
}
List<StorageVolume> volumes = deviceVolumeMap.get(device);
if (volumes == null) {
volumes = new ArrayList<StorageVolume>(3);
deviceVolumeMap.put(device, volumes);
}
final StorageVolume volume = new StorageVolume(device, file, fileSystem);
final StringTokenizer flags = new StringTokenizer(tokens.nextToken(), ",");
while (flags.hasMoreTokens()) {
final String token = flags.nextToken();
if (token.equals("rw")) {
volume.mReadOnly = false;
break;
} else if (token.equals("ro")) {
volume.mReadOnly = true;
break;
}
}
volumes.add(volume);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
// ignored
}
}
}
}
// remove volumes that are the same devices
boolean primaryStorageIncluded = false;
final File externalStorage = Environment.getExternalStorageDirectory();
final List<StorageVolume> volumeList = new ArrayList<StorageVolume>();
for (final Entry<String, List<StorageVolume>> entry : deviceVolumeMap.entrySet()) {
final List<StorageVolume> volumes = entry.getValue();
if (volumes.size() == 1) {
// go ahead and add
final StorageVolume v = volumes.get(0);
final boolean isPrimaryStorage = v.file.equals(externalStorage);
primaryStorageIncluded |= isPrimaryStorage;
setTypeAndAdd(volumeList, v, includeUsb, isPrimaryStorage);
continue;
}
final int volumesLength = volumes.size();
for (int i = 0; i < volumesLength; i++) {
final StorageVolume v = volumes.get(i);
if (v.file.equals(externalStorage)) {
primaryStorageIncluded = true;
// add as external storage and continue
setTypeAndAdd(volumeList, v, includeUsb, true);
break;
}
// if that was the last one and it's not the default external
// storage then add it as is
if (i == volumesLength - 1) {
setTypeAndAdd(volumeList, v, includeUsb, false);
}
}
}
// add primary storage if it was not found
if (!primaryStorageIncluded) {
final StorageVolume defaultExternalStorage = new StorageVolume("", externalStorage, "UNKNOWN");
defaultExternalStorage.mEmulated = Environment.isExternalStorageEmulated();
defaultExternalStorage.mType =
defaultExternalStorage.mEmulated ? StorageVolume.Type.INTERNAL
: StorageVolume.Type.EXTERNAL;
defaultExternalStorage.mRemovable = Environment.isExternalStorageRemovable();
defaultExternalStorage.mReadOnly =
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
volumeList.add(0, defaultExternalStorage);
}
return volumeList;
}
/**
* Sets {@link StorageVolume.Type}, removable and emulated flags and adds to
* volumeList
*
* @param volumeList
* List to add volume to
* @param v
* volume to add to list
* @param includeUsb
* if false, volume with type {@link StorageVolume.Type#USB} will
* not be added
* @param asFirstItem
* if true, adds the volume at the beginning of the volumeList
*/
private static void setTypeAndAdd(final List<StorageVolume> volumeList,
final StorageVolume v,
final boolean includeUsb,
final boolean asFirstItem) {
final StorageVolume.Type type = resolveType(v);
if (includeUsb || type != StorageVolume.Type.USB) {
v.mType = type;
if (v.file.equals(Environment.getExternalStorageDirectory())) {
v.mRemovable = Environment.isExternalStorageRemovable();
} else {
v.mRemovable = type != StorageVolume.Type.INTERNAL;
}
v.mEmulated = type == StorageVolume.Type.INTERNAL;
if (asFirstItem) {
volumeList.add(0, v);
} else {
volumeList.add(v);
}
}
}
/**
* Resolved {@link StorageVolume} type
*
* @param v
* {@link StorageVolume} to resolve type for
* @return {@link StorageVolume} type
*/
private static StorageVolume.Type resolveType(final StorageVolume v) {
if (v.file.equals(Environment.getExternalStorageDirectory())
&& Environment.isExternalStorageEmulated()) {
return StorageVolume.Type.INTERNAL;
} else if (containsIgnoreCase(v.file.getAbsolutePath(), "usb")) {
return StorageVolume.Type.USB;
} else {
return StorageVolume.Type.EXTERNAL;
}
}
/**
* Checks whether the array contains object
*
* @param array
* Array to check
* @param object
* Object to find
* @return true, if the given array contains the object
*/
private static <T> boolean arrayContains(T[] array, T object) {
for (final T item : array) {
if (item.equals(object)) {
return true;
}
}
return false;
}
/**
* Checks whether the path contains one of the directories
*
* For example, if path is /one/two, it returns true input is "one" or
* "two". Will return false if the input is one of "one/two", "/one" or
* "/two"
*
* @param path
* path to check for a directory
* @param dirs
* directories to find
* @return true, if the path contains one of the directories
*/
private static boolean pathContainsDir(final String path, final String[] dirs) {
final StringTokenizer tokens = new StringTokenizer(path, File.separator);
while (tokens.hasMoreElements()) {
final String next = tokens.nextToken();
for (final String dir : dirs) {
if (next.equals(dir)) {
return true;
}
}
}
return false;
}
/**
* Checks ifString contains a search String irrespective of case, handling.
* Case-insensitivity is defined as by
* {@link String#equalsIgnoreCase(String)}.
*
* @param str
* the String to check, may be null
* @param searchStr
* the String to find, may be null
* @return true if the String contains the search String irrespective of
* case or false if not or {@code null} string input
*/
public static boolean containsIgnoreCase(final String str, final String searchStr) {
if (str == null || searchStr == null) {
return false;
}
final int len = searchStr.length();
final int max = str.length() - len;
for (int i = 0; i <= max; i++) {
if (str.regionMatches(true, i, searchStr, 0, len)) {
return true;
}
}
return false;
}
/**
* Represents storage volume information
*/
public static final class StorageVolume {
/**
* Represents {@link StorageVolume} type
*/
public enum Type {
/**
* Device built-in internal storage. Probably points to
* {@link Environment#getExternalStorageDirectory()}
*/
INTERNAL,
/**
* External storage. Probably removable, if no other
* {@link StorageVolume} of type {@link #INTERNAL} is returned by
* {@link StorageHelper#getStorages(boolean)}, this might be
* pointing to {@link Environment#getExternalStorageDirectory()}
*/
EXTERNAL,
/**
* Removable usb storage
*/
USB
}
/**
* Device name
*/
public final String device;
/**
* Points to mount point of this device
*/
public final File file;
/**
* File system of this device
*/
public final String fileSystem;
/**
* if true, the storage is mounted as read-only
*/
private boolean mReadOnly;
/**
* If true, the storage is removable
*/
private boolean mRemovable;
/**
* If true, the storage is emulated
*/
private boolean mEmulated;
/**
* Type of this storage
*/
private Type mType;
StorageVolume(String device, File file, String fileSystem) {
this.device = device;
this.file = file;
this.fileSystem = fileSystem;
}
/**
* Returns type of this storage
*
* @return Type of this storage
*/
public Type getType() {
return mType;
}
/**
* Returns true if this storage is removable
*
* @return true if this storage is removable
*/
public boolean isRemovable() {
return mRemovable;
}
/**
* Returns true if this storage is emulated
*
* @return true if this storage is emulated
*/
public boolean isEmulated() {
return mEmulated;
}
/**
* Returns true if this storage is mounted as read-only
*
* @return true if this storage is mounted as read-only
*/
public boolean isReadOnly() {
return mReadOnly;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((file == null) ? 0 : file.hashCode());
return result;
}
/**
* Returns true if the other object is StorageHelper and it's
* {@link #file} matches this one's
*
* @see Object#equals(Object)
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final StorageVolume other = (StorageVolume) obj;
if (file == null) {
return other.file == null;
}
return file.equals(other.file);
}
@Override
public String toString() {
return file.getAbsolutePath() + (mReadOnly ? " ro " : " rw ") + mType + (mRemovable ? " R " : "")
+ (mEmulated ? " E " : "") + fileSystem;
}
}
}
my solution:
MOVE:
jQuery("#NodesToMove").detach().appendTo('#DestinationContainerNode')
COPY:
jQuery("#NodesToMove").appendTo('#DestinationContainerNode')
Note the usage of .detach(). When copying, be careful that you are not duplicating IDs.
I wanted a more concise answer and I came up with the following using the documentation at aggregates and group
db.countries.aggregate([{"$group": {"_id": "$country", "count":{"$sum": 1}}])
You can use
reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run /v ServiceName /d "c:\path\to\service\file\exe"
And it will appear int the service list. I do not know, whether that works correctly though. A service usually has to listen to several events.
There are several service wrapper though, that can run any application as a real service. For Example Microsofts SrvAny from the Win2003 Resource Kit
If you are doing it with Django, you can just pass the function with the context:
context = {
'title':'My title',
'str': str,
}
...
return render(request, 'index.html', context)
Now you will be able to use the str
function in jinja2 template
I prefer Serializable
= no boilerplate code. For passing data to other Fragments or Activities the speed difference to a Parcelable
does not matter.
I would also always provide a helper method for a Fragment
or Activity
, this way you always know, what data has to be passed. Here an example for your ListMusicFragment
:
private static final String EXTRA_MUSIC_LIST = "music_list";
public static ListMusicFragment createInstance(List<Music> music) {
ListMusicFragment fragment = new ListMusicFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(EXTRA_MUSIC_LIST, music);
fragment.setArguments(bundle);
return fragment;
}
@Override
public View onCreateView(...) {
...
Bundle bundle = intent.getArguments();
List<Music> musicList = (List<Music>)bundle.getSerializable(EXTRA_MUSIC_LIST);
...
}
Another way, which I didn't see posted, is to use a Queue. It's analogous to a way to implement a SkipLast() method without iterating more than necessary. This way will also allow you to do this on any number of last items.
public static void ForEachAndKnowIfLast<T>(
this IEnumerable<T> source,
Action<T, bool> a,
int numLastItems = 1)
{
int bufferMax = numLastItems + 1;
var buffer = new Queue<T>(bufferMax);
foreach (T x in source)
{
buffer.Enqueue(x);
if (buffer.Count < bufferMax)
continue; //Until the buffer is full, just add to it.
a(buffer.Dequeue(), false);
}
foreach (T item in buffer)
a(item, true);
}
To call this you'd do the following:
Model.Results.ForEachAndKnowIfLast(
(result, isLast) =>
{
//your logic goes here, using isLast to do things differently for last item(s).
});
I used this method.
Looper.myLooper().quit();
you can try.
pls try this,
$('#select_id option[value="'+value+'"]').attr("disabled", true);
I tried removing the .svn folder to other location and placed it back in the same root folder. After when I tried to update the SVN, it got updated. I don't know how exactly it worked.
How about:
if (stream.markSupported() == false) {
// lets replace the stream object
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(stream, baos);
stream.close();
stream = new ByteArrayInputStream(baos.toByteArray());
// now the stream should support 'mark' and 'reset'
}
This example selects a new Range
of Cells
defined by the current cell to a cell 5 to the right.
Note that .Offset
takes arguments of Offset(row, columns)
and can be quite useful.
Sub testForStackOverflow()
Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub
In my case I found that there were missing "await" statements before myContext.SaveChangesAsync() calls. Adding await before those async calls fixed the data reader issues for me.
Declaration, generally, refers to the introduction of a new name in the program. For example, you can declare a new function by describing it's "signature":
void xyz();
or declare an incomplete type:
class klass;
struct ztruct;
and last but not least, to declare an object:
int x;
It is described, in the C++ standard, at §3.1/1 as:
A declaration (Clause 7) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations.
A definition is a definition of a previously declared name (or it can be both definition and declaration). For example:
int x;
void xyz() {...}
class klass {...};
struct ztruct {...};
enum { x, y, z };
Specifically the C++ standard defines it, at §3.1/1, as:
A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function- body, it declares a static data member in a class definition (9.2, 9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), it is a template-parameter (14.1), it is a parameter-declaration (8.3.5) in a function declarator that is not the declarator of a function-definition, or it is a typedef declaration (7.1.3), an alias-declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attribute- declaration (Clause 7), an empty-declaration (Clause 7), or a using-directive (7.3.4).
Initialization refers to the "assignment" of a value, at construction time. For a generic object of type T
, it's often in the form:
T x = i;
but in C++ it can be:
T x(i);
or even:
T x {i};
with C++11.
So does it mean definition equals declaration plus initialization?
It depends. On what you are talking about. If you are talking about an object, for example:
int x;
This is a definition without initialization. The following, instead, is a definition with initialization:
int x = 0;
In certain context, it doesn't make sense to talk about "initialization", "definition" and "declaration". If you are talking about a function, for example, initialization does not mean much.
So, the answer is no: definition does not automatically mean declaration plus initialization.
Just in case if you are using Telerik components and you have a reference in your javascript with <%= .... %> then wrap your script tag with a RadScriptBlock.
<telerik:RadScriptBlock ID="radSript1" runat="server">
<script type="text/javascript">
//Your javascript
</script>
</telerik>
Regards Örvar
HTTP 1.1 comes with the host header in its specification while the HTTP 1.0 doesn't officially have a host header, but it doesn't refuse to add one.
The host header is useful because it allows the client to route a message throughout the proxy server, and the major difference between 1.0 and 1.1 versions HTTP are:
SELECT
*
FROM
(
SELECT
top 20 -- ($a) number of records to show
*
FROM
(
SELECT
top 29 -- ($b) last record position
*
FROM
table -- replace this for table name (i.e. "Customer")
ORDER BY
2 ASC
) AS tbl1
ORDER BY
2 DESC
) AS tbl2
ORDER BY
2 ASC;
-- Examples:
-- Show 5 records from position 5:
-- $a = 5;
-- $b = (5 + 5) - 1
-- $b = 9;
-- Show 10 records from position 4:
-- $a = 10;
-- $b = (10 + 4) - 1
-- $b = 13;
-- To calculate $b:
-- $b = ($a + position) - 1
-- For the present exercise we need to:
-- Show 20 records from position 10:
-- $a = 20;
-- $b = (20 + 10) - 1
-- $b = 29;
Do you want to print the entire list or you want to iterate through each element of the list? Either way to print anything meaningful your Dog
class need to override the toString()
method (as mentioned in other answers) from the Object
class to return a valid result.
public class Print {
public static void main(final String[] args) {
List<Dog> list = new ArrayList<Dog>();
Dog e = new Dog("Tommy");
list.add(e);
list.add(new Dog("tiger"));
System.out.println(list);
for(Dog d:list) {
System.out.println(d);
// prints [Tommy, tiger]
}
}
private static class Dog {
private final String name;
public Dog(final String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
}
The output of this code is:
[Tommy, tiger]
Tommy
tiger
Try to rebase your local master branch onto your remote/origin master branch and resolve any conflicts in the process.
You can also do this in a .htaccess file assuming they are enabled on the website.
SetEnv KOHANA_ENV production
Would be all you need to add to a .htaccess to add the environment variable
While jkp's solution works, the newer way of doing things (and the way the documentation recommends) is to use the subprocess
module. For simple commands its equivalent, but it offers more options if you want to do something complicated.
Example for your case:
import subprocess
subprocess.Popen(["rm","-r","some.file"])
This will run rm -r some.file
in the background. Note that calling .communicate()
on the object returned from Popen
will block until it completes, so don't do that if you want it to run in the background:
import subprocess
ls_output=subprocess.Popen(["sleep", "30"])
ls_output.communicate() # Will block for 30 seconds
See the documentation here.
Also, a point of clarification: "Background" as you use it here is purely a shell concept; technically, what you mean is that you want to spawn a process without blocking while you wait for it to complete. However, I've used "background" here to refer to shell-background-like behavior.
PHP will do it for you within limits
<?php
$str = "3.148";
$num = $str;
printf("%f\n", $num);
?>
About the .dex File :
One of the most remarkable features of the Dalvik Virtual Machine
(the workhorse under the Android system) is that it does not use Java bytecode. Instead, a homegrown format called DEX was introduced and not even the bytecode instructions are the same as Java bytecode instructions.
Compiled Android application code file.
Android programs are compiled into .dex
(Dalvik Executable) files, which are in turn zipped into a single .apk
file on the device. .dex
files can be created by automatically translating compiled applications written in the Java programming language.
Dex file format:
1. File Header
2. String Table
3. Class List
4. Field Table
5. Method Table
6. Class Definition Table
7. Field List
8. Method List
9. Code Header
10. Local Variable List
Android has documentation on the Dalvik Executable Format
(.dex files). You can find out more over at the official docs: Dex File Format
.dex
files are similar to java class files, but they were run under the Dalkvik Virtual Machine (DVM) on older Android versions, and compiled at install time on the device to native code with ART on newer Android versions.
You can decompile
.dex using the dexdump
tool which is provided in android-sdk.
There are also some Reverse Engineering Techniques to make a jar file
or java class file
from a .dex
file.
The link provided in the accepted answer shows a nice way to implement the pub/sub system using jQuery, but I found the code somewhat difficult to read, so here is my simplified version of the code:
$(document).on('testEvent', function(e, eventInfo) {
subscribers = $('.subscribers-testEvent');
subscribers.trigger('testEventHandler', [eventInfo]);
});
$('#myButton').on('click', function() {
$(document).trigger('testEvent', [1011]);
});
$('#notifier1').on('testEventHandler', function(e, eventInfo) {
alert('(notifier1)The value of eventInfo is: ' + eventInfo);
});
$('#notifier2').on('testEventHandler', function(e, eventInfo) {
alert('(notifier2)The value of eventInfo is: ' + eventInfo);
});
If you want to implement a public class, you must implement it in a file with the same name as that class. A single file can contain one public and optionally some private classes. This is useful if the classes are only used internally by the public class. Additionally the public class can also contain inner classes.
Although it is fine to have one or more private classes in a single source file, I would say that is more readable to use inner and anonymous classes instead. For example one can use an anonymous class to define a Comparator class inside a public class:
public static Comparator MyComparator = new Comparator() {
public int compare(Object obj, Object anotherObj) {
}
};
The Comparator class will normally require a separate file in order to be public. This way it is bundled with the class that uses it.
I took what you had, and added another X-Testing
header
var config = {headers: {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose',
"X-Testing" : "testing"
}
};
$http.get("/test", config);
And in the Chrome network tab, I see them being sent.
GET /test HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Accept: application/json;odata=verbose
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22
Authorization: Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==
X-Testing: testing
Referer: http://localhost:3000/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Are you not seeing them from the browser, or on the server? Try the browser tooling or a debug proxy and see what is being sent out.
Create a class to hold the objects.
public class Person{
private String name;
private String url;
//Get & Set methods for each field
}
Then deserialize as follows:
Gson gson = new Gson();
Person[] person = gson.fromJson(input, Person[].class); //input is your String
Reference Article: http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/
Historically (we're talking the 1980s and early 1990s), there were some architectures in which this was true. The root issue is that integer comparison is inherently implemented via integer subtractions. This gives rise to the following cases.
Comparison Subtraction
---------- -----------
A < B --> A - B < 0
A = B --> A - B = 0
A > B --> A - B > 0
Now, when A < B
the subtraction has to borrow a high-bit for the subtraction to be correct, just like you carry and borrow when adding and subtracting by hand. This "borrowed" bit was usually referred to as the carry bit and would be testable by a branch instruction. A second bit called the zero bit would be set if the subtraction were identically zero which implied equality.
There were usually at least two conditional branch instructions, one to branch on the carry bit and one on the zero bit.
Now, to get at the heart of the matter, let's expand the previous table to include the carry and zero bit results.
Comparison Subtraction Carry Bit Zero Bit
---------- ----------- --------- --------
A < B --> A - B < 0 0 0
A = B --> A - B = 0 1 1
A > B --> A - B > 0 1 0
So, implementing a branch for A < B
can be done in one instruction, because the carry bit is clear only in this case, , that is,
;; Implementation of "if (A < B) goto address;"
cmp A, B ;; compare A to B
bcz address ;; Branch if Carry is Zero to the new address
But, if we want to do a less-than-or-equal comparison, we need to do an additional check of the zero flag to catch the case of equality.
;; Implementation of "if (A <= B) goto address;"
cmp A, B ;; compare A to B
bcz address ;; branch if A < B
bzs address ;; also, Branch if the Zero bit is Set
So, on some machines, using a "less than" comparison might save one machine instruction. This was relevant in the era of sub-megahertz processor speed and 1:1 CPU-to-memory speed ratios, but it is almost totally irrelevant today.
I prefer the first version to start a java application just because it has less pitfalls ("welcome to classpath hell"). The second one requires an executable jar file and the classpath for that application has to be defined inside the jar's manifest (all other classpath declaration will be silently ignored...). So with the second version you'd have to look into the jar, read the manifest and try to find out if the classpath entries are valid from where the jar is stored... That's avoidable.
I don't expect any performance advantages or disadvantages for either version. It's just telling the jvm which class to use for the main thread and where it can find the libraries.
Taking for granted that the JSON you posted is actually what you are seeing in the browser, then the problem is the JSON itself.
The JSON snippet you have posted is malformed.
You have posted:
[{
"name" : "shopqwe",
"mobiles" : [],
"address" : {
"town" : "city",
"street" : "streetqwe",
"streetNumber" : "59",
"cordX" : 2.229997,
"cordY" : 1.002539
},
"shoe"[{
"shoeName" : "addidas",
"number" : "631744030",
"producent" : "nike",
"price" : 999.0,
"sizes" : [30.0, 35.0, 38.0]
}]
while the correct JSON would be:
[{
"name" : "shopqwe",
"mobiles" : [],
"address" : {
"town" : "city",
"street" : "streetqwe",
"streetNumber" : "59",
"cordX" : 2.229997,
"cordY" : 1.002539
},
"shoe" : [{
"shoeName" : "addidas",
"number" : "631744030",
"producent" : "nike",
"price" : 999.0,
"sizes" : [30.0, 35.0, 38.0]
}
]
}
]
__call__
makes any object be callable as a function.
This example will output 8:
class Adder(object):
def __init__(self, val):
self.val = val
def __call__(self, val):
return self.val + val
func = Adder(5)
print func(3)
There's no need to set a fact.
- shell: cat "hello"
register: cat_contents
- shell: echo "I cat hello"
when: cat_contents.stdout == "hello"
The best way now is to use the "Quit" button that is just to the left of the "Logout" button. I have to admit that I do not understand the utility of the Logout button. However, I am glad that they have added the exceedingly useful Quit button.
Do you have something against splitting it up?
...FROM <blah>
WHERE
(fieldA LIKE '%THIS%' OR fieldA LIKE '%THAT%')
AND something = else
This is the one symptom of greater issues. Notably that you have something setting TERM=dumb
. Other things that don't work properly are the less
command which says you don't have a fully functional terminal.
It seems like this is most commonly caused by having TERM set to something in your global Windows environment variables. For me, the issue came up when I installed Strawberry Perl some information about this is on the msysgit bug for this problem as well as several solutions.
The first solution is to fix it in your ~/.bashrc by adding:
export TERM=msys
You can do this from the Git Bash prompt like so:
echo "export TERM=msys" >> ~/.bashrc
The other solution, which ultimately is what I did because I don't care about Strawberry Perl's reasons for adding TERM=dumb
to my environment settings, is to go and remove the TERM=dumb
as directed in this comment on the msysgit bug report.
Control Panel/System/Advanced/Environment Variables... (or similar, depending on your version of Windows) is where sticky environment variables are set on Windows. By default, TERM is not set. If TERM is set in there, then you (or one of the programs you have installed - e.g. Strawberry Perl) has set it. Delete that setting, and you should be fine.
Similarly if you use Strawberry Perl and care about the CPAN client or something like that, you can leave the TERM=dumb
alone and use unset TERM
in your ~/.bashrc file which will have a similar effect to setting an explicit term as above.
Of course, all the other solutions are correct in that you can use git config --global core.editor $MYFAVORITEEDITOR
to make sure that Git uses your favorite editor when it needs to launch one for you.
May be this algorithm can work for question 1:
Or even better:
def GetValue(A)
val=0
for i=1 to 100
do
val=val^i
done
for value in A:
do
val=val^value
done
return val
This algorithm can in fact be expanded for two missing numbers. The first step remains the same. When we call GetValue with two missing numbers the result will be a a1^a2
are the two missing numbers. Lets say
val = a1^a2
Now to sieve out a1 and a2 from val we take any set bit in val. Lets say the ith
bit is set in val. That means that a1 and a2 have different parity at ith
bit position.
Now we do another iteration on the original array and keep two xor values. One for the numbers which have the ith bit set and other which doesn't have the ith bit set. We now have two buckets of numbers, and its guranteed that a1 and a2
will lie in different buckets. Now repeat the same what we did for finding one missing element on each of the bucket.
<?php
$string = 'foo';
if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $string))
{
// one or more of the 'special characters' found in $string
}
The best way to avoid this kind of issues it to build properties programmatically and then store them. For example, using code like this:
java.util.Properties props = new java.util.Properties();
props.setProperty("table.whereclause", "where id=100");
props.store(System.out, null);
This would output to System.out the properly escaped version.
In my case the output was:
#Mon Aug 12 13:50:56 EEST 2013
table.whereclause=where id\=100
As you can see, this is an easy way to generate content of .properties files that's guaranteed to be correct. And you can put as many properties as you want.
One difference observed (Python27):
os.environ
raises an exception if the environmental variable does not exist.
os.getenv
does not raise an exception, but returns None
For the poor guys like me using python 3.7. You need the python3.7-tk
package.
sudo apt install python3.7-tk
$ python
Python 3.7.4 (default, Sep 2 2019, 20:44:09)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'tkinter'
>>> exit()
Note. python3-tk
is installed. But not python3.7-tk
.
$ sudo apt install python3.7-tk
Reading package lists... Done
Building dependency tree
Reading state information... Done
Suggested packages:
tix python3.7-tk-dbg
The following NEW packages will be installed:
python3.7-tk
0 upgraded, 1 newly installed, 0 to remove and 34 not upgraded.
Need to get 143 kB of archives.
After this operation, 534 kB of additional disk space will be used.
Get:1 http://ppa.launchpad.net/deadsnakes/ppa/ubuntu xenial/main amd64 python3.7-tk amd64 3.7.4-1+xenial2 [143
kB]
Fetched 143 kB in 0s (364 kB/s)
Selecting previously unselected package python3.7-tk:amd64.
(Reading database ... 256375 files and directories currently installed.)
Preparing to unpack .../python3.7-tk_3.7.4-1+xenial2_amd64.deb ...
Unpacking python3.7-tk:amd64 (3.7.4-1+xenial2) ...
Setting up python3.7-tk:amd64 (3.7.4-1+xenial2) ...
After installing it, all good.
$ python3
Python 3.7.4 (default, Sep 2 2019, 20:44:09)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter
>>> exit()
Solve problem with two method parse common
public <T> T jsonToObject(String json, Class<T> type) {
T target = null;
try {
target = objectMapper.readValue(json, type);
} catch (Jsenter code hereonProcessingException e) {
e.printStackTrace();
}
return target;
}
public <T> T jsonToObject(String json, TypeReference<T> type) {
T target = null;
try {
target = objectMapper.readValue(json, type);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return target;
}
Late to the party, but might be of interest...
I find a combination of labs
and guides
specification useful in many cases:
You want nothing but a grid and a background:
ggplot(diamonds, mapping = aes(x = clarity)) +
geom_bar(aes(fill = cut)) +
labs(x = NULL, y = NULL) +
guides(x = "none", y = "none")
You want to only suppress the tick-mark label of one or both axes:
ggplot(diamonds, mapping = aes(x = clarity)) +
geom_bar(aes(fill = cut)) +
guides(x = "none", y = "none")
This will do the job too:
echo "$pid"|awk '{print $2}'
It is sometimes useful to not use quotes... because this can highlight issues in the code generating the query... For example:
Where x and y are should always be integers...
SELECT * FROM table
WHERE x= AND y=0
Is a SQL syntax error... a little lazy but can be useful...
A bit late but as this is an ongoing issue with Mac OSX...
The simplest solution I found was to simply remove the OpenJDK stuff that Apple installs. Every time an update of Mac OSX arrives it gets installed and you'll need to remove it again.
This works really well if you develop apps for Google App Engine on your mac using Java. The OpenJDK does not work well and the Java version that comes with the Mac OSX Yosemite upgrade will make the Eclipse Plug-in for App Engine crash on every deployment with the helpful error: "Read timed out".
Try the below Code:
$("#textbox").on('change keypress paste', function() {
console.log("Handler for .keypress() called.");
});
it depends if your div is in position: absolute / fixed or relative / static
for position: absolute & fixed
<div style="position: absolute; /*or fixed*/;
width: 50%;
height: 300px;
left: 50%;
top:100px;
margin: 0 0 0 -25%">blblablbalba</div>
The trick here is to have a negative margin half the width of the object
for position: relative & static
<div style="position: relative; /*or static*/;
width: 50%;
height: 300px;
margin: 0 auto">blblablbalba</div>
for both techniques, it is imperative to set the width.
You should restart apache or httpd, not mysqld
sudo service httpd restart
or
sudo /etc/init.d/apache2 restart
Motivation
Many data sets are large enough that we need to concern ourselves with speed/efficiency. So I offer this solution in that spirit. It happens to also be succinct.
For the sake of comparison, let's drop the index
column
df = data_set.drop('index', 1)
Solution
I'll propose the use of zip
and map
list(zip(*map(df.get, df)))
[('2012-02-17', 24.75, 25.03),
('2012-02-16', 25.0, 25.07),
('2012-02-15', 24.99, 25.15),
('2012-02-14', 24.68, 25.05),
('2012-02-13', 24.62, 24.77),
('2012-02-10', 24.38, 24.61)]
It happens to also be flexible if we wanted to deal with a specific subset of columns. We'll assume the columns we've already displayed are the subset we want.
list(zip(*map(df.get, ['data_date', 'data_1', 'data_2'])))
[('2012-02-17', 24.75, 25.03),
('2012-02-16', 25.0, 25.07),
('2012-02-15', 24.99, 25.15),
('2012-02-14', 24.68, 25.05),
('2012-02-13', 24.62, 24.77),
('2012-02-10', 24.38, 24.61)]
Turn's out records
is quickest followed by asymptotically converging zipmap
and iter_tuples
I'll use a library simple_benchmarks
that I got from this post
from simple_benchmark import BenchmarkBuilder
b = BenchmarkBuilder()
import pandas as pd
import numpy as np
def tuple_comp(df): return [tuple(x) for x in df.to_numpy()]
def iter_namedtuples(df): return list(df.itertuples(index=False))
def iter_tuples(df): return list(df.itertuples(index=False, name=None))
def records(df): return df.to_records(index=False).tolist()
def zipmap(df): return list(zip(*map(df.get, df)))
funcs = [tuple_comp, iter_namedtuples, iter_tuples, records, zipmap]
for func in funcs:
b.add_function()(func)
def creator(n):
return pd.DataFrame({"A": random.randint(n, size=n), "B": random.randint(n, size=n)})
@b.add_arguments('Rows in DataFrame')
def argument_provider():
for n in (10 ** (np.arange(4, 11) / 2)).astype(int):
yield n, creator(n)
r = b.run()
Check the results
r.to_pandas_dataframe().pipe(lambda d: d.div(d.min(1), 0))
tuple_comp iter_namedtuples iter_tuples records zipmap
100 2.905662 6.626308 3.450741 1.469471 1.000000
316 4.612692 4.814433 2.375874 1.096352 1.000000
1000 6.513121 4.106426 1.958293 1.000000 1.316303
3162 8.446138 4.082161 1.808339 1.000000 1.533605
10000 8.424483 3.621461 1.651831 1.000000 1.558592
31622 7.813803 3.386592 1.586483 1.000000 1.515478
100000 7.050572 3.162426 1.499977 1.000000 1.480131
r.plot()
Perhaps use this:
[a[i] for i in (1,2,5)]
# [11, 12, 15]
Wrap your formula with IFERROR
.
=IFERROR(yourformula)
LTrim function and RTrim function :
It uses the Trim function to remove both types of spaces.
select LTRIM(RTRIM(' SQL Server '))
output:
SQL Server
In most cases, you won't see an actual difference between the two approaches, but it's easy to construct a worst case scenario like this one:
public class Main
{
public static void main(String[] args)
{
long now = System.currentTimeMillis();
slow();
System.out.println("slow elapsed " + (System.currentTimeMillis() - now) + " ms");
now = System.currentTimeMillis();
fast();
System.out.println("fast elapsed " + (System.currentTimeMillis() - now) + " ms");
}
private static void fast()
{
StringBuilder s = new StringBuilder();
for(int i=0;i<100000;i++)
s.append("*");
}
private static void slow()
{
String s = "";
for(int i=0;i<100000;i++)
s+="*";
}
}
The output is:
slow elapsed 11741 ms
fast elapsed 7 ms
The problem is that to += append to a string reconstructs a new string, so it costs something linear to the length of your strings (sum of both).
So - to your question:
The second approach would be faster, but it's less readable and harder to maintain. As I said, in your specific case you would probably not see the difference.
Print content of object you can use
console.log(obj_str);
you can see the result in console like below.
Object {description: "test"}
For open console press F12 in chrome browser, you will found console tab in debug mode.
Print the last json error when debugging.
Also use the json.stringify() function to double check your JSON syntax.
json_decode( $so, true, 9 );
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
);
echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
The polynomial for CRC32 is:
x32 + x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2 + x + 1
Or in hex and binary:
0x 01 04 C1 1D B7
1 0000 0100 1100 0001 0001 1101 1011 0111
The highest term (x32) is usually not explicitly written, so it can instead be represented in hex just as
0x 04 C1 1D B7
Feel free to count the 1s and 0s, but you'll find they match up with the polynomial, where 1
is bit 0 (or the first bit) and x
is bit 1 (or the second bit).
Why this polynomial? Because there needs to be a standard given polynomial and the standard was set by IEEE 802.3. Also it is extremely difficult to find a polynomial that detects different bit errors effectively.
You can think of the CRC-32 as a series of "Binary Arithmetic with No Carries", or basically "XOR and shift operations". This is technically called Polynomial Arithmetic.
To better understand it, think of this multiplication:
(x^3 + x^2 + x^0)(x^3 + x^1 + x^0)
= (x^6 + x^4 + x^3
+ x^5 + x^3 + x^2
+ x^3 + x^1 + x^0)
= x^6 + x^5 + x^4 + 3*x^3 + x^2 + x^1 + x^0
If we assume x is base 2 then we get:
x^7 + x^3 + x^2 + x^1 + x^0
Why? Because 3x^3 is 11x^11 (but we need only 1 or 0 pre digit) so we carry over:
=1x^110 + 1x^101 + 1x^100 + 11x^11 + 1x^10 + 1x^1 + x^0
=1x^110 + 1x^101 + 1x^100 + 1x^100 + 1x^11 + 1x^10 + 1x^1 + x^0
=1x^110 + 1x^101 + 1x^101 + 1x^11 + 1x^10 + 1x^1 + x^0
=1x^110 + 1x^110 + 1x^11 + 1x^10 + 1x^1 + x^0
=1x^111 + 1x^11 + 1x^10 + 1x^1 + x^0
But mathematicians changed the rules so that it is mod 2. So basically any binary polynomial mod 2 is just addition without carry or XORs. So our original equation looks like:
=( 1x^110 + 1x^101 + 1x^100 + 11x^11 + 1x^10 + 1x^1 + x^0 ) MOD 2
=( 1x^110 + 1x^101 + 1x^100 + 1x^11 + 1x^10 + 1x^1 + x^0 )
= x^6 + x^5 + x^4 + 3*x^3 + x^2 + x^1 + x^0 (or that original number we had)
I know this is a leap of faith but this is beyond my capability as a line-programmer. If you are a hard-core CS-student or engineer I challenge to break this down. Everyone will benefit from this analysis.
So to work out a full example:
Original message : 1101011011
Polynomial of (W)idth 4 : 10011
Message after appending W zeros : 11010110110000
Now we divide the augmented Message by the Poly using CRC arithmetic. This is the same division as before:
1100001010 = Quotient (nobody cares about the quotient)
_______________
10011 ) 11010110110000 = Augmented message (1101011011 + 0000)
=Poly 10011,,.,,....
-----,,.,,....
10011,.,,....
10011,.,,....
-----,.,,....
00001.,,....
00000.,,....
-----.,,....
00010,,....
00000,,....
-----,,....
00101,....
00000,....
-----,....
01011....
00000....
-----....
10110...
10011...
-----...
01010..
00000..
-----..
10100.
10011.
-----.
01110
00000
-----
1110 = Remainder = THE CHECKSUM!!!!
The division yields a quotient, which we throw away, and a remainder, which is the calculated checksum. This ends the calculation. Usually, the checksum is then appended to the message and the result transmitted. In this case the transmission would be: 11010110111110.
Only use a 32-bit number as your divisor and use your entire stream as your dividend. Throw out the quotient and keep the remainder. Tack the remainder on the end of your message and you have a CRC32.
Average guy review:
QUOTIENT
----------
DIVISOR ) DIVIDEND
= REMAINDER
(Note that the stream has to be dividable by 32 bits or it should be padded. For example, an 8-bit ANSI stream would have to be padded. Also at the end of the stream, the division is halted.)
if you want to concatenate the string representation of the values of two variables, use the +
sign :
var var1 = 1;
var var2 = "bob";
var var3 = var2 + var1;//=bob1
But if you want to keep the two in only one variable, but still be able to access them later, you could make an object container:
function Container(){
this.variables = [];
}
Container.prototype.addVar = function(var){
this.variables.push(var);
}
Container.prototype.toString = function(){
var result = '';
for(var i in this.variables)
result += this.variables[i];
return result;
}
var var1 = 1;
var var2 = "bob";
var container = new Container();
container.addVar(var2);
container.addVar(var1);
container.toString();// = bob1
the advantage is that you can get the string representation of the two variables, bit you can modify them later :
container.variables[0] = 3;
container.variables[1] = "tom";
container.toString();// = tom3
HTML Code:
<form method="post" action="#" id="#">
<div class="form-group files color">
<input type="file" class="form-control" multiple="">
</div>
CSS:
.files input {
outline: 2px dashed #92b0b3;
outline-offset: -10px;
-webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear;
transition: outline-offset .15s ease-in-out, background-color .15s linear;
padding: 120px 0px 85px 35%;
text-align: center !important;
margin: 0;
width: 100% !important;
height: 400px;
}
.files input:focus{
outline: 2px dashed #92b0b3;
outline-offset: -10px;
-webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear;
transition: outline-offset .15s ease-in-out, background-color .15s linear;
border:1px solid #92b0b3;
}
.files{ position:relative}
.files:after { pointer-events: none;
position: absolute;
top: 60px;
left: 0;
width: 50px;
right: 0;
height: 400px;
content: "";
background-image: url('../../images/');
display: block;
margin: 0 auto;
background-size: 100%;
background-repeat: no-repeat;
}
.color input{ background-color:#f1f1f1;}
.files:before {
position: absolute;
bottom: 10px;
left: 0; pointer-events: none;
width: 100%;
right: 0;
height: 400px;
display: block;
margin: 0 auto;
color: #2ea591;
font-weight: 600;
text-transform: capitalize;
text-align: center;
}
It is better to include stdlib.h
. Since without stdlibg it takes long as long
To further generalize @Alexander's example, outer
is relevant in cases where a function must compute itself on each pair of vector values:
vars1<-c(1,2,3)
vars2<-c(10,20,30)
mult_one<-function(var1,var2)
{
var1*var2
}
outer(vars1,vars2,mult_one)
gives:
> outer(vars1, vars2, mult_one)
[,1] [,2] [,3]
[1,] 10 20 30
[2,] 20 40 60
[3,] 30 60 90
for(var a=1;a<8;a++){
var o="";
for(var b=1;b<=a;b++){
o +="#";
}
debug(o);
}
Try above code.
Output:
--> #
--> ##
--> ###
--> ####
--> #####
--> ######
To pass data from child component to parent component
In Parent Component:
getData(val){
// do not forget to bind getData in constructor
console.log(val);
}
render(){
return(<Child sendData={this.getData}/>);
}
In Child Component:
demoMethod(){
this.props.sendData(value);
}
For the website ensure that IIS HTTP response headers setting and add new key X-UA-Compatible pointing to "IE=edge"
If you have access to the server, the most reliable way of doing this is to do it on the server itself, in IIS. Go in to IIS HTTP Response Headers. Add Name: X-UA-Compatible Value: IE=edge This will override your browser and your code.
Based on what I've read, this is how it all works:
The general flow outlined in the question is correct. In step 2, User X is authenticated, and is also authorizing Site A's access to User X's information on Site B. In step 4, the site passes its Secret back to Site B, authenticating itself, as well as the Authorization Code, indicating what it's asking for (User X's access token).
Overall, OAuth 2 actually is a very simple security model, and encryption never comes directly into play. Instead, both the Secret and the Security Token are essentially passwords, and the whole thing is secured only by the security of the https connection.
OAuth 2 has no protection against replay attacks of the Security Token or the Secret. Instead, it relies entirely on Site B being responsible with these items and not letting them get out, and on them being sent over https while in transit (https will protect URL parameters).
The purpose of the Authorization Code step is simply convenience, and the Authorization Code is not especially sensitive on its own. It provides a common identifier for User X's access token for Site A when asking Site B for User X's access token. Just User X's user id on Site B would not have worked, because there could be many outstanding access tokens waiting to be handed out to different sites at the same time.
Sorting html table column on page load
var table = $('table#all_items_table');
var rows = table.find('tr:gt(0)').toArray().sort(comparer(3));
for (var i = 0; i < rows.length; i++) {
table.append(rows[i])
}
function comparer(index) {
return function (a, b) {
var v1= getCellValue(a, index),
v2= getCellValue(b, index);
return $.isNumeric(v2) && $.isNumeric(v1) ? v2 - v1: v2.localeCompare(v1)
}
}
function getCellValue(row, index) {
return parseFloat($(row).children('td').eq(index).html().replace(/,/g,'')); //1234234.45645->1234234
}
A simple way to do it would be to just annotate the Quartz Jobs with @Component
annotation, and then Spring will do all the DI magic for you, as it is now recognized as a Spring bean. I had to do something similar for an AspectJ
aspect - it was not a Spring bean until I annotated it with the Spring @Component
stereotype.
I am using Debian but this solution should work fine with Ubuntu.
You have to add a line in the neo4j-service script.
Here is what I have done :
nano /etc/init.d/neo4j-service
Add « ulimit –n 40000 » just before the start-stop-daemon line in the do_start section
Note that I am using version 2.0 Enterprise edition. Hope this will help you.
As I understand your question, you want to write some function y = interpolate(x_values, y_values, x)
, which will give you the y
value at some x
? The basic idea then follows these steps:
x_values
which define an interval containing x
. For instance, for x=3
with your example lists, the containing interval would be [x1,x2]=[2.5,3.4]
, and the indices would be i1=1
, i2=2
(y_values[i2]-y_values[i1])/(x_values[i2]-x_values[i1])
(ie dy/dx
).x
is now the value at x1
plus the slope multiplied by the distance from x1
.You will additionally need to decide what happens if x
is outside the interval of x_values
, either it's an error, or you could interpolate "backwards", assuming the slope is the same as the first/last interval.
Did this help, or did you need more specific advice?
This post helped me understand concerns.
# app/models/trader.rb
class Trader
include Shared::Schedule
end
# app/models/concerns/shared/schedule.rb
module Shared::Schedule
extend ActiveSupport::Concern
...
end
Goto SolutionExplorer (should be already visible, if not use menu: View->SolutionExplorer).
Find your .cxx file in the solution tree, right click on it and choose "Properties" from the popup menu. You will get window with your file's properties.
Using tree on the left side go to the "C++/Precompiled Headers" section. On the right side of the window you'll get three properties. Set property named "Create/Use Precompiled Header" to the value of "Not Using Precompiled Headers".
Emacs has comment-dwim (Do What I Mean) - just select the block and do a:
M-;
It's a toggle - use it to comment AND uncomment blocks.
If you don't have yaml-mode installed you will need to tell Emacs to use the hash character (#).
You haven't got your SUMIF
in the correct order - it needs to be range, criteria, sum range. Try:
=SUMIF(A:A,">="&DATE(2012,1,1),B:B)
I took yckart's answer and:
(If you put your scripts at the bottom of your page below the jQuery include you shouldn't need document ready)
jQuery:
<script>
$(".card-table-search").keyup(function() {
var value = this.value.toLowerCase().trim();
$(".card-table").find("tr").each(function(index) {
var id = $(this).find("td").first().text().toLowerCase().trim();
$(this).toggle(id.indexOf(value) !== -1);
});
});
</script>
If you want to extend this have it iterate over each 'td' and do this comparison.
This is a follow up to my original question to help out others with the same problem. If you need to filter by an attribute, rather than manually looking up the id you can use the following code to retrieve all the id, value pairs for an attribute. The data is returned as an array with the attribute name as the key.
function getAttributeOptions($attributeName) {
$product = Mage::getModel('catalog/product');
$collection = Mage::getResourceModel('eav/entity_attribute_collection')
->setEntityTypeFilter($product->getResource()->getTypeId())
->addFieldToFilter('attribute_code', $attributeName);
$_attribute = $collection->getFirstItem()->setEntity($product->getResource());
$attribute_options = $_attribute->getSource()->getAllOptions(false);
foreach($attribute_options as $val) {
$attrList[$val['label']] = $val['value'];
}
return $attrList;
}
Here is a function you can use to get products by their attribute set id. Retrieved using the previous function.
function getProductsByAttributeSetId($attributeSetId) {
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToFilter('attribute_set_id',$attributeSetId);
$products->addAttributeToSelect('*');
$products->load();
foreach($products as $val) {
$productsArray[] = $val->getData();
}
return $productsArray;
}
First of all, if anyone is going to store any password in a file, I would make sure it's hashed. It's not the best security, but at least it will not be in plain text.
First, create the password and hash it:
echo "password123" | md5sum | cut -d '-' -f 1 > /tmp/secret
Now, create your program to use the hash. In this case, this little program receives user input for a password without echoing, and then converts it to hash to be compared with the stored hash. If it matches the stored hash, then access is granted:
#!/bin/bash
PASSWORD_FILE="/tmp/secret"
MD5_HASH=$(cat /tmp/secret)
PASSWORD_WRONG=1
while [ $PASSWORD_WRONG -eq 1 ]
do
echo "Enter your password:"
read -s ENTERED_PASSWORD
if [ "$MD5_HASH" != "$(echo $ENTERED_PASSWORD | md5sum | cut -d '-' -f 1)" ]; then
echo "Access Deniend: Incorrenct password!. Try again"
else
echo "Access Granted"
PASSWORD_WRONG=0
fi
done
Type hints are for maintainability and don't get interpreted by Python. In the code below, the line def add(self, ic:int)
doesn't result in an error until the next return...
line:
class C1:
def __init__(self):
self.idn = 1
def add(self, ic: int):
return self.idn + ic
c1 = C1()
c1.add(2)
c1.add(c1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 5, in add
TypeError: unsupported operand type(s) for +: 'int' and 'C1'
Try this...
<string-array name="names">
<item></item>
<item>By Bus</item>
<item>By Train</item>
<item>By Van</item>
<item>By Bike</item>
</string-array>
String travel_type;
ArrayAdapter<String> myAdapter = new ArrayAdapter(AddNew_Trip.this,android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.names));
myAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
mySpinner.setAdapter(myAdapter);
mySpinner.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
travel_type = String.valueOf(adapterView.getItemAtPosition(i));
//Toast.makeText(Plan_Trip.this, travel_type, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
);
}
You have to prepend every directory with -I
:
INC=-I/usr/informix/incl/c++ -I/opt/informix/incl/public
I actually just resolved an issue I was having by swapping around the order that I was altering the properties in. For example I was changing the attribute first but I actually had to remove the class and add the new class before modifying the attributes. I'm not sure why it worked but it did. So something to try would be to change from $("XXXX").attr('something').removeClass( "class" ).addClass( "newClass" )
to $("XXXX").removeClass( "class" ).addClass( "newClass" ).attr('something')
.
The main concern is whether a variable inside the anonymous class instance can be resolved at run-time. It is not a must to make a variable final as long as it is guaranteed that the variable is inside the run-time scope. For example, please see the two variables _statusMessage and _statusTextView inside updateStatus() method.
public class WorkerService extends Service {
Worker _worker;
ExecutorService _executorService;
ScheduledExecutorService _scheduledStopService;
TextView _statusTextView;
@Override
public void onCreate() {
_worker = new Worker(this);
_worker.monitorGpsInBackground();
// To get a thread pool service containing merely one thread
_executorService = Executors.newSingleThreadExecutor();
// schedule something to run in the future
_scheduledStopService = Executors.newSingleThreadScheduledExecutor();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
ServiceRunnable runnable = new ServiceRunnable(this, startId);
_executorService.execute(runnable);
// the return value tells what the OS should
// do if this service is killed for resource reasons
// 1. START_STICKY: the OS restarts the service when resources become
// available by passing a null intent to onStartCommand
// 2. START_REDELIVER_INTENT: the OS restarts the service when resources
// become available by passing the last intent that was passed to the
// service before it was killed to onStartCommand
// 3. START_NOT_STICKY: just wait for next call to startService, no
// auto-restart
return Service.START_NOT_STICKY;
}
@Override
public void onDestroy() {
_worker.stopGpsMonitoring();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
class ServiceRunnable implements Runnable {
WorkerService _theService;
int _startId;
String _statusMessage;
public ServiceRunnable(WorkerService theService, int startId) {
_theService = theService;
_startId = startId;
}
@Override
public void run() {
_statusTextView = MyActivity.getActivityStatusView();
// get most recently available location as a latitude /
// longtitude
Location location = _worker.getLocation();
updateStatus("Starting");
// convert lat/lng to a human-readable address
String address = _worker.reverseGeocode(location);
updateStatus("Reverse geocoding");
// Write the location and address out to a file
_worker.save(location, address, "ResponsiveUx.out");
updateStatus("Done");
DelayedStopRequest stopRequest = new DelayedStopRequest(_theService, _startId);
// schedule a stopRequest after 10 seconds
_theService._scheduledStopService.schedule(stopRequest, 10, TimeUnit.SECONDS);
}
void updateStatus(String message) {
_statusMessage = message;
if (_statusTextView != null) {
_statusTextView.post(new Runnable() {
@Override
public void run() {
_statusTextView.setText(_statusMessage);
}
});
}
}
}
If you do not increase the height of navbar..
.navbar .brand {
position: fixed;
overflow: visible;
padding-left: 0;
padding-top: 0;
}
This is incredible but real.
csrf filter is enabled by default and it actually blocks any POST, PUT or DELETE requests which do not include de csrf token.
If this is so then allow any HTTP method:
@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
/**
* Allow POST, PUT or DELETE request
*
* NOTE: csrf filter is enabled by default and it actually blocks any POST, PUT or DELETE requests
* which do not include de csrf token.
*/
http.csrf().disable()
}
If you are obtaining a 401 the most intuitive thing is to think that in the request you have No Auth or you are missing something in the headers regarding authorization.
But apparently there is an internal function that is filtering the HTTP methods that use POST and returns a 401. After fixing it I thought it was a cache issue with the status code but apparently not.
GL
Why is this happening?
The entire ext/mysql
PHP extension, which provides all functions named with the prefix mysql_
, was officially deprecated in PHP v5.5.0 and removed in PHP v7.
It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.
The manual has contained warnings against its use in new code since June 2011.
How can I fix it?
As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql
. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.
They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.
Hashphp.org has an excellent tutorial on migrating from ext/mysql
to PDO.
I understand that it's possible to suppress deprecation errors by setting
error_reporting
inphp.ini
to excludeE_DEPRECATED
:error_reporting = E_ALL ^ E_DEPRECATED
What will happen if I do that?
Yes, it is possible to suppress such error messages and continue using the old ext/mysql
extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.
Note also that this technique will suppress all E_DEPRECATED
messages, not just those to do with the ext/mysql
extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @
—however this will suppress all errors raised by that expression, not just E_DEPRECATED
ones.
You are starting a new project.
There is absolutely no reason to use ext/mysql
—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.
You have (your own) legacy codebase that currently depends upon ext/mysql
.
It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.
Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.
Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.
The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.
Consider whether you really need to upgrade to PHP v5.5 at this time.
You should begin planning to replace ext/mysql
with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.
However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
You are using a third party project that depends upon ext/mysql
.
Consider whether you really need to upgrade to PHP v5.5 at this time.
Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
It is absolutely essential to perform regression testing.
I have recently migrated from C3P0
to HikariCP
in a Spring and Hibernate based project and it was not as easy as I had imagined and here I am sharing my findings.
For Spring Boot
see my answer here
I have the following setup
Some of the below configs are similar to some of the answers above but, there are differences.
In order to pull in the right jars, I needed to pull in the following jars
//latest driver because *brettw* see https://github.com/pgjdbc/pgjdbc/pull/849
compile 'org.postgresql:postgresql:42.2.0'
compile('com.zaxxer:HikariCP:2.7.6') {
//they are pulled in separately elsewhere
exclude group: 'org.hibernate', module: 'hibernate-core'
}
// Recommended to use HikariCPConnectionProvider by Hibernate in 4.3.6+
compile('org.hibernate:hibernate-hikaricp:4.3.8.Final') {
//they are pulled in separately elsewhere, to avoid version conflicts
exclude group: 'org.hibernate', module: 'hibernate-core'
exclude group: 'com.zaxxer', module: 'HikariCP'
}
// Needed for HikariCP logging if you use log4j
compile('org.slf4j:slf4j-simple:1.7.25')
compile('org.slf4j:slf4j-log4j12:1.7.25') {
//log4j pulled in separately, exclude to avoid version conflict
exclude group: 'log4j', module: 'log4j'
}
In order to get Spring & Hibernate to make use of Hikari Connection pool, you need to define the HikariDataSource
and feed it into sessionFactory
bean as shown below.
<!-- HikariCP Database bean -->
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<constructor-arg ref="hikariConfig" />
</bean>
<!-- HikariConfig config that is fed to above dataSource -->
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="SpringHikariPool" />
<property name="dataSourceClassName" value="org.postgresql.ds.PGSimpleDataSource" />
<property name="maximumPoolSize" value="20" />
<property name="idleTimeout" value="30000" />
<property name="dataSourceProperties">
<props>
<prop key="serverName">localhost</prop>
<prop key="portNumber">5432</prop>
<prop key="databaseName">dbname</prop>
<prop key="user">dbuser</prop>
<prop key="password">dbpassword</prop>
</props>
</property>
</bean>
<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
<!-- Your Hikari dataSource below -->
<property name="dataSource" ref="dataSource"/>
<!-- your other configs go here -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.connection.provider_class">org.hibernate.hikaricp.internal.HikariCPConnectionProvider</prop>
<!-- Remaining props goes here -->
</props>
</property>
</bean>
Once the above are setup then, you need to add an entry to your log4j or logback
and set the level
to DEBUG
to see Hikari
Connection Pool start up.
<!-- Keep additivity=false to avoid duplicate lines -->
<logger additivity="false" name="com.zaxxer.hikari">
<level value="debug"/>
<!-- Your appenders goes here -->
</logger>
Via application.properties
in Spring Boot
debug=true
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG
Using logback.xml
<logger name="com.zaxxer.hikari" level="DEBUG" additivity="false">
<appender-ref ref="STDOUT" />
</logger>
With the above you should be all good to go! Obviously you need to customize the HikariCP
pool configs in order to get the performance that it promises.
There is another way of performing the fit, which is by using the 'lmfit' package. It basically uses the cuve_fit but is much better in fitting and offers complex fitting as well. Detailed step by step instructions are given in the below link. http://cars9.uchicago.edu/software/python/lmfit/model.html#model.best_fit
var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item
Or can say whats fields not will expose with:
Gson gson = gsonBuilder.excludeFieldsWithModifiers(Modifier.TRANSIENT).create();
on your class on attribute:
private **transient** boolean nameAttribute;
You could use preg_split
instead of explode
and split on [ ]+
(one or more spaces). But I think in this case you could go with preg_match_all
and capturing:
preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];
The pattern matches a space, php
, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php
as part of a user name but really only as a command.
An alternative to capturing is the "keep" feature of PCRE. If you use \K
in the pattern, everything before it is discarded in the match:
preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];
I would use preg_match()
. I do something similar for many of my system management scripts. Here is an example:
$test = "user 12052 0.2 0.1 137184 13056 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user 12054 0.2 0.1 137184 13064 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user 12055 0.6 0.1 137844 14220 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user 12057 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user 12058 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user 12059 0.3 0.1 135112 13000 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root 12068 0.0 0.0 106088 1164 pts/1 S+ 10:00 0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root 12070 0.0 0.0 103240 828 pts/1 R+ 10:00 0:00 grep utilities";
$lines = explode("\n", $test);
foreach($lines as $line){
if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
print_r($matches);
}
}
The above prints:
Array
(
[0] => .php cust1 cron
[1] => cust1
)
Array
(
[0] => .php cust3 cron
[1] => cust3
)
Array
(
[0] => .php cust4 cron
[1] => cust4
)
Array
(
[0] => .php cust89 cron
[1] => cust89
)
Array
(
[0] => .php cust435 cron
[1] => cust435
)
Array
(
[0] => .php cust16 cron
[1] => cust16
)
You can set $test
to equal the output from exec. the values you are looking for would be in the if
statement under the foreach
. $matches[1]
will have the custx value.
Robi Code is work for me, just put if !null so that if phone number is null, user can fill the phone number by him/her self.
editTextPhoneNumber = (EditText) findViewById(R.id.editTextPhoneNumber);
TelephonyManager tMgr;
tMgr= (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
if (mPhoneNumber != null){
editTextPhoneNumber.setText(mPhoneNumber);
}
Can you try this,
echo date("Y-m-d H:i:s", 1388516401);
As noted by theGame,
This means that you pass in a string value for the time, and optionally a value for the current time, which is a UNIX timestamp. The value that is returned is an integer which is a UNIX timestamp.
echo strtotime("2014-01-01 00:00:01");
This will return into the value 1388516401, which is the UNIX timestamp for the date 2014-01-01. This can be confirmed using the date() function as like below:
echo date('Y-m-d', 1198148400); // echos 2014-01-01
we could open html file from linux/unix by using firefox .html
htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc.
Read from excel, modify and write back
/// <summary>
/// /Reads an excel file and converts it into dataset with each sheet as each table of the dataset
/// </summary>
/// <param name="filename"></param>
/// <param name="headers">If set to true the first row will be considered as headers</param>
/// <returns></returns>
public DataSet Import(string filename, bool headers = true)
{
var _xl = new Excel.Application();
var wb = _xl.Workbooks.Open(filename);
var sheets = wb.Sheets;
DataSet dataSet = null;
if (sheets != null && sheets.Count != 0)
{
dataSet = new DataSet();
foreach (var item in sheets)
{
var sheet = (Excel.Worksheet)item;
DataTable dt = null;
if (sheet != null)
{
dt = new DataTable();
var ColumnCount = ((Excel.Range)sheet.UsedRange.Rows[1, Type.Missing]).Columns.Count;
var rowCount = ((Excel.Range)sheet.UsedRange.Columns[1, Type.Missing]).Rows.Count;
for (int j = 0; j < ColumnCount; j++)
{
var cell = (Excel.Range)sheet.Cells[1, j + 1];
var column = new DataColumn(headers ? cell.Value : string.Empty);
dt.Columns.Add(column);
}
for (int i = 0; i < rowCount; i++)
{
var r = dt.NewRow();
for (int j = 0; j < ColumnCount; j++)
{
var cell = (Excel.Range)sheet.Cells[i + 1 + (headers ? 1 : 0), j + 1];
r[j] = cell.Value;
}
dt.Rows.Add(r);
}
}
dataSet.Tables.Add(dt);
}
}
_xl.Quit();
return dataSet;
}
public string Export(DataTable dt, bool headers = false)
{
var wb = _xl.Workbooks.Add();
var sheet = (Excel.Worksheet)wb.ActiveSheet;
//process columns
for (int i = 0; i < dt.Columns.Count; i++)
{
var col = dt.Columns[i];
//added columns to the top of sheet
var currentCell = (Excel.Range)sheet.Cells[1, i + 1];
currentCell.Value = col.ToString();
currentCell.Font.Bold = true;
//process rows
for (int j = 0; j < dt.Rows.Count; j++)
{
var row = dt.Rows[j];
//added rows to sheet
var cell = (Excel.Range)sheet.Cells[j + 1 + 1, i + 1];
cell.Value = row[i];
}
currentCell.EntireColumn.AutoFit();
}
var fileName="{somepath/somefile.xlsx}";
wb.SaveCopyAs(fileName);
_xl.Quit();
return fileName;
}
Just iterate over the transposed of your array:
for column in array.T:
some_function(column)
You can check scrollHeight and clientHeight with scrollTop to scroll to bottom of div like code below.
$('#div').scroll(function (event) {_x000D_
if ((parseInt($('#div')[0].scrollHeight) - parseInt(this.clientHeight)) == parseInt($('#div').scrollTop())) _x000D_
{_x000D_
console.log("this is scroll bottom of div");_x000D_
}_x000D_
_x000D_
});
_x000D_
Simple test, accessing http://localhost:8000/hello?foo=bar#this-is-not-sent-to-server
python -c "import SimpleHTTPServer;SimpleHTTPServer.test()"
Serving HTTP on 0.0.0.0 port 8000 ...
localhost - - [02/Jun/2009 12:48:47] code 404, message File not found
localhost - - [02/Jun/2009 12:48:47] "GET /hello?foo=bar HTTP/1.1" 404 -
The server receives the request without the #appendage - anything after the hash tag is simply an anchor lookup on the client.
You can find the anchor name used within the URL via javascript using, as an example:
<script>alert(window.location.hash);</script>
The parse_url() function in PHP can work if you already have the needed URL string including the fragment (http://codepad.org/BDqjtXix):
<?
echo parse_url("http://foo?bar#fizzbuzz",PHP_URL_FRAGMENT);
?>
Output: fizzbuzz
But I don't think PHP receives the fragment information because it's client-only.
.card-img-top {
width: 100%;
height: 40vh;
object-fit: cover;
}
As shown above but when you add height i suggest using "vh" (Viewport Height units) for a more mobile-friendly experience.
If you just want to apply a function to each element and put the results in an output array, you can use arrayfun
.
As others have pointed out, for most operations, it's best to avoid loops in MATLAB and vectorise your code instead.
If I move
CreateUser.py
to the main user_management directory, I can easily use:import Modules.LDAPManager
to importLDAPManager.py
--- this works.
Please, don't. In this way the LDAPManager
module used by CreateUser
will not be the same as the one imported via other imports. This can create problems when you have some global state in the module or during pickling/unpickling. Avoid imports that work only because the module happens to be in the same directory.
When you have a package structure you should either:
Use relative imports, i.e if the CreateUser.py
is in Scripts/
:
from ..Modules import LDAPManager
Note that this was (note the past tense) discouraged by PEP 8 only because old versions of python didn't support them very well, but this problem was solved years ago. The current version of PEP 8 does suggest them as an acceptable alternative to absolute imports. I actually like them inside packages.
Use absolute imports using the whole package name(CreateUser.py
in Scripts/
):
from user_management.Modules import LDAPManager
In order for the second one to work the package user_management
should be installed inside the PYTHONPATH
. During development you can configure the IDE so that this happens, without having to manually add calls to sys.path.append
anywhere.
Also I find it odd that Scripts/
is a subpackage. Because in a real installation the user_management
module would be installed under the site-packages
found in the lib/
directory (whichever directory is used to install libraries in your OS), while the scripts should be installed under a bin/
directory (whichever contains executables for your OS).
In fact I believe Script/
shouldn't even be under user_management
. It should be at the same level of user_management
.
In this way you do not have to use -m
, but you simply have to make sure the package can be found (this again is a matter of configuring the IDE, installing the package correctly or using PYTHONPATH=. python Scripts/CreateUser.py
to launch the scripts with the correct path).
In summary, the hierarchy I would use is:
user_management (package)
|
|------- __init__.py
|
|------- Modules/
| |
| |----- __init__.py
| |----- LDAPManager.py
| |----- PasswordManager.py
|
Scripts/ (*not* a package)
|
|----- CreateUser.py
|----- FindUser.py
Then the code of CreateUser.py
and FindUser.py
should use absolute imports to import the modules:
from user_management.Modules import LDAPManager
During installation you make sure that user_management
ends up somewhere in the PYTHONPATH
, and the scripts inside the directory for executables so that they are able to find the modules. During development you either rely on IDE configuration, or you launch CreateUser.py
adding the Scripts/
parent directory to the PYTHONPATH
(I mean the directory that contains both user_management
and Scripts
):
PYTHONPATH=/the/parent/directory python Scripts/CreateUser.py
Or you can modify the PYTHONPATH
globally so that you don't have to specify this each time. On unix OSes (linux, Mac OS X etc.) you can modify one of the shell scripts to define the PYTHONPATH
external variable, on Windows you have to change the environmental variables settings.
Addendum I believe, if you are using python2, it's better to make sure to avoid implicit relative imports by putting:
from __future__ import absolute_import
at the top of your modules. In this way import X
always means to import the toplevel module X
and will never try to import the X.py
file that's in the same directory (if that directory isn't in the PYTHONPATH
). In this way the only way to do a relative import is to use the explicit syntax (the from . import X
), which is better (explicit is better than implicit).
This will make sure you never happen to use the "bogus" implicit relative imports, since these would raise an ImportError
clearly signalling that something is wrong. Otherwise you could use a module that's not what you think it is.
You can simply use this code at the end. (Do not use False)
Application.CutCopyMode = True
A robust way to check if an object is an array in javascript is detailed here:
Here are two functions from the xa.js framework which I attach to a utils = {}
‘container’. These should help you properly detect arrays.
var utils = {};
/**
* utils.isArray
*
* Best guess if object is an array.
*/
utils.isArray = function(obj) {
// do an instanceof check first
if (obj instanceof Array) {
return true;
}
// then check for obvious falses
if (typeof obj !== 'object') {
return false;
}
if (utils.type(obj) === 'array') {
return true;
}
return false;
};
/**
* utils.type
*
* Attempt to ascertain actual object type.
*/
utils.type = function(obj) {
if (obj === null || typeof obj === 'undefined') {
return String (obj);
}
return Object.prototype.toString.call(obj)
.replace(/\[object ([a-zA-Z]+)\]/, '$1').toLowerCase();
};
If you then want to check if an object is in an array, I would also include this code:
/**
* Adding hasOwnProperty method if needed.
*/
if (typeof Object.prototype.hasOwnProperty !== 'function') {
Object.prototype.hasOwnProperty = function (prop) {
var type = utils.type(this);
type = type.charAt(0).toUpperCase() + type.substr(1);
return this[prop] !== undefined
&& this[prop] !== window[type].prototype[prop];
};
}
And finally this in_array function:
function in_array (needle, haystack, strict) {
var key;
if (strict) {
for (key in haystack) {
if (!haystack.hasOwnProperty[key]) continue;
if (haystack[key] === needle) {
return true;
}
}
} else {
for (key in haystack) {
if (!haystack.hasOwnProperty[key]) continue;
if (haystack[key] == needle) {
return true;
}
}
}
return false;
}
The PIL distribution is mispackaged for egg installation.
Install Pillow instead, the friendly PIL fork.
IPython intercepts those, they're called built-in magic commands, here's the list: https://ipython.org/ipython-doc/dev/interactive/magics.html
You can also create your own custom magics, https://ipython.org/ipython-doc/dev/config/custommagics.html
Your timeit
is here https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit
Please to solve this problem we just have set installed JDK path in
standalone.conf
file which under the bin folder of JBoss\Wildfly Server. To solve this we do the following steps:
Yes you can: Take this utility function that I have written today:
function shangMergeCol() {
tcol= db.getCollection(arguments[0]);
for (var i=1; i<arguments.length; i++){
scol= db.getCollection(arguments[i]);
scol.find().forEach(
function (d) {
tcol.insert(d);
}
)
}
}
You can pass to this function any number of collections, the first one is going to be the target one. All the rest collections are sources to be transferred to the target one.
You simply can't use View as a Header of ListView.
Because the view which is being passed in has to be inflated.
Look at my answer at Android ListView addHeaderView() nullPointerException for predefined Views for more info.
EDIT:
Look at this tutorial Android ListView and ListActivity - Tutorial .
EDIT 2: This link is broken Android ListActivity with a header or footer
Exact syntax will of course depend upon database, but something like:
SELECT * FROM my_table WHERE (filename, Dates) IN (SELECT filename, Max(Dates) FROM my_table GROUP BY filename)
This will give you results exactly what you are asking for and displaying above. Fiddle: http://www.sqlfiddle.com/#!2/3af8a/1/0
Make sure that st_new.sh does something at the end what you can recognize (like touch /tmp/st_new.tmp when you remove the file first and always start one instance of st_new.sh).
Then make a polling loop. First sleep the normal time you think you should wait,
and wait short time in every loop.
This will result in something like
max_retry=20
retry=0
sleep 10 # Minimum time for st_new.sh to finish
while [ ${retry} -lt ${max_retry} ]; do
if [ -f /tmp/st_new.tmp ]; then
break # call results.sh outside loop
else
(( retry = retry + 1 ))
sleep 1
fi
done
if [ -f /tmp/st_new.tmp ]; then
source ../../results.sh
rm -f /tmp/st_new.tmp
else
echo Something wrong with st_new.sh
fi
I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).
If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::
.
Something along these lines:
create view view1
as
select table1.col1,table2.col1,table3.col3
from table1
inner join
table2
inner join
table3
on
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;
Notice the varchar
typecasting on the table1.col4.
Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.
Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).
The are various ways:
$ echo "$a" | tr '[:upper:]' '[:lower:]'
hi all
$ echo "$a" | awk '{print tolower($0)}'
hi all
You may run into portability issues with the following examples:
$ echo "${a,,}"
hi all
$ echo "$a" | sed -e 's/\(.*\)/\L\1/'
hi all
# this also works:
$ sed -e 's/\(.*\)/\L\1/' <<< "$a"
hi all
$ echo "$a" | perl -ne 'print lc'
hi all
lc(){
case "$1" in
[A-Z])
n=$(printf "%d" "'$1")
n=$((n+32))
printf \\$(printf "%o" "$n")
;;
*)
printf "%s" "$1"
;;
esac
}
word="I Love Bash"
for((i=0;i<${#word};i++))
do
ch="${word:$i:1}"
lc "$ch"
done
Note: YMMV on this one. Doesn't work for me (GNU bash version 4.2.46 and 4.0.33 (and same behaviour 2.05b.0 but nocasematch is not implemented)) even with using shopt -u nocasematch;
. Unsetting that nocasematch causes [[ "fooBaR" == "FOObar" ]] to match OK BUT inside case weirdly [b-z] are incorrectly matched by [A-Z]. Bash is confused by the double-negative ("unsetting nocasematch")! :-)
package main
import (
"fmt"
"strings"
)
func main() {
strs := strings.Split("127.0.0.1:5432", ":")
ip := strs[0]
port := strs[1]
fmt.Println(ip, port)
}
Here is the definition for strings.Split
// Split slices s into all substrings separated by sep and returns a slice of
// the substrings between those separators.
//
// If s does not contain sep and sep is not empty, Split returns a
// slice of length 1 whose only element is s.
//
// If sep is empty, Split splits after each UTF-8 sequence. If both s
// and sep are empty, Split returns an empty slice.
//
// It is equivalent to SplitN with a count of -1.
func Split(s, sep string) []string { return genSplit(s, sep, 0, -1) }
wsExists
function (without reliance on Error Handling!)Here's a short & simple function that doesn't rely on error handling to determine whether a worksheet exists (and is properly declared to work in any situation!)
Function wsExists(wsName As String) As Boolean
Dim ws: For Each ws In Sheets
wsExists = (wsName = ws.Name): If wsExists Then Exit Function
Next ws
End Function
The following example adds a new worksheet named myNewSheet
, if it doesn't already exist:
If Not wsExists("myNewSheet") Then Sheets.Add.Name = "myNewSheet"
For Each
…Next
Statement (VBA)Exit
Statement (VBA) You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the ${}
things) in JSP to access/display them. You can put JSP files in /WEB-INF
folder to prevent users from directly accessing them without invoking the preprocessing servlet.
Kickoff example:
@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "Hello World";
request.setAttribute("message", message); // This will be available as ${message}
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
}
And /WEB-INF/hello.jsp
look like:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: ${message}</p>
</body>
</html>
When opening http://localhost:8080/contextpath/hello this will show
Message: Hello World
in the browser.
This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.
Also browse the "Frequent" tab of all questions tagged [servlets] to find frequently asked questions.
For your specific data, you can use
Select col1, col2, LTRIM(RTRIM(SUBSTRING(
STUFF(col3, CHARINDEX('|', col3,
PATINDEX('%|Client Name =%', col3) + 14), 1000, ''),
PATINDEX('%|Client Name =%', col3) + 14, 1000))) col3
from Table01
Test
select col3='Clent ID = 4356hy|Client Name = B B BOB|Client Phone = 667-444-2626|Client Fax = 666-666-0151|Info = INF8888877 -MAC333330554/444400800'
into t1m
from master..spt_values a
cross join master..spt_values b
where a.number < 100
-- (711704 row(s) affected)
set statistics time on
dbcc dropcleanbuffers
dbcc freeproccache
select a=CHARINDEX('|Client Name =', col3) into #tmp1 from t1m
drop table #tmp1
dbcc dropcleanbuffers
dbcc freeproccache
select a=PATINDEX('%|Client Name =%', col3) into #tmp2 from t1m
drop table #tmp2
set statistics time off
Timings
CHARINDEX:
SQL Server Execution Times (1):
CPU time = 5656 ms, elapsed time = 6418 ms.
SQL Server Execution Times (2):
CPU time = 5813 ms, elapsed time = 6114 ms.
SQL Server Execution Times (3):
CPU time = 5672 ms, elapsed time = 6108 ms.
PATINDEX:
SQL Server Execution Times (1):
CPU time = 5906 ms, elapsed time = 6296 ms.
SQL Server Execution Times (2):
CPU time = 5860 ms, elapsed time = 6404 ms.
SQL Server Execution Times (3):
CPU time = 6109 ms, elapsed time = 6301 ms.
Conclusion
The timings for CharIndex and PatIndex for 700k calls are within 3.5% of each other, so I don't think it would matter whichever is used. I use them interchangeably when both can work.
No, the @jmlane answer is wrong.
Checkin (git add, git commit)
:text
property is Set, Set value to 'auto'
, the conversion happens enen the file has been committed with 'CRLF'text
property is Unset
:nothing happens, enen for Checkout
text
property is Unspecified
, conversion depends on core.autocrlf
autocrlf = input or autocrlf = true
, the conversion only happens when the file in the repository is 'LF', if it has been 'CRLF', nothing will happens.autocrlf = false
, nothing happensCheckout
:text
property is Unset
: nothing happens.text
property is Set, Set value to 'auto
: it depends on core.autocrlf
, core.eol
.
core.eol
text
property is Unspecified
, it depends on core.autocrlf
.
2.1
2.2
text
property is Unspecified
So the Default behavior is text
property is Unspecified
and core.autocrlf = false
:
text
property is set, checkin behavior is depends on itself, not on autocrlfIt's and old post, but it's new for me. So, it is straight forward! In this part of the code:
public boolean onNavigationItemSelected(MenuItem item) {
} , I bound an ImageView to the LinearLayout, which contains the ImageView from the example, listed below. Mind: it's the same code you get when you start a new project, and choose the template "Navigation Drawer Activity":
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:src="@android:drawable/sym_def_app_icon" />
I gave the LinearLayout and ID, inside nav_header_main.xml (in my case I chose 'navigation_header_container' , so it went this way:
LinearLayout lV = (LinearLayout) findViewById(R.id.navigation_header_container);
ivCloseDrawer = (ImageView) lV.findViewById(R.id.imageView);
ivCloseDrawer.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
drawer.closeDrawer(GravityCompat.START);
}
});
Note: I have a private ImageView ivCloseDrawer declared at the top, before onCreate (MainActivity).
It worked fine! Hope it helps, Best Regards.
There are two types in this parsing.
From a file, you can use the following
import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']
This arcticle explains the full parsing and getting values using two scenarios.Parsing JSON using Python
You can also use the special word like
:
Public Sub Search()
If "My Big String with, in the middle" Like "*,*" Then
Debug.Print ("Found ','")
End If
End Sub
public static String clobToString(final Clob clob) throws SQLException, IOException {
try (final Reader reader = clob.getCharacterStream()) {
try (final StringWriter stringWriter = new StringWriter()) {
IOUtils.copy(reader, stringWriter);
return stringWriter.toString();
}
}
}
You're so close!
Change
plot "print_1012720" using 1:2 title "Flow 1", \
plot "print_1058167" using 1:2 title "Flow 2", \
plot "print_193548" using 1:2 title "Flow 3", \
plot "print_401125" using 1:2 title "Flow 4", \
plot "print_401275" using 1:2 title "Flow 5", \
plot "print_401276" using 1:2 title "Flow 6"
to
plot "print_1012720" using 1:2 title "Flow 1", \
"print_1058167" using 1:2 title "Flow 2", \
"print_193548" using 1:2 title "Flow 3", \
"print_401125" using 1:2 title "Flow 4", \
"print_401275" using 1:2 title "Flow 5", \
"print_401276" using 1:2 title "Flow 6"
The error arises because gnuplot is trying to interpret the word "plot" as the filename to plot, but you haven't assigned any strings to a variable named "plot" (which is good – that would be super confusing).
Only one column version
df[column_name].fillna(method='ffill', inplace=True)
df[column_name].fillna(method='backfill', inplace=True)
This simple trick works: Copy and Paste. Do NOT cut and paste. After you paste, then reselect the part you copied and go to EDIT, slide down to CLEAR, and CLEAR CONTENTS.
If you haven't already pushed the commits then you can go back to a previous commit using git reset HEAD^[1,2,3,4...]
For example
git commit <file1> -m "Updated files 1 and 2"
git commit <file3> -m "Updated file 3"
Oops, forgot to add file2 to the first commit...
git reset HEAD^1 // because I only need to go back 1 commit
git add <file2>
This will add file2 to the first commit.
Just leaving the way using Microsoft.AspNet.WebApi.Client
here.
Example:
var client = HttpClientFactory.Create();
var result = await client.PostAsync<ExampleClass>("http://www.sample.com/write", new ExampleClass(), new JsonMediaTypeFormatter());
You can use the LocalForward
directive in your host yam
section of ~/.ssh/config
:
LocalForward 5901 computer.myHost.edu:5901
The jQuery docs for text()
says
Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.
I'd use $td.html()
instead.
You can also use this
document.querySelector('yourId').innerHTML = 'Content';